repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
Pagejects/pagejects-integration
pagejects-guice/src/main/kotlin/net/pagejects/guice/PagejectsModule.kt
1
1567
package net.pagejects.guice import com.google.inject.AbstractModule import com.google.inject.Provider import net.pagejects.core.PagejectsManager import net.pagejects.core.annotation.PageObject import net.pagejects.core.annotation.PublicAPI import net.pagejects.core.impl.PageObjectCache import org.reflections.Reflections /** * Guice module for Pagejects * * This module will bind all interfaces from package `packageName` that annotated by [PageObject] * * @author Andrey Paslavsky * @since 0.1 * @constructor Please take attention: all implementations should have public constructor without parameters * @param packageName This package name will be used to locate Page Objects that should be bound to the Guice */ @PublicAPI abstract class PagejectsModule(private val packageName: String) : AbstractModule() { /** * See [AbstractModule.configure] */ final override fun configure() { configure(PagejectsManager.instance) Reflections(packageName).getTypesAnnotatedWith(PageObject::class.java).forEach { bindPageObject(it) } } /** * This method using to setup Pagejects before load Page Objects * * @param pagejectsManager [PagejectsManager] provides set of methods to configure Pagejects */ @PublicAPI abstract fun configure(pagejectsManager: PagejectsManager): Unit @Suppress("UNCHECKED_CAST") private fun <T : Any> bindPageObject(pageObjectClass: Class<T>) { bind(pageObjectClass).toProvider(Provider { PageObjectCache[pageObjectClass] }) } }
apache-2.0
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/ui/AdvancedPropertyTab.kt
1
2562
package wu.seal.jsontokotlin.ui import com.intellij.util.ui.JBDimension import wu.seal.jsontokotlin.model.ConfigManager import wu.seal.jsontokotlin.model.DefaultValueStrategy import wu.seal.jsontokotlin.model.PropertyTypeStrategy import java.awt.BorderLayout import javax.swing.JPanel /** * * Created by Seal.Wu on 2018/2/7. */ class AdvancedPropertyTab(isDoubleBuffered: Boolean) : JPanel(BorderLayout(), isDoubleBuffered) { init { jScrollPanel(JBDimension(500, 300)) { jVerticalLinearLayout { jLabel("Keyword") jButtonGroup { jRadioButton("Val", !ConfigManager.isPropertiesVar, { ConfigManager.isPropertiesVar = false }) jRadioButton("Var", ConfigManager.isPropertiesVar, { ConfigManager.isPropertiesVar = true }) } jLine() jLabel("Type") jButtonGroup { jRadioButton("Non-Nullable", ConfigManager.propertyTypeStrategy == PropertyTypeStrategy.NotNullable, { ConfigManager.propertyTypeStrategy = PropertyTypeStrategy.NotNullable }) jRadioButton("Nullable", ConfigManager.propertyTypeStrategy == PropertyTypeStrategy.Nullable, { ConfigManager.propertyTypeStrategy = PropertyTypeStrategy.Nullable }) jRadioButton("Auto Determine Nullable Or Not From JSON Value", ConfigManager.propertyTypeStrategy == PropertyTypeStrategy.AutoDeterMineNullableOrNot, { ConfigManager.propertyTypeStrategy = PropertyTypeStrategy.AutoDeterMineNullableOrNot }) } jLine() jLabel("Default Value Strategy") jButtonGroup { jRadioButton("Don't Init With Default Value", ConfigManager.defaultValueStrategy == DefaultValueStrategy.None, { ConfigManager.defaultValueStrategy = DefaultValueStrategy.None }) jRadioButton("Init With Non-Null Default Value (Avoid Null)", ConfigManager.defaultValueStrategy == DefaultValueStrategy.AvoidNull, { ConfigManager.defaultValueStrategy = DefaultValueStrategy.AvoidNull }) jRadioButton("Init With Default Value Null When Property Is Nullable", ConfigManager.defaultValueStrategy == DefaultValueStrategy.AllowNull, { ConfigManager.defaultValueStrategy = DefaultValueStrategy.AllowNull }) } } } } }
gpl-3.0
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt
2
1142
package eu.kanade.tachiyomi.source.model import java.io.Serializable interface SManga : Serializable { var url: String var title: String var artist: String? var author: String? var description: String? var genre: String? var status: Int var thumbnail_url: String? var initialized: Boolean fun copyFrom(other: SManga) { if (other.author != null) author = other.author if (other.artist != null) artist = other.artist if (other.description != null) description = other.description if (other.genre != null) genre = other.genre if (other.thumbnail_url != null) thumbnail_url = other.thumbnail_url status = other.status if (!initialized) initialized = other.initialized } companion object { const val UNKNOWN = 0 const val ONGOING = 1 const val COMPLETED = 2 const val LICENSED = 3 fun create(): SManga { return SMangaImpl() } } }
apache-2.0
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/serializers/OrganizationExternalDatabaseTableStreamSerializer.kt
1
2078
package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.organization.OrganizationExternalDatabaseTable import org.springframework.stereotype.Component import java.util.* @Component class OrganizationExternalDatabaseTableStreamSerializer : SelfRegisteringStreamSerializer<OrganizationExternalDatabaseTable> { companion object { fun serialize(output: ObjectDataOutput, obj: OrganizationExternalDatabaseTable) { UUIDStreamSerializerUtils.serialize(output, obj.id) output.writeUTF(obj.name) output.writeUTF(obj.title) output.writeUTF(obj.description) UUIDStreamSerializerUtils.serialize(output, obj.organizationId) output.writeInt(obj.oid) } fun deserialize(input: ObjectDataInput): OrganizationExternalDatabaseTable { val id = UUIDStreamSerializerUtils.deserialize(input) val name = input.readUTF() val title = input.readUTF() val description = input.readUTF() val orgId = UUIDStreamSerializerUtils.deserialize(input) val oid = input.readInt(); return OrganizationExternalDatabaseTable(id, name, title, Optional.of(description), orgId, oid) } } override fun write(output: ObjectDataOutput, obj: OrganizationExternalDatabaseTable) { serialize(output, obj) } override fun read(input: ObjectDataInput): OrganizationExternalDatabaseTable { return deserialize(input) } override fun getClazz(): Class<out OrganizationExternalDatabaseTable> { return OrganizationExternalDatabaseTable::class.java } override fun getTypeId(): Int { return StreamSerializerTypeIds.ORGANIZATION_EXTERNAL_DATABASE_TABLE.ordinal } }
gpl-3.0
dataloom/conductor-client
src/test/kotlin/com/openlattice/hazelcast/serializers/EntitySetAssemblyKeyStreamSerializerTest.kt
1
1405
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.hazelcast.serializers import com.kryptnostic.rhizome.hazelcast.serializers.AbstractStreamSerializerTest import com.openlattice.assembler.EntitySetAssemblyKey import java.util.UUID class EntitySetAssemblyKeyStreamSerializerTest : AbstractStreamSerializerTest<EntitySetAssemblyKeyStreamSerializer, EntitySetAssemblyKey>() { override fun createSerializer(): EntitySetAssemblyKeyStreamSerializer { return EntitySetAssemblyKeyStreamSerializer() } override fun createInput(): EntitySetAssemblyKey { return EntitySetAssemblyKey(UUID.randomUUID(), UUID.randomUUID()) } }
gpl-3.0
MeilCli/HKJson
hkjson/src/main/kotlin/net/meilcli/hkjson/objects/LongJson.kt
1
389
package net.meilcli.hkjson.objects class LongJson { companion object { val optional = LongOptionalJson.Companion val array = LongArrayJson.Companion } } class LongOptionalJson { companion object } class LongArrayJson { companion object { val optional = LongArrayOptionalJson.Companion } } class LongArrayOptionalJson { companion object }
mit
msebire/intellij-community
plugins/stats-collector/src/com/intellij/completion/NotificationManager.kt
3
1811
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.reporting.isSendAllowed class NotificationManager : StartupActivity { companion object { private const val PLUGIN_NAME = "Completion Stats Collector" private const val MESSAGE_TEXT = "Data about your code completion usage will be anonymously reported. " + "No personal data or code will be sent." private const val MESSAGE_TEXT_EAP = "$MESSAGE_TEXT This is only enabled in EAP builds." private const val MESSAGE_SHOWN_KEY = "completion.stats.allow.message.shown" } private fun isMessageShown() = PropertiesComponent.getInstance().getBoolean(MESSAGE_SHOWN_KEY, false) private fun setMessageShown(value: Boolean) = PropertiesComponent.getInstance().setValue(MESSAGE_SHOWN_KEY, value) override fun runActivity(project: Project) { if (ApplicationManager.getApplication().isUnitTestMode) { return } // Show message in EAP build or if additional plugin installed if (!isMessageShown() && isSendAllowed()) { notify(project) setMessageShown(true) } } private fun notify(project: Project) { val messageText = if (ApplicationManager.getApplication().isEAP) MESSAGE_TEXT_EAP else MESSAGE_TEXT val notification = Notification(PLUGIN_NAME, PLUGIN_NAME, messageText, NotificationType.INFORMATION) notification.notify(project) } }
apache-2.0
mg6maciej/SafetyNetExample
Server/src/main/kotlin/pl/mg6/safetynet/Application.kt
1
279
package pl.mg6.safetynet import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class Application fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) }
mit
Bodo1981/swapi.co
app/src/main/java/com/christianbahl/swapico/list/delegates/TextDelegate.kt
1
1699
package com.christianbahl.swapico.list.delegates import android.content.Context import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.christianbahl.swapico.R import com.christianbahl.swapico.base.BaseDelegate import com.christianbahl.swapico.list.model.ListItem import com.christianbahl.swapico.list.model.ListItemType import kotlinx.android.synthetic.main.row_single_text.view.* import org.jetbrains.anko.onClick /** * @author Christian Bahl */ class TextDelegate(viewType: Int, context: Context, val callback: (detailsId: Int) -> Unit) : BaseDelegate<List<ListItem>>(viewType, context) { override fun onCreateViewHolder(parent: ViewGroup?) = FilmViewHolder(inflater.inflate(R.layout.row_single_text, parent, false), callback) override fun isForViewType(items: List<ListItem>?, position: Int) = items?.get(position)?.type == ListItemType.TEXT override fun onBindViewHolder(items: List<ListItem>?, position: Int, viewHolder: RecyclerView.ViewHolder?) { (viewHolder as FilmViewHolder).bindView(items?.get(position)) } class FilmViewHolder(itemView: View, val callback: (detailsId: Int) -> Unit) : RecyclerView.ViewHolder(itemView) { public fun bindView(listItem: ListItem?) { itemView.row_single_text_text.text = listItem?.text if (listItem != null && listItem.url.isNotBlank()) { itemView.onClick { callback(pathId(listItem.url)) } } } private fun pathId(url: String): Int { val fixedUrl = if (url.endsWith("/")) url.substring(0, url.length - 1) else url val urlSplit = fixedUrl.split("/") return urlSplit[urlSplit.size - 1].toInt() } } }
apache-2.0
yamamotoj/workshop-jb
src/syntax/ifWhenExpressions.kt
55
737
package syntax.ifWhenExpressions fun ifExpression(a: Int, b: Int) { val max1 = if (a > b) a else b val max2 = if (a > b) { println("Choose a") a } else { println("Choose b") b } } fun whenExpression(a: Any?) { val result = when (a) { null -> "null" is String -> "String" is Any -> "Any" else -> "Don't know" } } fun whenExpression(x: Int) { when (x) { 0, 11 -> "0 or 11" in 1..10 -> "from 1 to 10" !in 12..14 -> "not from 12 to 14" else -> "otherwise" } } fun whenWithoutArgument(x: Int) { when { x == 42 -> "x is 42" x % 2 == 1 -> "x is odd" else -> "otherwise" } }
mit
wisnia/Videooo
app/src/main/kotlin/com/wisnia/videooo/splashscreen/SplashScreenActivity.kt
2
967
package com.wisnia.videooo.splashscreen import android.content.Intent import android.os.Bundle import com.wisnia.videooo.login.LoginActivity import com.wisnia.videooo.mvp.PresentationActivity import com.wisnia.videooo.mvp.Presenter import com.wisnia.videooo.splashscreen.presentation.SplashScreenPresenter import com.wisnia.videooo.splashscreen.view.SplashScreenView import dagger.android.AndroidInjection import javax.inject.Inject class SplashScreenActivity : PresentationActivity<SplashScreenView>(), SplashScreenView { @Inject lateinit var presenter: SplashScreenPresenter override fun getPresenter(): Presenter<SplashScreenView> = presenter override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) } override fun showLoginScreen() { Intent(this, LoginActivity::class.java).let { startActivity(it) finish() } } }
apache-2.0
kotlin-es/kotlin-JFrame-standalone
03-start-async-message-application/src/main/kotlin/components/progressBar/ProgressBarImpl.kt
3
1023
package components.progressBar import utils.ThreadMain import java.awt.Component import java.util.concurrent.CompletableFuture import javax.swing.JProgressBar /** * Created by vicboma on 05/12/16. */ class ProgressBarImpl internal constructor(val min: Int, val max: Int) : JProgressBar(min,max) , ProgressBar { companion object { fun create(min: Int, max: Int): ProgressBar { return ProgressBarImpl(min,max) } } init{ value = 0 isStringPainted = true setAlignmentX(Component.CENTER_ALIGNMENT) } override fun asyncUI() { ThreadMain.asyncUI { CompletableFuture.runAsync { for (i in min..max) { Thread.sleep(30) value = i * 1 } }.thenAcceptAsync { Thread.sleep(500) value = 0 asyncUI() } } } override fun component() : JProgressBar { return this } }
mit
hschroedl/FluentAST
core/src/test/kotlin/at.hschroedl.fluentast/ast/expression/ArrayTest.kt
1
2128
package at.hschroedl.fluentast.ast.expression import at.hschroedl.fluentast.arrayInit import at.hschroedl.fluentast.ast.type.FluentArrayType import at.hschroedl.fluentast.i import at.hschroedl.fluentast.newArray import at.hschroedl.fluentast.test.dummyExpression import at.hschroedl.fluentast.test.dummyLiteral import at.hschroedl.fluentast.test.dummyType import at.hschroedl.fluentast.test.toInlineString import org.eclipse.jdt.core.dom.ArrayAccess import org.eclipse.jdt.core.dom.ArrayCreation import org.eclipse.jdt.core.dom.ArrayInitializer import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class ArrayTest { @Test internal fun arrayAccess_withExpressions_returnsArrayAccessWithExpressions() { val expression = dummyExpression("test").index(dummyLiteral(1)).build() as ArrayAccess assertEquals("test[1]", expression.toInlineString()) } @Test internal fun arrayInitializer_withNumbers_returnsArrayInitializerWithNumbers() { val expression = arrayInit(dummyLiteral(1), dummyLiteral(2), dummyLiteral(3)).build() as ArrayInitializer assertEquals("{1,2,3}", expression.toInlineString()) } @Test internal fun arrayInitializer_withNestedInitializers_returnsArrayInitializerWithNumbers() { val expression = arrayInit(dummyLiteral(1), FluentArrayInitializer( dummyLiteral(2), dummyLiteral(3))).build() as ArrayInitializer assertEquals("{1,{2,3}}", expression.toInlineString()) } @Test internal fun arrayCreation_withType_returnsArrayCreation() { val expression = newArray(FluentArrayType(dummyType("Integer"), 3)).build() as ArrayCreation assertEquals("new Integer[][][]", expression.toInlineString()) } @Test internal fun arrayCreation_withInitializer_returnsArrayCreation() { val expression = newArray(FluentArrayType(dummyType("Integer"), 3), arrayInit( i(1), i(2))).build() as ArrayCreation assertEquals("new Integer[][][]{1,2}", expression.toInlineString()) } }
apache-2.0
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/fragments/Screen.kt
1
402
package lt.vilnius.tvarkau.fragments import android.support.annotation.StringRes @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Screen( @StringRes val titleRes: Int = 0, val navigationMode: NavigationMode = NavigationMode.DEFAULT, val trackingScreenName: String = "" ) enum class NavigationMode { DEFAULT, CLOSE, BACK, }
mit
hschroedl/FluentAST
core/src/test/kotlin/at.hschroedl.fluentast/ast/expression/ConditionalExpressionTest.kt
1
729
package at.hschroedl.fluentast.ast.expression import at.hschroedl.fluentast.ternary import at.hschroedl.fluentast.test.dummyExpression import at.hschroedl.fluentast.test.dummyLiteral import at.hschroedl.fluentast.test.toInlineString import org.eclipse.jdt.core.dom.ConditionalExpression import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class ConditionalExpressionTest { @Test internal fun conditionalExpression_withTypes_returnsConditionalExpression() { val expression = ternary(dummyExpression("dummy"), dummyLiteral(1), dummyLiteral(2)).build() as ConditionalExpression assertEquals("dummy ? 1 : 2", expression.toInlineString()) } }
apache-2.0
ShevaBrothers/easylib
src/core/util/AbstractTree.kt
1
723
/** * @Author is Yurii Yatsenko (@kyparus) * A generic tree of elements. * @param E the type of elements contained in the collection. The collection is covariant on its element type. */ interface AbstractTree<E> { // Query Operations /** * Returns the size of the collection. */ val size: Int /** * Returns `true` if the collection is empty (contains no elements), `false` otherwise. */ val isEmpty: Boolean /** * Adds a value to tree. */ fun insert(value: E) /** * Returns 'true' if value is in the collection, otherwise 'false' */ fun search(value: E): Boolean /** * Removes all elements from the tree. */ fun clear() }
mit
mehulsbhatt/emv-bertlv
src/test/java/io/github/binaryfoo/decoders/SignedDynamicApplicationDataDecoderTest.kt
1
1680
package io.github.binaryfoo.decoders import io.github.binaryfoo.tlv.ISOUtil import org.junit.Test import org.hamcrest.core.Is.`is` import org.junit.Assert.assertThat import io.github.binaryfoo.DecodedAsStringMatcher public class SignedDynamicApplicationDataDecoderTest { Test public fun decodeOutputOfCDA() { val recovered = ISOUtil.hex2byte("6A0501260836DF6D9E2104092E40D58B731AF5885C067BE29D015DD4C9454026810F0879E219B8A7DCD0BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB5734B62BE6BFF2A04C1CFF4060E549C932E1723DBC") val decoded = decodeSignedDynamicData(recovered, 0) assertThat(decoded, `is`(DecodedAsStringMatcher.decodedAsString("""Header: 6A Format: 05 Hash algorithm: 01 Dynamic data length: 38 ICC dynamic number length: 8 ICC dynamic number: 36DF6D9E2104092E Cryptogram information data: 40 Cryptogram: D58B731AF5885C06 Transaction data hash code: 7BE29D015DD4C9454026810F0879E219B8A7DCD0 Hash: 5734B62BE6BFF2A04C1CFF4060E549C932E1723D Trailer: BC """))) } Test public fun decodeBogStandardDDA() { val recovered = ISOUtil.hex2byte("6A05010706112233445566BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB97C21EB1AA67291E00322913CE1C52CCF0D93200BC") val decoded = decodeSignedDynamicData(recovered, 0) assertThat(decoded, `is`(DecodedAsStringMatcher.decodedAsString("""Header: 6A Format: 05 Hash algorithm: 01 Dynamic data length: 7 ICC dynamic number length: 6 ICC dynamic number: 112233445566 Hash: 97C21EB1AA67291E00322913CE1C52CCF0D93200 Trailer: BC """))) } }
mit
joan-domingo/Podcasts-RAC1-Android
app/src/test/java/cat/xojan/random1/testutil/Data.kt
1
2234
package cat.xojan.random1.testutil import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.session.MediaSessionCompat import cat.xojan.random1.domain.model.Podcast import cat.xojan.random1.domain.model.PodcastState import cat.xojan.random1.domain.model.Program import cat.xojan.random1.domain.model.Section import java.util.* val podcast1 = Podcast("id1", "path1", "filePath1", Date(), 0, "podcastId1", null, null, PodcastState.DOWNLOADED, "programTitle1", 1) val podcast2 = Podcast("id2", "path1", null, Date(), 0, "podcastId2", null, null, PodcastState.LOADED, "programTitle1", 1) val podcast3 = Podcast("id3", "path1", "filePath3", Date(), 0, "podcastId3", null, null, PodcastState.DOWNLOADING, "programTitle1", 1) val podcastList = listOf(podcast1, podcast2, podcast3) val section1 = Section("sectionId1", "sectionTitle1", "http://image.url", "programId1") val section2 = Section("sectionId2", "sectionTitle2", "http://image.url", "programId1") val section3 = Section("sectionId3", "sectionTitle3", "http://image.url", "programId1") val section4 = Section("sectionId4", "sectionTitle4", "http://image.url", "programId1") val sectionList = listOf(section1, section2, section3, section4) val sectionListResult1 = listOf(section1, section4) // PROGRAMS val program1 = Program("programId1", "programTitle1", null, null) val program2 = Program("programId2", "programTitle2", null, null) val program3 = Program("programId3", "programTitle3", null, null) val programsMap = linkedMapOf(Pair("programId1", program1), Pair("programId2", program2), Pair("programId3", program3)) // Description item val description1:MediaDescriptionCompat = MediaDescriptionCompat.Builder() .build() val description2:MediaDescriptionCompat = MediaDescriptionCompat.Builder() .build() val description3:MediaDescriptionCompat = MediaDescriptionCompat.Builder() .build() // Queue item val queueItem1 = MediaSessionCompat.QueueItem(description1, 1) val queueItem2 = MediaSessionCompat.QueueItem(description2, 2) val queueItem3 = MediaSessionCompat.QueueItem(description3, 3) val queueList1Item = listOf(queueItem1) val queueItemList = listOf(queueItem1, queueItem2, queueItem3)
mit
NooAn/bytheway
app/src/main/java/ru/a1024bits/bytheway/dagger/UserRepositoryModule.kt
1
1058
package ru.a1024bits.bytheway.dagger import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreSettings import dagger.Module import dagger.Provides import ru.a1024bits.bytheway.MapWebService import ru.a1024bits.bytheway.repository.UserRepository import javax.inject.Singleton /** * Created by andrey.gusenkov on 19/09/2017. */ @Module class UserRepositoryModule { @Provides @Singleton fun provideUserRepository(store: FirebaseFirestore, mapService: MapWebService): UserRepository = UserRepository(store, mapService) @Provides @Singleton fun providesFirestoreRepository(settings: FirebaseFirestoreSettings): FirebaseFirestore { val store = FirebaseFirestore.getInstance(); store.firestoreSettings = settings return store } @Provides @Singleton fun providesFirestoreSettings(): FirebaseFirestoreSettings = FirebaseFirestoreSettings.Builder() .setPersistenceEnabled(true) .setSslEnabled(true) .build() }
mit
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/reviewer/Binding.kt
1
10521
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.reviewer import android.content.Context import android.os.Build import android.view.KeyEvent import androidx.annotation.VisibleForTesting import com.ichi2.anki.cardviewer.Gesture import com.ichi2.compat.CompatHelper import com.ichi2.utils.StringUtil import timber.log.Timber class Binding private constructor(val modifierKeys: ModifierKeys?, val keycode: Int?, val unicodeCharacter: Char?, val gesture: Gesture?) { constructor(gesture: Gesture?) : this(null, null, null, gesture) private fun getKeyCodePrefix(): String { // KEY_PREFIX is not usable before API 23 val keyPrefix = if (CompatHelper.sdkVersion >= Build.VERSION_CODES.M) KEY_PREFIX.toString() else "" if (keycode == null) { return keyPrefix } if (KeyEvent.isGamepadButton(keycode)) { return GAMEPAD_PREFIX } return keyPrefix } fun toDisplayString(context: Context?): String { val string = StringBuilder() when { keycode != null -> { string.append(getKeyCodePrefix()) string.append(' ') string.append(modifierKeys!!.toString()) val keyCodeString = KeyEvent.keyCodeToString(keycode) // replace "Button" as we use the gamepad icon string.append(StringUtil.toTitleCase(keyCodeString.replace("KEYCODE_", "").replace("BUTTON_", "").replace('_', ' '))) } unicodeCharacter != null -> { string.append(KEY_PREFIX) string.append(' ') string.append(modifierKeys!!.toString()) string.append(unicodeCharacter) } gesture != null -> { string.append(gesture.toDisplayString(context!!)) } } return string.toString() } override fun toString(): String { val string = StringBuilder() when { keycode != null -> { string.append(KEY_PREFIX) string.append(modifierKeys!!.toString()) string.append(keycode) } unicodeCharacter != null -> { string.append(UNICODE_PREFIX) string.append(modifierKeys!!.toString()) string.append(unicodeCharacter) } gesture != null -> { string.append(GESTURE_PREFIX) string.append(gesture) } } return string.toString() } val isValid: Boolean get() = isKey || gesture != null val isKeyCode: Boolean get() = keycode != null val isKey: Boolean get() = isKeyCode || unicodeCharacter != null val isGesture: Boolean = gesture != null fun matchesModifier(event: KeyEvent): Boolean { return modifierKeys == null || modifierKeys.matches(event) } open class ModifierKeys internal constructor(private val shift: Boolean, private val ctrl: Boolean, private val alt: Boolean) { fun matches(event: KeyEvent): Boolean { // return false if Ctrl+1 is pressed and 1 is expected return shiftMatches(event) && ctrlMatches(event) && altMatches(event) } private fun shiftMatches(event: KeyEvent): Boolean = shift == event.isShiftPressed private fun ctrlMatches(event: KeyEvent): Boolean = ctrl == event.isCtrlPressed private fun altMatches(event: KeyEvent): Boolean = altMatches(event.isAltPressed) open fun shiftMatches(shiftPressed: Boolean): Boolean = shift == shiftPressed fun ctrlMatches(ctrlPressed: Boolean): Boolean = ctrl == ctrlPressed fun altMatches(altPressed: Boolean): Boolean = alt == altPressed override fun toString(): String { val string = StringBuilder() if (ctrl) { string.append("Ctrl+") } if (alt) { string.append("Alt+") } if (shift) { string.append("Shift+") } return string.toString() } companion object { fun none(): ModifierKeys = ModifierKeys(shift = false, ctrl = false, alt = false) fun ctrl(): ModifierKeys = ModifierKeys(shift = false, ctrl = true, alt = false) fun shift(): ModifierKeys = ModifierKeys(shift = true, ctrl = false, alt = false) fun alt(): ModifierKeys = ModifierKeys(shift = false, ctrl = false, alt = true) /** * Parses a [ModifierKeys] from a string. * @param s The string to parse * @return The [ModifierKeys], and the remainder of the string */ fun parse(s: String): Pair<ModifierKeys, String> { var modifiers = none() val plus = s.lastIndexOf("+") if (plus == -1) { return Pair(modifiers, s) } modifiers = fromString(s.substring(0, plus + 1)) return Pair(modifiers, s.substring(plus + 1)) } fun fromString(from: String): ModifierKeys = ModifierKeys(from.contains("Shift"), from.contains("Ctrl"), from.contains("Alt")) } } /** Modifier keys which cannot be defined by a binding */ private class AppDefinedModifierKeys private constructor() : ModifierKeys(false, false, false) { override fun shiftMatches(shiftPressed: Boolean): Boolean = true companion object { /** * Specifies a keycode combination binding from an unknown input device * Should be due to the "default" key bindings and never from user input * * If we do not know what the device is, "*" could be a key on the keyboard or Shift + 8 * * So we need to ignore shift, rather than match it to a value * * If we have bindings in the app, then we know whether we need shift or not (in actual fact, we should * be fine to use keycodes). */ fun allowShift(): ModifierKeys = AppDefinedModifierKeys() } } companion object { const val FORBIDDEN_UNICODE_CHAR = MappableBinding.PREF_SEPARATOR /** * https://www.fileformat.info/info/unicode/char/2328/index.htm (Keyboard) * This is not usable on API 21 or 22 */ const val KEY_PREFIX = '\u2328' /** https://www.fileformat.info/info/unicode/char/235d/index.htm (similar to a finger) */ const val GESTURE_PREFIX = '\u235D' /** https://www.fileformat.info/info/unicode/char/2705/index.htm - checkmark (often used in URLs for unicode) * Only used for serialisation. [.KEY_PREFIX] is used for display. */ const val UNICODE_PREFIX = '\u2705' const val GAMEPAD_PREFIX = "🎮" /** This returns multiple bindings due to the "default" implementation not knowing what the keycode for a button is */ fun key(event: KeyEvent): List<Binding> { val modifiers = ModifierKeys(event.isShiftPressed, event.isCtrlPressed, event.isAltPressed) val ret: MutableList<Binding> = ArrayList() val keyCode = event.keyCode if (keyCode != 0) { ret.add(keyCode(modifiers, keyCode)) } // passing in metaState: 0 means that Ctrl+1 returns '1' instead of '\0' // NOTE: We do not differentiate on upper/lower case via KeyEvent.META_CAPS_LOCK_ON val unicodeChar = event.getUnicodeChar(event.metaState and (KeyEvent.META_SHIFT_ON or KeyEvent.META_NUM_LOCK_ON)) if (unicodeChar != 0) { try { ret.add(unicode(modifiers, unicodeChar.toChar())) } catch (e: Exception) { Timber.w(e) } } return ret } /** * Specifies a unicode binding from an unknown input device * See [AppDefinedModifierKeys] */ fun unicode(unicodeChar: Char): Binding = unicode(AppDefinedModifierKeys.allowShift(), unicodeChar) fun unicode(modifierKeys: ModifierKeys?, unicodeChar: Char): Binding { if (unicodeChar == FORBIDDEN_UNICODE_CHAR) return unknown() return Binding(modifierKeys, null, unicodeChar, null) } fun keyCode(keyCode: Int): Binding = keyCode(ModifierKeys.none(), keyCode) fun keyCode(modifiers: ModifierKeys?, keyCode: Int): Binding = Binding(modifiers, keyCode, null, null) fun gesture(gesture: Gesture?): Binding = Binding(null, null, null, gesture) @VisibleForTesting fun unknown(): Binding = Binding(ModifierKeys.none(), null, null, null) fun fromString(from: String): Binding { if (from.isEmpty()) return unknown() try { return when (from[0]) { GESTURE_PREFIX -> { gesture(Gesture.valueOf(from.substring(1))) } UNICODE_PREFIX -> { val parsed = ModifierKeys.parse(from.substring(1)) unicode(parsed.first, parsed.second[0]) } KEY_PREFIX -> { val parsed = ModifierKeys.parse(from.substring(1)) val keyCode = parsed.second.toInt() keyCode(parsed.first, keyCode) } else -> unknown() } } catch (ex: Exception) { Timber.w(ex) } return unknown() } } }
gpl-3.0
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/data/db/MovieReelDatabase.kt
1
1060
package com.moviereel.data.db import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import com.moviereel.data.db.dao.MovieNowPlayingDao import com.moviereel.data.db.dao.MoviePopularDao import com.moviereel.data.db.dao.MovieTopRatedDao import com.moviereel.data.db.dao.MovieUpcomingDao import com.moviereel.data.db.entities.GenreEntity import com.moviereel.data.db.entities.movie.* /** * @author lusinabrian on 28/03/17 */ @Database(entities = arrayOf(MovieNowPlayingEntity::class, MoviePopularEntity::class, MovieTopRatedEntity::class, MovieUpcomingEntity::class, GenreEntity::class), version = 1, exportSchema = false) @TypeConverters(DbConverters::class) abstract class MovieReelDatabase : RoomDatabase() { abstract fun getMovieNowPlayingDao(): MovieNowPlayingDao abstract fun getMoviePopularDao(): MoviePopularDao abstract fun getMovieTopRatedDao(): MovieTopRatedDao abstract fun getMovieUpcomingDao(): MovieUpcomingDao }
mit
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/RecoveryWordsActivity.kt
1
7474
package com.samourai.wallet import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.google.android.material.transition.MaterialSharedAxis import com.samourai.wallet.access.AccessFactory import com.samourai.wallet.util.AppUtil import com.samourai.wallet.util.TimeOutUtil import kotlinx.android.synthetic.main.activity_recovery_words.* import kotlinx.android.synthetic.main.fragment_paper_wallet_instructions.* import kotlinx.android.synthetic.main.fragment_recovery_passphrase.* import kotlinx.android.synthetic.main.fragment_recovery_words.* class RecoveryWordsActivity : AppCompatActivity() { private var step = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recovery_words) window.statusBarColor = ContextCompat.getColor(this, R.color.window) navigate() nextButton.setOnClickListener { step += 1 navigate() } if(BuildConfig.FLAVOR != "staging"){ window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE) } } private fun navigate() { val wordList = arrayListOf<String>(); var passphrase = "" intent.extras?.getString(WORD_LIST)?.let { it -> val words: Array<String> = it.trim { it <= ' ' }.split(" ").toTypedArray() wordList.addAll(words) } intent.extras?.getString(PASSPHRASE)?.let { it -> passphrase = it } if (step >= 3) { AccessFactory.getInstance(applicationContext).setIsLoggedIn(true) TimeOutUtil.getInstance().updatePin() AppUtil.getInstance(applicationContext).restartApp() return } val fragment = when (step) { 0 -> RecoveryTemplateDownload() 1 -> RecoveryWords.newInstance(ArrayList(wordList)) 2 -> PassphraseFragment.newInstance(passphrase) else -> RecoveryTemplateDownload() } supportFragmentManager .beginTransaction() .replace(recoveryWordsFrame.id, fragment) .commit() } override fun onBackPressed() { if (step == 0) { super.onBackPressed() } else { step -= 1 this.navigate() } } class RecoveryTemplateDownload : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_paper_wallet_instructions, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) downloadRecoveryTemplate.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse("https://samouraiwallet.com/recovery/worksheet") }) } } } class PassphraseFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_recovery_passphrase, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { bundle-> bundle.getString(PASSPHRASE)?.let { passphraseView.text = it } } } companion object { fun newInstance(passPhrase: String): Fragment { return PassphraseFragment().apply { arguments = Bundle().apply { putString(PASSPHRASE, passPhrase) } } } } } class RecoveryWords : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_recovery_words, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enterTransition = MaterialSharedAxis(MaterialSharedAxis.X,true) returnTransition = MaterialSharedAxis(MaterialSharedAxis.X,false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { bundle -> bundle.getStringArrayList(WORD_LIST) ?.let { if (it.size == 12) { it.map { word -> "(${it.indexOf(word) + 1}) $word" } .forEachIndexed { index, word -> run { when (index) { 0 -> word1.text = word 1 -> word2.text = word 2 -> word3.text = word 3 -> word4.text = word 4 -> word5.text = word 5 -> word6.text = word 6 -> word7.text = word 7 -> word8.text = word 8 -> word9.text = word 9 -> word10.text = word 10 -> word11.text = word 11 -> word12.text = word } } } } } } } companion object { fun newInstance(list: ArrayList<String>): Fragment { return RecoveryWords().apply { arguments = Bundle().apply { putStringArrayList(WORD_LIST, list) } } } } } companion object { const val WORD_LIST = "BIP39_WORD_LIST" const val PASSPHRASE = "PASSPHRASE" } }
unlicense
madlexa/lurry
src/main/kotlin/one/trifle/lurry/connection/LurrySource.kt
1
854
/* * Copyright 2017 Aleksey Dobrynin * * 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 one.trifle.lurry.connection import one.trifle.lurry.LQuery interface LurrySource { val type: DatabaseType fun execute(query: LQuery, params: Map<String, Any>): List<Row> interface Row { fun toMap(): Map<String, Any> } }
apache-2.0
Kotlin/kotlinx.serialization
formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/ProtobufWriter.kt
1
3078
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:OptIn(ExperimentalSerializationApi::class) package kotlinx.serialization.protobuf.internal import kotlinx.serialization.* import kotlinx.serialization.protobuf.* internal class ProtobufWriter(private val out: ByteArrayOutput) { fun writeBytes(bytes: ByteArray, tag: Int) { out.encode32((tag shl 3) or SIZE_DELIMITED) writeBytes(bytes) } fun writeBytes(bytes: ByteArray) { out.encode32(bytes.size) out.write(bytes) } fun writeOutput(output: ByteArrayOutput, tag: Int) { out.encode32((tag shl 3) or SIZE_DELIMITED) writeOutput(output) } fun writeOutput(output: ByteArrayOutput) { out.encode32(output.size()) out.write(output) } fun writeInt(value: Int, tag: Int, format: ProtoIntegerType) { val wireType = if (format == ProtoIntegerType.FIXED) i32 else VARINT out.encode32((tag shl 3) or wireType) out.encode32(value, format) } fun writeInt(value: Int) { out.encode32(value) } fun writeLong(value: Long, tag: Int, format: ProtoIntegerType) { val wireType = if (format == ProtoIntegerType.FIXED) i64 else VARINT out.encode32((tag shl 3) or wireType) out.encode64(value, format) } fun writeLong(value: Long) { out.encode64(value) } fun writeString(value: String, tag: Int) { val bytes = value.encodeToByteArray() writeBytes(bytes, tag) } fun writeString(value: String) { val bytes = value.encodeToByteArray() writeBytes(bytes) } fun writeDouble(value: Double, tag: Int) { out.encode32((tag shl 3) or i64) out.writeLong(value.reverseBytes()) } fun writeDouble(value: Double) { out.writeLong(value.reverseBytes()) } fun writeFloat(value: Float, tag: Int) { out.encode32((tag shl 3) or i32) out.writeInt(value.reverseBytes()) } fun writeFloat(value: Float) { out.writeInt(value.reverseBytes()) } private fun ByteArrayOutput.encode32( number: Int, format: ProtoIntegerType = ProtoIntegerType.DEFAULT ) { when (format) { ProtoIntegerType.FIXED -> out.writeInt(number.reverseBytes()) ProtoIntegerType.DEFAULT -> encodeVarint64(number.toLong()) ProtoIntegerType.SIGNED -> encodeVarint32(((number shl 1) xor (number shr 31))) } } private fun ByteArrayOutput.encode64(number: Long, format: ProtoIntegerType = ProtoIntegerType.DEFAULT) { when (format) { ProtoIntegerType.FIXED -> out.writeLong(number.reverseBytes()) ProtoIntegerType.DEFAULT -> encodeVarint64(number) ProtoIntegerType.SIGNED -> encodeVarint64((number shl 1) xor (number shr 63)) } } private fun Float.reverseBytes(): Int = toRawBits().reverseBytes() private fun Double.reverseBytes(): Long = toRawBits().reverseBytes() }
apache-2.0
jonninja/node.kt
src/main/kotlin/node/express/middleware/Static.kt
1
1940
package node.express.middleware import node.express.Request import node.express.Response import java.io.File import java.util.HashMap import node.express.RouteHandler import node.mimeType import node.util._withNotNull /** * Middleware for serving a tree of static files */ public fun static(basePath: String): RouteHandler.()->Unit { val files = HashMap<String, File>() // a cache of paths to files to improve performance return { if (req.method != "get" && req.method != "head") next() else { var requestPath = req.param("*") as? String ?: "" var srcFile: File? = files[requestPath] ?: { var path = requestPath if (!path.startsWith("/")) { path = "/" + path } if (path.endsWith("/")) { path += "index.html" } var f = File(basePath + path) if (f.exists()) { files.put(requestPath, f) f } else { null } }() if (srcFile != null) { res.sendFile(srcFile) } else { next() } } } } /** * Middleware that servers static resources from the code pacakage */ public fun staticResources(classBasePath: String): RouteHandler.()->Unit { return { if (req.method != "get" && req.method != "head") next() else { var requestPath = req.param("*") as? String ?: "" if (requestPath.length() > 0 && requestPath.charAt(0) == '/') { requestPath = requestPath.substring(1) } var resource = Thread.currentThread().getContextClassLoader().getResource(classBasePath + requestPath) if (resource != null) { _withNotNull(requestPath.mimeType()) { res.contentType(it) } resource.openStream().use { res.send(it) } } else { next() } } } }
mit
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/effect/sound/LanternSoundType.kt
1
676
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.effect.sound import org.lanternpowered.api.effect.sound.SoundType import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.server.catalog.DefaultCatalogType class LanternSoundType @JvmOverloads constructor( key: NamespacedKey, val eventId: Int? = null ) : DefaultCatalogType(key), SoundType
mit
raatiniemi/worker
app/src/androidTest/java/me/raatiniemi/worker/data/projects/TimesheetDaoTest.kt
1
6701
/* * Copyright (C) 2018 Tobias Raatiniemi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.raatiniemi.worker.data.projects import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class TimesheetDaoTest : BaseDaoTest() { @Before override fun setUp() { super.setUp() projects.add(projectEntity()) } @Test fun findAll_withoutTimeIntervals() { val actual = timesheet.findAll(1, 0, 10) assertEquals(emptyList<TimesheetDay>(), actual) } @Test fun findAll_withoutTimeIntervalForProject() { projects.add(projectEntity { id = 2 name = "Name #2" }) timeIntervals.add(timeIntervalEntity { projectId = 2 }) val actual = timesheet.findAll(1, 0, 10) assertEquals(emptyList<TimesheetDay>(), actual) } @Test fun findAll_withTimeInterval() { timeIntervals.add(timeIntervalEntity()) val expected = listOf( TimesheetDay(1, "1") ) val actual = timesheet.findAll(1, 0, 10) assertEquals(expected, actual) } @Test fun findAll_withTimeIntervalOnSameDay() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 10 stopInMilliseconds = 100 }) val expected = listOf( TimesheetDay(1, "1,2") ) val actual = timesheet.findAll(1, 0, 10) assertEquals(expected, actual) } @Test fun findAll_withTimeIntervalOnDifferentDays() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(90000000, "2"), TimesheetDay(1, "1") ) val actual = timesheet.findAll(1, 0, 10) assertEquals(expected, actual) } @Test fun findAll_withTimeIntervalWithOffset() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(1, "1") ) val actual = timesheet.findAll(1, 1, 10) assertEquals(expected, actual) } @Test fun findAll_withTimeIntervalWithMaxResult() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(90000000, "2") ) val actual = timesheet.findAll(1, 0, 1) assertEquals(expected, actual) } @Test fun findAllUnregistered_withoutTimeIntervals() { val actual = timesheet.findAllUnregistered(1, 0, 10) assertEquals(emptyList<TimesheetDay>(), actual) } @Test fun findAllUnregistered_withoutTimeIntervalForProject() { projects.add(projectEntity { id = 2 name = "Name #2" }) timeIntervals.add(timeIntervalEntity { projectId = 2 }) val actual = timesheet.findAllUnregistered(1, 0, 10) assertEquals(emptyList<TimesheetDay>(), actual) } @Test fun findAllUnregistered_withTimeInterval() { timeIntervals.add(timeIntervalEntity()) val expected = listOf( TimesheetDay(1, "1") ) val actual = timesheet.findAllUnregistered(1, 0, 10) assertEquals(expected, actual) } @Test fun findAllUnregistered_withTimeIntervalOnSameDay() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 10 stopInMilliseconds = 100 }) val expected = listOf( TimesheetDay(1, "1,2") ) val actual = timesheet.findAllUnregistered(1, 0, 10) assertEquals(expected, actual) } @Test fun findAllUnregistered_withTimeIntervalOnDifferentDays() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(90000000, "2"), TimesheetDay(1, "1") ) val actual = timesheet.findAllUnregistered(1, 0, 10) assertEquals(expected, actual) } @Test fun findAllUnregistered_withTimeIntervalWithOffset() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(1, "1") ) val actual = timesheet.findAllUnregistered(1, 1, 10) assertEquals(expected, actual) } @Test fun findAllUnregistered_withTimeIntervalWithMaxResult() { timeIntervals.add(timeIntervalEntity()) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(90000000, "2") ) val actual = timesheet.findAllUnregistered(1, 0, 1) assertEquals(expected, actual) } @Test fun findAllUnregistered_withRegisteredTimeInterval() { timeIntervals.add(timeIntervalEntity { registered = true }) timeIntervals.add(timeIntervalEntity { startInMilliseconds = 90000000 stopInMilliseconds = 90000010 }) val expected = listOf( TimesheetDay(90000000, "2") ) val actual = timesheet.findAllUnregistered(1, 0, 10) assertEquals(expected, actual) } }
gpl-2.0
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/SpannerExchangesService.kt
1
2786
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner import io.grpc.Status import kotlinx.coroutines.flow.singleOrNull import org.wfanet.measurement.common.grpc.failGrpc import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.gcloud.common.toCloudDate import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient import org.wfanet.measurement.gcloud.spanner.appendClause import org.wfanet.measurement.gcloud.spanner.bind import org.wfanet.measurement.internal.kingdom.CreateExchangeRequest import org.wfanet.measurement.internal.kingdom.Exchange import org.wfanet.measurement.internal.kingdom.ExchangesGrpcKt.ExchangesCoroutineImplBase import org.wfanet.measurement.internal.kingdom.GetExchangeRequest import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.PROVIDER_PARAM import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.providerFilter import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.ExchangeReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.CreateExchange class SpannerExchangesService( private val idGenerator: IdGenerator, private val client: AsyncDatabaseClient ) : ExchangesCoroutineImplBase() { override suspend fun createExchange(request: CreateExchangeRequest): Exchange { return CreateExchange(request.exchange).execute(client, idGenerator) } override suspend fun getExchange(request: GetExchangeRequest): Exchange { return ExchangeReader() .fillStatementBuilder { appendClause( """ WHERE RecurringExchanges.ExternalRecurringExchangeId = @external_recurring_exchange_id AND Exchanges.Date = @date AND ${providerFilter(request.provider)} """ .trimIndent() ) bind("external_recurring_exchange_id" to request.externalRecurringExchangeId) bind("date" to request.date.toCloudDate()) bind(PROVIDER_PARAM to request.provider.externalId) appendClause("LIMIT 1") } .execute(client.singleUse()) .singleOrNull() ?.exchange ?: failGrpc(Status.NOT_FOUND) { "Exchange not found" } } }
apache-2.0
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/shows/collected/CollectedShowsFragment.kt
1
4546
/* * Copyright (C) 2016 Simon Vig Therkildsen * * 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.simonvt.cathode.ui.shows.collected import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import net.simonvt.cathode.R import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.settings.Settings import net.simonvt.cathode.settings.TraktLinkSettings import net.simonvt.cathode.sync.scheduler.EpisodeTaskScheduler import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler import net.simonvt.cathode.ui.CathodeViewModelFactory import net.simonvt.cathode.ui.LibraryType import net.simonvt.cathode.ui.lists.ListDialog import net.simonvt.cathode.ui.shows.ShowsFragment import javax.inject.Inject class CollectedShowsFragment @Inject constructor( showScheduler: ShowTaskScheduler, episodeScheduler: EpisodeTaskScheduler ) : ShowsFragment(showScheduler, episodeScheduler), ListDialog.Callback { @Inject lateinit var viewModelFactory: CathodeViewModelFactory lateinit var viewModel: CollectedShowsViewModel private var sortBy: SortBy? = null enum class SortBy constructor(val key: String, val sortOrder: String) { TITLE("title", Shows.SORT_TITLE), COLLECTED("collected", Shows.SORT_COLLECTED); override fun toString(): String { return key } companion object { fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: TITLE } } override fun onCreate(inState: Bundle?) { sortBy = SortBy.fromValue( Settings.get(requireContext()) .getString(Settings.Sort.SHOW_COLLECTED, SortBy.TITLE.key)!! ) super.onCreate(inState) setEmptyText(R.string.empty_show_collection) setTitle(R.string.title_shows_collection) viewModel = ViewModelProviders.of(this, viewModelFactory).get(CollectedShowsViewModel::class.java) viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) }) viewModel.shows.observe(this, observer) } override fun onViewCreated(view: View, inState: Bundle?) { super.onViewCreated(view, inState) swipeRefreshLayout.isEnabled = TraktLinkSettings.isLinked(requireContext()) } override fun createMenu(toolbar: Toolbar) { super.createMenu(toolbar) toolbar.inflateMenu(R.menu.fragment_shows_collected) } override fun onRefresh() { viewModel.refresh() } override fun onMenuItemClick(item: MenuItem): Boolean { if (item.itemId == R.id.menu_sort) { val items = arrayListOf<ListDialog.Item>() items.add(ListDialog.Item(R.id.sort_title, R.string.sort_title)) items.add(ListDialog.Item(R.id.sort_collected, R.string.sort_collected)) ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this) .show(requireFragmentManager(), DIALOG_SORT) return true } return super.onMenuItemClick(item) } override fun onItemSelected(id: Int) { when (id) { R.id.sort_title -> if (sortBy != SortBy.TITLE) { sortBy = SortBy.TITLE Settings.get(requireContext()) .edit() .putString(Settings.Sort.SHOW_COLLECTED, SortBy.TITLE.key) .apply() viewModel.setSortBy(sortBy!!) scrollToTop = true } R.id.sort_collected -> if (sortBy != SortBy.COLLECTED) { sortBy = SortBy.COLLECTED Settings.get(requireContext()) .edit() .putString(Settings.Sort.SHOW_COLLECTED, SortBy.COLLECTED.key) .apply() viewModel.setSortBy(sortBy!!) scrollToTop = true } } } override fun getLibraryType(): LibraryType { return LibraryType.COLLECTION } companion object { const val TAG = "net.simonvt.cathode.ui.shows.collected.ShowsCollectionFragment" private const val DIALOG_SORT = "net.simonvt.cathode.common.ui.fragment.ShowCollectionFragment.sortDialog" } }
apache-2.0
KotlinKit/Reactant
Core/src/main/kotlin/org/brightify/reactant/autolayout/util/View+constraint.kt
1
340
package org.brightify.reactant.autolayout.util import android.view.View import org.brightify.reactant.autolayout.dsl.ConstraintDsl /** * @author <a href="mailto:[email protected]">Filip Dolnik</a> */ val View.snp: ConstraintDsl get() = ConstraintDsl(this) val View.description: String get() = "${javaClass.simpleName}($id)"
mit
daverix/urlforwarder
app/src/main/java/net/daverix/urlforward/ViewModels.kt
1
544
package net.daverix.urlforward import androidx.compose.runtime.Composable import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel @Composable inline fun <reified T : ViewModel> viewModelWithFactory( crossinline factory: () -> T ): T = viewModel( factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return factory() as T } } )
gpl-3.0
google-developer-training/basic-android-kotlin-compose-training-affirmations
app/src/main/java/com/example/affirmations/ui/theme/Shape.kt
1
936
/* * Copyright (C) 2021 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.example.affirmations.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
apache-2.0
jamieadkins95/Roach
data/src/main/java/com/jamieadkins/gwent/data/update/UpdateDataModule.kt
1
1764
package com.jamieadkins.gwent.data.update import com.jamieadkins.gwent.data.update.repository.CardUpdateRepository import com.jamieadkins.gwent.data.update.repository.CategoryUpdateRepository import com.jamieadkins.gwent.data.update.repository.InstantAppsRepositoryImpl import com.jamieadkins.gwent.data.update.repository.KeywordUpdateRepository import com.jamieadkins.gwent.data.update.repository.NoticesRepositoryImpl import com.jamieadkins.gwent.data.update.repository.NotificationsRepository import com.jamieadkins.gwent.data.update.repository.UpdateRepositoryImpl import com.jamieadkins.gwent.domain.update.repository.InstantAppsRepository import com.jamieadkins.gwent.domain.update.repository.NoticesRepository import com.jamieadkins.gwent.domain.update.repository.UpdateRepository import dagger.Binds import dagger.Module import dagger.Reusable @Module(includes = [PatchDataModule::class]) abstract class UpdateDataModule { @Binds @Reusable abstract fun repository(repository: UpdateRepositoryImpl): UpdateRepository @CardUpdate @Binds @Reusable abstract fun card(repository: CardUpdateRepository): UpdateRepository @KeywordUpdate @Binds @Reusable abstract fun keyword(repository: KeywordUpdateRepository): UpdateRepository @CategoryUpdate @Binds @Reusable abstract fun category(repository: CategoryUpdateRepository): UpdateRepository @NotificationsUpdate @Binds @Reusable abstract fun notifications(repository: NotificationsRepository): UpdateRepository @Binds @Reusable abstract fun notices(repository: NoticesRepositoryImpl): NoticesRepository @Binds @Reusable abstract fun instant(repository: InstantAppsRepositoryImpl): InstantAppsRepository }
apache-2.0
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/osmDataRepresentation/OSMDataReader.kt
1
7034
package de.esymetric.jerusalem.osmDataRepresentation import de.esymetric.jerusalem.utils.Utils import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.util.* class OSMDataReader( var inputStream: InputStream, var listener: OSMDataReaderListener, var jumpOverNodes: Boolean ) { var entityCount: Long = 0 interface OSMDataReaderListener { fun foundNode(node: OSMNode) fun foundWay(way: OSMWay) } var buffer = "" fun read(startTime: Date): Boolean { val lnr = BufferedReader( InputStreamReader( inputStream ), 1_000_000 ) try { readToTag(lnr, "<osm") readToTag(lnr, ">") if (jumpOverNodes) { while (true) { buffer = lnr.readLine() if (!buffer.contains("<way")) { continue } break } } while (true) { if (readToTag(lnr, "<") == null) break val xmlNodeName = readToTag(lnr, " ") val sb = StringBuilder() sb.append(xmlNodeName) sb.append(' ') val tail = readToTag(lnr, ">") sb.append(tail) if (tail?.last() != '/') { sb.append('>') sb.append(readToTag(lnr, "</$xmlNodeName>")) sb.append("</") sb.append(xmlNodeName) } val content = sb.toString() entityCount++ if (entityCount and 0xFFFFF == 0L) { println( Utils.formatTimeStopWatch( Date().time - startTime.time ) + " " + entityCount + " entities read" ) if (entityCount and 0x700000 == 0L) { print("free memory: " + Runtime.getRuntime().freeMemory() / 1024L / 1024L + " MB / " + Runtime.getRuntime().totalMemory() / 1024L / 1024L + " MB " ) System.gc() println( " >>> " + Runtime.getRuntime().freeMemory() / 1024L / 1024L + " MB / " + Runtime.getRuntime().totalMemory() / 1024L / 1024L + " MB " ) } } if ("node" == xmlNodeName) { makeOSMNode(content) continue } if ("way" == xmlNodeName) { makeOSMWay(content) continue } } } catch (e: IOException) { e.printStackTrace() } return true } private fun makeOSMWay(content: String) { try { val way = OSMWay() val xmlNodes = splitXmlNodes(content) val attributes = getAttributes(xmlNodes.first()) way.id = attributes["id"]?.toInt() ?: throw OsmReaderXMLParseException() val nodes = mutableListOf<Long>() val tags = mutableMapOf<String, String>() for (childNode in xmlNodes) { if (childNode.startsWith("nd")) { val childAttrib = getAttributes(childNode) childAttrib["ref"]?.toLong()?.let { nodes.add(it) } } else if (childNode.startsWith("tag")) { val childAttrib = getAttributes(childNode) tags[childAttrib["k"]!!] = childAttrib["v"]!! } } way.nodes = nodes.toTypedArray() way.tags = tags listener.foundWay(way) } catch (e: OsmReaderXMLParseException) { println("XML Parse Error on: $content") e.printStackTrace() } } private fun makeOSMNode(content: String) { try { val node = OSMNode() val xmlNodes = splitXmlNodes(content) val attributes = getAttributes(xmlNodes.first()) node.id = attributes["id"]?.toLong() ?: throw OsmReaderXMLParseException() node.lat = attributes["lat"]?.toDouble() ?: throw OsmReaderXMLParseException() node.lng = attributes["lon"]?.toDouble() ?: throw OsmReaderXMLParseException() listener.foundNode(node) } catch (e: OsmReaderXMLParseException) { println("XML Parse Error on: $content") e.printStackTrace() } } @Throws(IOException::class) fun readToTag(lnr: BufferedReader, tag: String): String? { if (buffer.isNotEmpty()) { val p = buffer.indexOf(tag) if (p >= 0) { val head = buffer.substring(0, p) val tail = buffer.substring(p + tag.length) buffer = tail + '\n' return head } } val buf = StringBuffer() buf.append(buffer) while (true) { val line = lnr.readLine() ?: return null val p = line.indexOf(tag) if (p < 0) { buf.append(line) buf.append('\n') } else { val head = line.substring(0, p) val tail = line.substring(p + tag.length) buf.append(head) buffer = tail + '\n' return buf.toString() } } } private fun splitXmlNodes(content: String): List<String> = content.split('<') private fun getAttributes(content: String): Map<String, String> { var tail = content val attrib = mutableMapOf<String, String>() while(true) { val pBlank = tail.indexOf(' ') if (pBlank < 0 ) break; val pEquals = tail.indexOf('=') if (pEquals < 0 ) break; val name = tail.substring(pBlank + 1, pEquals) tail = tail.substring(pEquals + 2) // jump over quote val pQuote = tail.indexOf('"') if (pQuote < 0 ) break; val value = tail.substring(0, pQuote) tail = tail.substring(pQuote + 1) attrib[name] = value } return attrib } } class OsmReaderXMLParseException : RuntimeException()
apache-2.0
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/model/topic/Home.kt
1
2384
package xyz.rankki.psnine.model.topic import me.ghui.fruit.Attrs import me.ghui.fruit.annotations.Pick import xyz.rankki.psnine.base.BaseTopicModel import xyz.rankki.psnine.common.config.PSNineTypes class Home : BaseTopicModel() { @Pick(value = "div.side > div.box > p:nth-child(1) > a > img", attr = Attrs.SRC) private var _avatar: String = "" @Pick(value = "div.side > div.box > p:nth-child(2) > a") private var _username: String = "" @Pick(value = "div.main > div:nth-child(1) > div:nth-child(1) > div > span:nth-child(3)") private var _meta: String = "" @Pick(value = "div.main > div:nth-child(1) > div:nth-child(1) > h1") private var _title: String = "" @Pick(value = "div.main > div:nth-child(1) > div.content.pd10", attr = Attrs.INNER_HTML) private var _content: String = "" @Pick(value = "div.main > div.box.mt20 > div.post:has(div.ml64)") private var _replies: ArrayList<Reply> = ArrayList() @Pick(value = "div.main > div.box.mt20 > div.post > a.btn") private var _isMoreReplies: String = "" @Pick(value = "div.main > div.box > table.list > tbody > tr") var games: ArrayList<Game> = ArrayList() @Pick(value = "div.main > div:nth-child(1) > div.content.pd10:has(table)", attr = "itemprop") private var _hasTable: String = "" @Pick(value = "div.main > div:nth-child(1) > div.content.pd10:has(div.pd10)", attr = "itemprop") private var _hasTrophy: String = "" override fun getType(): Int = PSNineTypes.Home override fun getUsername(): String = _username override fun getContent(): String = "<h3>$_title</h3><br>$_content" override fun getTime(): String = _meta override fun getAvatar(): String = _avatar override fun isMoreReplies(): Boolean = _isMoreReplies !== "" override fun getReplies(): ArrayList<Reply> = _replies override fun usingWebView(): Boolean = _hasTable !== "" || _hasTrophy !== "" class Game { @Pick(value = "td.pdd10 > a > img", attr = Attrs.SRC) var gameAvatar: String = "" @Pick(value = "td.pd10 > p > a") var gameName: String = "" @Pick(value = "td.pd10 > p > span") var gameEdition: String = "" @Pick(value = "td.pd10 > div.meta") var gameTrophy: String = "" @Pick(value = "td.pd10 > blockquote") var gameComment: String = "" } }
apache-2.0
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/ad/AdHelper.kt
1
709
package cc.aoeiuv020.panovel.ad import android.app.Application import android.os.Build import cc.aoeiuv020.panovel.settings.AdSettings import org.jetbrains.anko.AnkoLogger /** * Created by AoEiuV020 on 2021.04.25-23:45:31. */ object AdHelper : AnkoLogger { fun init(context: Application) { } fun checkSplashAdAvailable() = AdSettings.adEnabled && isArm() private fun isArm(): Boolean { // GDT只支持arm系列, // 不能判断SUPPORTED_ABIS,因为模拟器支持arm情况也是优先使用x86导致无法加载广告, @Suppress("DEPRECATION") return Build.CPU_ABI.contains("arm") } fun createListHelper() = TestAdListHelper() }
gpl-3.0
tasks/tasks
app/src/main/java/org/tasks/data/TaskAttachment.kt
1
1414
package org.tasks.data import android.os.Parcel import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey import com.todoroo.astrid.helper.UUIDHelper @Entity(tableName = "attachment_file") data class TaskAttachment( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "file_id") @Transient val id: Long? = null, @ColumnInfo(name = "file_uuid") val remoteId: String = UUIDHelper.newUUID(), @ColumnInfo(name = "filename") val name: String, @ColumnInfo(name = "uri") val uri: String, ) : Parcelable { @Ignore constructor(parcel: Parcel) : this( remoteId = parcel.readString()!!, name = parcel.readString()!!, uri = parcel.readString()!!, ) override fun describeContents() = 0 override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(remoteId) parcel.writeString(name) parcel.writeString(uri) } companion object { const val KEY = "attachment" const val FILES_DIRECTORY_DEFAULT = "attachments" @JvmField val CREATOR = object : Parcelable.Creator<TaskAttachment> { override fun createFromParcel(parcel: Parcel) = TaskAttachment(parcel) override fun newArray(size: Int): Array<TaskAttachment?> = arrayOfNulls(size) } } }
gpl-3.0
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/dependency/AssertK.kt
2
1542
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.dependency /** * Assertion library for tests in Kotlin * * [AssertK](https://github.com/willowtreeapps/assertk) */ @Suppress("unused") object AssertK { private const val version = "0.25" const val libJvm = "com.willowtreeapps.assertk:assertk-jvm:${version}" }
apache-2.0
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/ui/web/WebActivity.kt
1
2040
package jp.kentan.studentportalplus.ui.web import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import android.webkit.WebSettings import android.webkit.WebView import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import jp.kentan.studentportalplus.R import jp.kentan.studentportalplus.databinding.ActivityWebBinding class WebActivity : AppCompatActivity() { companion object { private const val EXTRA_TITLE = "EXTRA_TITLE" private const val EXTRA_URL = "EXTRA_URL" fun createIntent(context: Context, title: String, url: String) = Intent(context, WebActivity::class.java).apply { putExtra(EXTRA_TITLE, title) putExtra(EXTRA_URL, url) } } private lateinit var webView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) webView = DataBindingUtil.setContentView<ActivityWebBinding>(this, R.layout.activity_web).webView supportActionBar?.setDisplayHomeAsUpEnabled(true) val title = intent.getStringExtra(EXTRA_TITLE) val url = intent.getStringExtra(EXTRA_URL) if (title == null || url == null) { finish() return } setTitle(title) webView.apply { settings.cacheMode = WebSettings.LOAD_NO_CACHE settings.setAppCacheEnabled(false) loadUrl(url) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { finish() return true } override fun onPause() { webView.run { onPause() pauseTimers() } super.onPause() } override fun onResume() { super.onResume() webView.run { resumeTimers() onResume() } } override fun onDestroy() { webView.destroy() super.onDestroy() } }
gpl-3.0
Guardsquare/proguard
gradle-plugin/src/main/kotlin/proguard/gradle/plugin/android/ProGuardTransform.kt
1
7470
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2021 Guardsquare NV * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.gradle.plugin.android import com.android.build.api.transform.Format import com.android.build.api.transform.Format.DIRECTORY import com.android.build.api.transform.Format.JAR import com.android.build.api.transform.QualifiedContent import com.android.build.api.transform.QualifiedContent.DefaultContentType import com.android.build.api.transform.QualifiedContent.DefaultContentType.CLASSES import com.android.build.api.transform.QualifiedContent.DefaultContentType.RESOURCES import com.android.build.api.transform.QualifiedContent.Scope import com.android.build.api.transform.QualifiedContent.Scope.EXTERNAL_LIBRARIES import com.android.build.api.transform.QualifiedContent.Scope.PROJECT import com.android.build.api.transform.QualifiedContent.Scope.PROVIDED_ONLY import com.android.build.api.transform.QualifiedContent.Scope.SUB_PROJECTS import com.android.build.api.transform.SecondaryFile import com.android.build.api.transform.Transform import com.android.build.api.transform.TransformInput import com.android.build.api.transform.TransformInvocation import com.android.build.api.transform.TransformOutputProvider import com.android.build.api.variant.VariantInfo import com.android.build.gradle.BaseExtension import java.io.File import org.gradle.api.Project import proguard.gradle.ProGuardTask import proguard.gradle.plugin.android.AndroidPlugin.Companion.COLLECT_CONSUMER_RULES_TASK_NAME import proguard.gradle.plugin.android.AndroidProjectType.ANDROID_APPLICATION import proguard.gradle.plugin.android.AndroidProjectType.ANDROID_LIBRARY import proguard.gradle.plugin.android.dsl.ProGuardAndroidExtension import proguard.gradle.plugin.android.dsl.UserProGuardConfiguration class ProGuardTransform( private val project: Project, private val proguardBlock: ProGuardAndroidExtension, private val projectType: AndroidProjectType, private val androidExtension: BaseExtension ) : Transform() { override fun transform(transformInvocation: TransformInvocation) { val variantName: String = transformInvocation.context.variantName val variantBlock = proguardBlock.configurations.findVariantConfiguration(variantName) ?: throw RuntimeException("Invalid configuration: $variantName") val proguardTask = project.tasks.create("proguardTask${variantName.capitalize()}", ProGuardTask::class.java) createIOEntries(transformInvocation.inputs, transformInvocation.outputProvider).forEach { proguardTask.injars(it.first) proguardTask.outjars(it.second) } proguardTask.extraJar(transformInvocation .outputProvider .getContentLocation("extra.jar", setOf(CLASSES, RESOURCES), mutableSetOf(PROJECT), JAR)) proguardTask.libraryjars(createLibraryJars(transformInvocation.referencedInputs)) proguardTask.configuration(project.tasks.getByPath(COLLECT_CONSUMER_RULES_TASK_NAME + variantName.capitalize()).outputs.files) proguardTask.configuration(variantBlock.configurations.map { project.file(it.path) }) val aaptRulesFile = getAaptRulesFile() if (aaptRulesFile != null && File(aaptRulesFile).exists()) { proguardTask.configuration(aaptRulesFile) } else { project.logger.warn("AAPT rules file not found: you may need to apply some extra keep rules for classes referenced from resources in your own ProGuard configuration.") } val mappingDir = project.buildDir.resolve("outputs/proguard/$variantName/mapping") if (!mappingDir.exists()) mappingDir.mkdirs() proguardTask.printmapping(File(mappingDir, "mapping.txt")) proguardTask.printseeds(File(mappingDir, "seeds.txt")) proguardTask.printusage(File(mappingDir, "usage.txt")) proguardTask.android() proguardTask.proguard() } override fun getName(): String = "ProguardTransform" override fun getInputTypes(): Set<DefaultContentType> = setOf(CLASSES, RESOURCES) override fun getScopes(): MutableSet<in Scope> = when (projectType) { ANDROID_APPLICATION -> mutableSetOf(PROJECT, SUB_PROJECTS, EXTERNAL_LIBRARIES) ANDROID_LIBRARY -> mutableSetOf(PROJECT) } override fun getReferencedScopes(): MutableSet<in Scope> = when (projectType) { ANDROID_APPLICATION -> mutableSetOf(PROVIDED_ONLY) ANDROID_LIBRARY -> mutableSetOf(PROVIDED_ONLY, EXTERNAL_LIBRARIES, SUB_PROJECTS) } override fun isIncremental(): Boolean = false override fun applyToVariant(variant: VariantInfo?): Boolean = variant?.let { proguardBlock.configurations.findVariantConfiguration(it) } != null override fun getSecondaryFiles(): MutableCollection<SecondaryFile> = proguardBlock .configurations .flatMap { it.configurations } .filterIsInstance<UserProGuardConfiguration>() .map { SecondaryFile(project.file(it.path), false) } .toMutableSet().apply { getAaptRulesFile()?.let { this.add(SecondaryFile(project.file(it), false)) } } private fun createIOEntries( inputs: Collection<TransformInput>, outputProvider: TransformOutputProvider ): List<ProGuardIOEntry> { fun createEntry(input: QualifiedContent, format: Format): ProGuardIOEntry { return ProGuardIOEntry( input.file, outputProvider.getContentLocation(input.name, input.contentTypes, input.scopes, format).canonicalFile) } return inputs.flatMap { input -> input.directoryInputs.map { createEntry(it, DIRECTORY) } + input.jarInputs.map { createEntry(it, JAR) } } } private fun createLibraryJars(inputs: Collection<TransformInput>): List<File> = inputs.flatMap { input -> input.directoryInputs.map { it.file } + input.jarInputs.map { it.file } } + listOf(androidExtension.sdkDirectory.resolve("platforms/${androidExtension.compileSdkVersion}/android.jar")) + androidExtension.libraryRequests.map { androidExtension.sdkDirectory.resolve("platforms/${androidExtension.compileSdkVersion}/optional/${it.name}.jar") } private fun getAaptRulesFile() = androidExtension.aaptAdditionalParameters .zipWithNext { cmd, param -> if (cmd == "--proguard") param else null } .filterNotNull() .firstOrNull { File(it).exists() } } typealias ProGuardIOEntry = Pair<File, File>
gpl-2.0
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ToolBarToolConnector.kt
1
2860
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.project import javafx.event.EventHandler import javafx.geometry.Orientation import javafx.geometry.Side import javafx.scene.control.Button import javafx.scene.control.ContextMenu import javafx.scene.control.MenuItem import javafx.scene.control.ToolBar import uk.co.nickthecoder.paratask.ToolBarTool /** * Connects the Tool with its tool bar. */ class ToolBarToolConnector( val projectWindow: ProjectWindow, val tool: ToolBarTool, val runToolOnEdit: Boolean, side: Side = Side.TOP) { val toolBar = ConnectedToolBar() var side: Side = side set(v) { if (field != v) { field = v projectWindow.removeToolBar(toolBar) projectWindow.addToolBar(toolBar, v) toolBar.orientation = if (v == Side.TOP || v == Side.BOTTOM) Orientation.HORIZONTAL else Orientation.VERTICAL } } init { toolBar.contextMenu = ContextMenu() val editItem = MenuItem("Edit Toolbar") editItem.onAction = EventHandler { editToolBar() } toolBar.contextMenu.items.add(editItem) } fun remove() { projectWindow.removeToolBar(toolBar) } fun update(buttons: List<Button>) { if (buttons.isEmpty()) { projectWindow.removeToolBar(toolBar) } else { with(toolBar.items) { clear() buttons.forEach { button -> add(button) } } if (toolBar.parent == null) { projectWindow.addToolBar(toolBar, side) } } } fun editToolBar() { tool.toolPane?.halfTab?.let { halfTab -> halfTab.projectTab.isSelected = true if (!runToolOnEdit) { halfTab.toolPane.parametersTab.isSelected = true } return } val projectTab = projectWindow.tabs.addTool(tool, run = runToolOnEdit) projectTab.left.toolPane.parametersTab.isSelected = true } inner class ConnectedToolBar : ToolBar() { val connector = this@ToolBarToolConnector } }
gpl-3.0
robertwb/incubator-beam
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/cookbook/FilterExamples.kt
9
9311
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.examples.kotlin.cookbook import com.google.api.services.bigquery.model.TableFieldSchema import com.google.api.services.bigquery.model.TableRow import com.google.api.services.bigquery.model.TableSchema import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO import org.apache.beam.sdk.io.gcp.bigquery.WriteResult import org.apache.beam.sdk.options.* import org.apache.beam.sdk.transforms.* import org.apache.beam.sdk.values.PCollection import java.util.logging.Logger /** * This is an example that demonstrates several approaches to filtering, and use of the Mean * transform. It shows how to dynamically set parameters by defining and using new pipeline options, * and how to use a value derived by the pipeline. * * * Concepts: The Mean transform; Options configuration; using pipeline-derived data as a side * input; approaches to filtering, selection, and projection. * * * The example reads public samples of weather data from BigQuery. It performs a projection on * the data, finds the global mean of the temperature readings, filters on readings for a single * given month, and then outputs only data (for that month) that has a mean temp smaller than the * derived global mean. * * * Note: Before running this example, you must create a BigQuery dataset to contain your output * table. * * * To execute this pipeline locally, specify the BigQuery table for the output: * * <pre>`--output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID * [--monthFilter=<month_number>] `</pre> * * * where optional parameter `--monthFilter` is set to a number 1-12. * * * To change the runner, specify: * * <pre>`--runner=YOUR_SELECTED_RUNNER `</pre> * * * See examples/kotlin/README.md for instructions about how to configure different runners. * * * The BigQuery input table defaults to `clouddataflow-readonly:samples.weather_stations` * and can be overridden with `--input`. */ object FilterExamples { // Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod. private const val WEATHER_SAMPLES_TABLE = "clouddataflow-readonly:samples.weather_stations" internal val LOG = Logger.getLogger(FilterExamples::class.java.name) internal const val MONTH_TO_FILTER = 7 /** * Examines each row in the input table. Outputs only the subset of the cells this example is * interested in-- the mean_temp and year, month, and day-- as a bigquery table row. */ internal class ProjectionFn : DoFn<TableRow, TableRow>() { @ProcessElement fun processElement(c: ProcessContext) { val row = c.element() // Grab year, month, day, mean_temp from the row val year = Integer.parseInt(row["year"] as String) val month = Integer.parseInt(row["month"] as String) val day = Integer.parseInt(row["day"] as String) val meanTemp = row["mean_temp"].toString().toDouble() // Prepares the data for writing to BigQuery by building a TableRow object val outRow = TableRow() .set("year", year) .set("month", month) .set("day", day) .set("mean_temp", meanTemp) c.output(outRow) } } /** * Implements 'filter' functionality. * * * Examines each row in the input table. Outputs only rows from the month monthFilter, which is * passed in as a parameter during construction of this DoFn. */ internal class FilterSingleMonthDataFn(private var monthFilter: Int?) : DoFn<TableRow, TableRow>() { @ProcessElement fun processElement(c: ProcessContext) { val row = c.element() val month = row["month"] if (month == this.monthFilter) { c.output(row) } } } /** * Examines each row (weather reading) in the input table. Output the temperature reading for that * row ('mean_temp'). */ internal class ExtractTempFn : DoFn<TableRow, Double>() { @ProcessElement fun processElement(c: ProcessContext) { val row = c.element() val meanTemp = java.lang.Double.parseDouble(row["mean_temp"].toString()) c.output(meanTemp) } } /** * Finds the global mean of the mean_temp for each day/record, and outputs only data that has a * mean temp larger than this global mean. */ internal class BelowGlobalMean(private var monthFilter: Int?) : PTransform<PCollection<TableRow>, PCollection<TableRow>>() { override fun expand(rows: PCollection<TableRow>): PCollection<TableRow> { // Extract the mean_temp from each row. val meanTemps = rows.apply(ParDo.of(ExtractTempFn())) // Find the global mean, of all the mean_temp readings in the weather data, // and prepare this singleton PCollectionView for use as a side input. val globalMeanTemp = meanTemps.apply(Mean.globally()).apply(View.asSingleton()) // Rows filtered to remove all but a single month val monthFilteredRows = rows.apply(ParDo.of(FilterSingleMonthDataFn(monthFilter))) // Then, use the global mean as a side input, to further filter the weather data. // By using a side input to pass in the filtering criteria, we can use a value // that is computed earlier in pipeline execution. // We'll only output readings with temperatures below this mean. return monthFilteredRows.apply( "ParseAndFilter", ParDo.of( object : DoFn<TableRow, TableRow>() { @ProcessElement fun processElement(c: ProcessContext) { val meanTemp = java.lang.Double.parseDouble(c.element()["mean_temp"].toString()) val gTemp = c.sideInput(globalMeanTemp) if (meanTemp < gTemp) { c.output(c.element()) } } }) .withSideInputs(globalMeanTemp)) } } /** * Options supported by [FilterExamples]. * * * Inherits standard configuration options. */ interface Options : PipelineOptions { @get:Description("Table to read from, specified as <project_id>:<dataset_id>.<table_id>") @get:Default.String(WEATHER_SAMPLES_TABLE) var input: String @get:Description("Table to write to, specified as <project_id>:<dataset_id>.<table_id>. The dataset_id must already exist") @get:Validation.Required var output: String @get:Description("Numeric value of month to filter on") @get:Default.Integer(MONTH_TO_FILTER) var monthFilter: Int? } /** Helper method to build the table schema for the output table. */ private fun buildWeatherSchemaProjection(): TableSchema { val fields = arrayListOf<TableFieldSchema>( TableFieldSchema().setName("year").setType("INTEGER"), TableFieldSchema().setName("month").setType("INTEGER"), TableFieldSchema().setName("day").setType("INTEGER"), TableFieldSchema().setName("mean_temp").setType("FLOAT") ) return TableSchema().setFields(fields) } @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val options = PipelineOptionsFactory.fromArgs(*args).withValidation() as Options val p = Pipeline.create(options) val schema = buildWeatherSchemaProjection() p.apply(BigQueryIO.readTableRows().from(options.input)) .apply(ParDo.of(ProjectionFn())) .apply(BelowGlobalMean(options.monthFilter)) .apply<WriteResult>( BigQueryIO.writeTableRows() .to(options.output) .withSchema(schema) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)) p.run().waitUntilFinish() } }
apache-2.0
nemerosa/ontrack
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/AutoPromotionPropertyMutationProvider.kt
1
3199
package net.nemerosa.ontrack.extension.general import graphql.Scalars.GraphQLString import graphql.schema.GraphQLInputObjectField import graphql.schema.GraphQLList import graphql.schema.GraphQLNonNull import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.graphql.schema.MutationInput import net.nemerosa.ontrack.graphql.schema.PropertyMutationProvider import net.nemerosa.ontrack.graphql.schema.optionalStringInputField import net.nemerosa.ontrack.model.structure.ProjectEntity import net.nemerosa.ontrack.model.structure.PromotionLevel import net.nemerosa.ontrack.model.structure.PropertyType import net.nemerosa.ontrack.model.structure.StructureService import org.springframework.stereotype.Component import kotlin.reflect.KClass @Component class AutoPromotionPropertyMutationProvider( private val structureService: StructureService, ) : PropertyMutationProvider<AutoPromotionProperty> { override val propertyType: KClass<out PropertyType<AutoPromotionProperty>> = AutoPromotionPropertyType::class override val mutationNameFragment: String = "AutoPromotion" override val inputFields: List<GraphQLInputObjectField> = listOf( GraphQLInputObjectField.newInputObjectField() .name(AutoPromotionProperty::validationStamps.name) .description("List of needed validation stamps") .type(GraphQLList(GraphQLNonNull(GraphQLString))) .build(), optionalStringInputField(AutoPromotionProperty::include.name, "Regular expression to include validation stamps by name"), optionalStringInputField(AutoPromotionProperty::exclude.name, "Regular expression to exclude validation stamps by name"), GraphQLInputObjectField.newInputObjectField() .name(AutoPromotionProperty::promotionLevels.name) .description("List of needed promotion levels") .type(GraphQLList(GraphQLNonNull(GraphQLString))) .build(), ) override fun readInput(entity: ProjectEntity, input: MutationInput): AutoPromotionProperty { if (entity is PromotionLevel) { val validationStamps = input.getInput<List<String>>(AutoPromotionProperty::validationStamps.name) ?.mapNotNull { structureService.findValidationStampByName(entity.project.name, entity.branch.name, it).getOrNull() } ?: emptyList() val promotionLevels = input.getInput<List<String>>(AutoPromotionProperty::promotionLevels.name) ?.mapNotNull { structureService.findPromotionLevelByName(entity.project.name, entity.branch.name, it).getOrNull() } ?: emptyList() return AutoPromotionProperty( validationStamps = validationStamps, include = input.getInput<String>(AutoPromotionProperty::include.name) ?: "", exclude = input.getInput<String>(AutoPromotionProperty::exclude.name) ?: "", promotionLevels = promotionLevels, ) } else { throw IllegalStateException("Parent entity must be a promotion level") } } }
mit
cfieber/spinnaker-gradle-project
spinnaker-extensions/src/functionaltest/kotlin/com/netflix/spinnaker/gradle/extension/SpinnakerExtensionGradlePluginFunctionalTest.kt
1
1594
/* * Copyright 2019 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.gradle.extension import java.io.File import org.gradle.testkit.runner.GradleRunner import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertTrue /** * Functional test for the 'com.netflix.spinnaker.gradle.extension' plugin. */ class SpinnakerExtensionGradlePluginFunctionalTest { @Test fun `can run task`() { // Setup the test build val projectDir = File("build/functionaltest") projectDir.mkdirs() projectDir.resolve("settings.gradle").writeText("") projectDir.resolve("build.gradle").writeText(""" plugins { id('io.spinnaker.plugin.bundler') } """) // Run the build val runner = GradleRunner.create() runner.forwardOutput() runner.withPluginClasspath() runner.withArguments("collectPluginZips") runner.withProjectDir(projectDir) val result = runner.build() // Verify the result assertTrue(result.output.contains("BUILD SUCCESSFUL")) } }
apache-2.0
nemerosa/ontrack
ontrack-extension-scm/src/test/java/net/nemerosa/ontrack/extension/scm/catalog/api/CatalogGraphQLIT.kt
1
13591
package net.nemerosa.ontrack.extension.scm.catalog.api import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.scm.catalog.CatalogFixtures.entry import net.nemerosa.ontrack.extension.scm.catalog.CatalogFixtures.team import net.nemerosa.ontrack.extension.scm.catalog.CatalogLinkService import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalog import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalogAccessFunction import net.nemerosa.ontrack.extension.scm.catalog.mock.MockSCMCatalogProvider import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.json.getTextField import net.nemerosa.ontrack.model.security.Roles import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class CatalogGraphQLIT : AbstractQLKTITJUnit4Support() { @Autowired private lateinit var scmCatalog: SCMCatalog @Autowired private lateinit var catalogLinkService: CatalogLinkService @Autowired private lateinit var scmCatalogProvider: MockSCMCatalogProvider @Test fun `SCM catalog stats per team`() { scmCatalogProvider.clear() // Registration of mock entries with their teams val entries = listOf( entry( scm = "mocking", repository = "project/repository-1", config = "my-config", teams = listOf( team("team-1") ) ), entry( scm = "mocking", repository = "project/repository-2", config = "my-config", teams = listOf( team("team-1") ) ), entry( scm = "mocking", repository = "project/repository-3", config = "my-config", teams = listOf( team("team-1") ) ), entry( scm = "mocking", repository = "project/repository-4", config = "my-config", teams = listOf( team("team-2") ) ), entry( scm = "mocking", repository = "project/repository-5", config = "my-config", teams = listOf( team("team-2") ) ), entry( scm = "mocking", repository = "project/repository-6", config = "my-config", teams = listOf( team("team-3"), ) ), entry( scm = "mocking", repository = "project/repository-7", config = "my-config", teams = listOf( team("team-4"), team("team-5"), ) ), ) entries.forEach { entry -> scmCatalogProvider.storeEntry(entry) } // Collection of entries scmCatalog.collectSCMCatalog { println(it) } // Gets stats about teams asAdmin { run( """{ scmCatalogTeams { id entryCount entries { repository } } }""" ) { data -> val scmCatalogTeams = data.path("scmCatalogTeams") assertEquals(5, scmCatalogTeams.size()) assertEquals( mapOf( "id" to "team-1", "entryCount" to 3, "entries" to listOf( mapOf("repository" to "project/repository-1"), mapOf("repository" to "project/repository-2"), mapOf("repository" to "project/repository-3"), ) ).asJson(), scmCatalogTeams.find { it.getTextField("id") == "team-1" } ) assertEquals( mapOf( "id" to "team-2", "entryCount" to 2, "entries" to listOf( mapOf("repository" to "project/repository-4"), mapOf("repository" to "project/repository-5"), ) ).asJson(), scmCatalogTeams.find { it.getTextField("id") == "team-2" } ) assertEquals( mapOf( "id" to "team-3", "entryCount" to 1, "entries" to listOf( mapOf("repository" to "project/repository-6"), ) ).asJson(), scmCatalogTeams.find { it.getTextField("id") == "team-3" } ) assertEquals( mapOf( "id" to "team-4", "entryCount" to 1, "entries" to listOf( mapOf("repository" to "project/repository-7"), ) ).asJson(), scmCatalogTeams.find { it.getTextField("id") == "team-4" } ) assertEquals( mapOf( "id" to "team-5", "entryCount" to 1, "entries" to listOf( mapOf("repository" to "project/repository-7"), ) ).asJson(), scmCatalogTeams.find { it.getTextField("id") == "team-5" } ) } } // Gets stats about team count asAdmin { run( """{ scmCatalogTeamStats { teamCount entryCount } }""" ) { data -> assertEquals( mapOf( "scmCatalogTeamStats" to listOf( mapOf("teamCount" to 2, "entryCount" to 1), mapOf("teamCount" to 1, "entryCount" to 6), ) ).asJson(), data ) } } } @Test fun `Collection of entries and linking`() { scmCatalogProvider.clear() // Registration of mock entry val entry = entry(scm = "mocking", repository = "project/repository", config = "my-config") scmCatalogProvider.storeEntry(entry) // Collection of entries scmCatalog.collectSCMCatalog { println(it) } // Checks entry has been collected val collectionData = withGrantViewToAll { asUserWith<SCMCatalogAccessFunction, JsonNode> { run( """{ scmCatalog { pageItems { entry { scm config repository repositoryPage } } } }""" ) } } val item = collectionData["scmCatalog"]["pageItems"][0] assertEquals("mocking", item["entry"]["scm"].asText()) assertEquals("my-config", item["entry"]["config"].asText()) assertEquals("project/repository", item["entry"]["repository"].asText()) assertEquals("uri:project/repository", item["entry"]["repositoryPage"].asText()) // Search on orphan entries val orphanData = withGrantViewToAll { asUserWith<SCMCatalogAccessFunction, JsonNode> { run( """{ scmCatalog(link: "UNLINKED") { pageItems { entry { repository } project { name } } } }""" ) } } assertNotNull(orphanData) { val orphanItem = it["scmCatalog"]["pageItems"][0] assertEquals("project/repository", orphanItem["entry"]["repository"].asText()) assertTrue(orphanItem["project"].isNull, "Entry is not linked") } // Link with one project val project = project { // Collection of catalog links scmCatalogProvider.linkEntry(entry, this) catalogLinkService.computeCatalogLinks() // Checks the link has been recorded val linkedEntry = catalogLinkService.getSCMCatalogEntry(this) assertNotNull(linkedEntry, "Project is linked to a SCM catalog entry") { assertEquals("mocking", it.scm) assertEquals("my-config", it.config) assertEquals("project/repository", it.repository) assertEquals("uri:project/repository", it.repositoryPage) } // Getting the SCM entry through GraphQL & project root val data = withGrantViewToAll { asUserWith<SCMCatalogAccessFunction, JsonNode> { run( """ query ProjectInfo { projects(id: $id) { scmCatalogEntry { scm config repository repositoryPage } } } """ ) } } // Checking data assertNotNull(data) { val projectItem = it["projects"][0]["scmCatalogEntry"] assertEquals("mocking", projectItem["scm"].asText()) assertEquals("my-config", projectItem["config"].asText()) assertEquals("project/repository", projectItem["repository"].asText()) assertEquals("uri:project/repository", projectItem["repositoryPage"].asText()) } // Getting the data through GraphQL & catalog entries val entryCollectionData = withGrantViewToAll { asUserWith<SCMCatalogAccessFunction, JsonNode> { run( """{ scmCatalog { pageItems { project { name } } } }""" ) } } assertNotNull(entryCollectionData) { val project = it["scmCatalog"]["pageItems"][0]["project"] assertEquals(name, project["name"].asText()) } } // Search on linked entries val data = withGrantViewToAll { asUserWith<SCMCatalogAccessFunction, JsonNode> { run( """{ scmCatalog(link: "LINKED") { pageItems { project { name } } } }""" ) } } assertNotNull(data) { val projectItem = it["scmCatalog"]["pageItems"][0]["project"] assertEquals(project.name, projectItem["name"].asText()) } } @Test fun `SCM Catalog accessible to administrators in view-to-all mode`() { scmCatalogTest { withGrantViewToAll { asAdmin(it) } } } @Test fun `SCM Catalog accessible to administrators in restricted mode`() { scmCatalogTest { withNoGrantViewToAll { asAdmin(it) } } } @Test fun `SCM Catalog accessible to global read only`() { scmCatalogTest { withNoGrantViewToAll { asAccountWithGlobalRole(Roles.GLOBAL_READ_ONLY, it) } } } private fun scmCatalogTest(setup: (code: () -> Unit) -> Unit) { // Collection of entries val entry = entry(scm = "mocking") scmCatalogProvider.clear() scmCatalogProvider.storeEntry(entry) scmCatalog.collectSCMCatalog { println(it) } // Link with one project val project = project { scmCatalogProvider.linkEntry(entry, this) catalogLinkService.computeCatalogLinks() } // Checks rights setup { val data = run( """{ scmCatalog(link: "LINKED") { pageItems { project { name } } } }""" ) assertNotNull(data) { val entryItem = it["scmCatalog"]["pageItems"][0] assertEquals(project.name, entryItem["project"]["name"].asText()) } } } }
mit
chibatching/Kotpref
kotpref/src/main/kotlin/com/chibatching/kotpref/KotprefModel.kt
1
3936
package com.chibatching.kotpref import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.os.SystemClock import androidx.annotation.CallSuper import com.chibatching.kotpref.pref.PreferenceProperty import kotlin.reflect.KProperty public abstract class KotprefModel( private val contextProvider: ContextProvider = StaticContextProvider, private val preferencesProvider: PreferencesProvider = defaultPreferenceProvider() ) { public constructor( context: Context, preferencesProvider: PreferencesProvider = defaultPreferenceProvider() ) : this( ContextProvider { context.applicationContext }, preferencesProvider ) internal var kotprefInTransaction: Boolean = false internal var kotprefTransactionStartTime: Long = Long.MAX_VALUE internal val kotprefProperties: MutableMap<String, PreferenceProperty> = mutableMapOf() /** * Application Context */ public val context: Context get() = contextProvider.getApplicationContext() /** * Preference file name */ public open val kotprefName: String = javaClass.simpleName /** * commit() all properties in this pref by default instead of apply() */ public open val commitAllPropertiesByDefault: Boolean = false /** * Preference read/write mode */ public open val kotprefMode: Int = Context.MODE_PRIVATE /** * Internal shared preferences. * This property will be initialized on use. */ internal val kotprefPreference: KotprefPreferences by lazy { KotprefPreferences(preferencesProvider.get(context, kotprefName, kotprefMode)) } /** * Internal shared preferences editor. */ internal var kotprefEditor: KotprefPreferences.KotprefEditor? = null /** * SharedPreferences instance exposed. * Use carefully when during bulk edit, it may cause inconsistent with internal data of Kotpref. */ public val preferences: SharedPreferences get() = kotprefPreference /** * Clear all preferences in this model */ @CallSuper public open fun clear() { beginBulkEdit() kotprefEditor!!.clear() commitBulkEdit() } /** * Begin bulk edit mode. You must commit or cancel after bulk edit finished. */ @SuppressLint("CommitPrefEdits") public fun beginBulkEdit() { kotprefInTransaction = true kotprefTransactionStartTime = SystemClock.uptimeMillis() kotprefEditor = kotprefPreference.KotprefEditor(kotprefPreference.edit()) } /** * Commit values set in the bulk edit mode to preferences. */ public fun commitBulkEdit() { kotprefEditor!!.apply() kotprefInTransaction = false } /** * Commit values set in the bulk edit mode to preferences immediately, in blocking manner. */ public fun blockingCommitBulkEdit() { kotprefEditor!!.commit() kotprefInTransaction = false } /** * Cancel bulk edit mode. Values set in the bulk mode will be rolled back. */ public fun cancelBulkEdit() { kotprefEditor = null kotprefInTransaction = false } /** * Get preference key for a property. * @param property property delegated to Kotpref * @return preference key */ public fun getPrefKey(property: KProperty<*>): String? { return kotprefProperties[property.name]?.preferenceKey } /** * Remove entry from SharedPreferences * @param property property to remove */ @SuppressLint("ApplySharedPref") public fun remove(property: KProperty<*>) { preferences.edit().remove(getPrefKey(property)).apply { if (commitAllPropertiesByDefault) { commit() } else { apply() } } } }
apache-2.0
jraska/github-client
core-testing/src/main/java/com/jraska/github/client/RecordingWebLinkLauncher.kt
1
362
package com.jraska.github.client import okhttp3.HttpUrl class RecordingWebLinkLauncher : WebLinkLauncher { private val linksLaunched = mutableListOf<HttpUrl>() fun linksLaunched(): List<HttpUrl> = linksLaunched override fun launchOnWeb(url: HttpUrl) { linksLaunched.add(url) } } fun Fakes.recordingWebLinkLauncher() = RecordingWebLinkLauncher()
apache-2.0
olonho/carkot
translator/src/test/kotlin/tests/null_comparison_1/null_comparison_1.kt
1
697
class null_comparison_1_class fun null_comparison_1_getClass(): null_comparison_1_class? { return null } fun null_comparison_1(): Int { val a: null_comparison_1_class? = null_comparison_1_getClass() println(if (a == null) 555 else 9990) if (a == null) { return 87 } return 945 } fun null_comparison_1_reassigned(): Int { var a: null_comparison_1_class? = null_comparison_1_class() a = null_comparison_1_getClass() if (a == null) { return 87 } return 945 } fun null_comparison_1_declaration(): Int { val a: null_comparison_1_class? a = null_comparison_1_getClass() if (a == null) { return 87 } return 945 }
mit
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/forge/inspections/sideonly/MethodSideOnlyInspection.kt
1
5585
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClassType import com.intellij.psi.PsiMethod import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class MethodSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of @SideOnly in method declaration" override fun buildErrorString(vararg infos: Any): String { val error = infos[0] as Error return error.getErrorString(*SideOnlyUtil.getSubArray(infos)) } override fun getStaticDescription(): String? { return "A method in a class annotated for one side cannot be declared as being in the other side. " + "For example, a class which is annotated as @SideOnly(Side.SERVER) cannot contain a method which " + "is annotated as @SideOnly(Side.CLIENT). Since a class that is annotated with @SideOnly brings " + "everything with it, @SideOnly annotated methods are usually useless" } override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val error = infos[0] as Error val annotation = infos[3] as PsiAnnotation return if (annotation.isWritable && error === Error.METHOD_IN_WRONG_CLASS) { RemoveAnnotationInspectionGadgetsFix(annotation, "Remove @SideOnly annotation from method") } else { null } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitMethod(method: PsiMethod) { val psiClass = method.containingClass ?: return if (!SideOnlyUtil.beginningCheck(method)) { return } val (methodAnnotation, methodSide) = SideOnlyUtil.checkMethod(method) if (methodAnnotation == null) { return } val resolve = (method.returnType as? PsiClassType)?.resolve() val (returnAnnotation, returnSide) = if (resolve == null) null to Side.NONE else SideOnlyUtil.getSideForClass(resolve) if (returnAnnotation != null && returnSide !== Side.NONE && returnSide !== Side.INVALID && returnSide !== methodSide && methodSide !== Side.NONE && methodSide !== Side.INVALID ) { registerMethodError( method, Error.RETURN_TYPE_ON_WRONG_METHOD, methodAnnotation.renderSide(methodSide), returnAnnotation.renderSide(returnSide), method.getAnnotation(methodAnnotation.annotationName) ) } for ((classAnnotation, classSide) in SideOnlyUtil.checkClassHierarchy(psiClass)) { if (classAnnotation != null && classSide !== Side.NONE && classSide !== Side.INVALID) { if ( methodSide !== classSide && methodSide !== Side.NONE && methodSide !== Side.INVALID ) { registerMethodError( method, Error.METHOD_IN_WRONG_CLASS, methodAnnotation.renderSide(methodSide), classAnnotation.renderSide(classSide), method.getAnnotation(methodAnnotation.annotationName) ) } if (returnAnnotation != null && returnSide !== Side.NONE && returnSide !== Side.INVALID) { if (returnSide !== classSide) { registerMethodError( method, Error.RETURN_TYPE_IN_WRONG_CLASS, classAnnotation.renderSide(classSide), returnAnnotation.renderSide(returnSide), method.getAnnotation(methodAnnotation.annotationName) ) } } break } } } } } enum class Error { METHOD_IN_WRONG_CLASS { override fun getErrorString(vararg infos: Any): String { return "Method annotated with " + infos[0] + " cannot be declared inside a class annotated with " + infos[1] + "." } }, RETURN_TYPE_ON_WRONG_METHOD { override fun getErrorString(vararg infos: Any): String { return "Method annotated with " + infos[0] + " cannot return a type annotated with " + infos[1] + "." } }, RETURN_TYPE_IN_WRONG_CLASS { override fun getErrorString(vararg infos: Any): String { return "Method in a class annotated with " + infos[0] + " cannot return a type annotated with " + infos[1] + "." } }; abstract fun getErrorString(vararg infos: Any): String } }
mit
DemonWav/IntelliJBukkitSupport
src/main/kotlin/errorreporter/ErrorReporter.kt
1
5352
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.errorreporter import com.demonwav.mcdev.update.PluginUtil import com.intellij.diagnostic.DiagnosticBundle import com.intellij.diagnostic.LogMessage import com.intellij.ide.DataManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.idea.IdeaLogger import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.diagnostic.ErrorReportSubmitter import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.SubmittedReportInfo import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.util.Consumer import java.awt.Component class ErrorReporter : ErrorReportSubmitter() { private val ignoredErrorMessages = listOf( "Key com.demonwav.mcdev.translations.TranslationFoldingSettings duplicated", "Inspection #EntityConstructor has no description" ) private val baseUrl = "https://github.com/minecraft-dev/MinecraftDev/issues" override fun getReportActionText() = "Report to Minecraft Dev GitHub Issue Tracker" override fun submit( events: Array<out IdeaLoggingEvent>, additionalInfo: String?, parentComponent: Component, consumer: Consumer<in SubmittedReportInfo> ): Boolean { val dataContext = DataManager.getInstance().getDataContext(parentComponent) val project = CommonDataKeys.PROJECT.getData(dataContext) val event = events[0] val errorMessage = event.throwableText if (errorMessage.isNotBlank() && ignoredErrorMessages.any(errorMessage::contains)) { val task = object : Task.Backgroundable(project, "Ignored error") { override fun run(indicator: ProgressIndicator) { consumer.consume(SubmittedReportInfo(null, null, SubmittedReportInfo.SubmissionStatus.DUPLICATE)) } } if (project == null) { task.run(EmptyProgressIndicator()) } else { ProgressManager.getInstance().run(task) } return true } val errorData = ErrorData(event.throwable, IdeaLogger.ourLastActionId) errorData.description = additionalInfo errorData.message = event.message PluginManagerCore.getPlugin(PluginUtil.PLUGIN_ID)?.let { plugin -> errorData.pluginName = plugin.name errorData.pluginVersion = plugin.version } val data = event.data if (data is LogMessage) { errorData.throwable = data.throwable errorData.attachments = data.includedAttachments } val (reportValues, attachments) = errorData.formatErrorData() val task = AnonymousFeedbackTask( project, "Submitting error report", true, reportValues, attachments, { htmlUrl, token, isDuplicate -> val type = if (isDuplicate) { SubmittedReportInfo.SubmissionStatus.DUPLICATE } else { SubmittedReportInfo.SubmissionStatus.NEW_ISSUE } val message = if (!isDuplicate) { "<html>Created Issue #$token successfully. <a href=\"$htmlUrl\">View issue.</a></html>" } else { "<html>Commented on existing Issue #$token successfully. " + "<a href=\"$htmlUrl\">View comment.</a></html>" } NotificationGroupManager.getInstance().getNotificationGroup("Error Report").createNotification( DiagnosticBundle.message("error.report.title"), message, NotificationType.INFORMATION ).setListener(NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project) val reportInfo = SubmittedReportInfo(htmlUrl, "Issue #$token", type) consumer.consume(reportInfo) }, { e -> val message = "<html>Error Submitting Issue: ${e.message}<br>Consider opening an issue on " + "<a href=\"$baseUrl\">the GitHub issue tracker.</a></html>" NotificationGroupManager.getInstance().getNotificationGroup("Error Report").createNotification( DiagnosticBundle.message("error.report.title"), message, NotificationType.ERROR, ).setListener(NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project) consumer.consume(SubmittedReportInfo(null, null, SubmittedReportInfo.SubmissionStatus.FAILED)) } ) if (project == null) { task.run(EmptyProgressIndicator()) } else { ProgressManager.getInstance().run(task) } return true } }
mit
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/util/ContentResolverUtil.kt
1
398
package yuku.alkitab.base.util import android.content.ContentResolver import android.net.Uri /** * Returns null on error */ fun ContentResolver.safeQuery( uri: Uri, projection: Array<String?>?, selection: String?, selectionArgs: Array<String?>?, sortOrder: String?, ) = try { query(uri, projection, selection, selectionArgs, sortOrder, null) } catch (e: Exception) { null }
apache-2.0
oboehm/jfachwert
src/main/kotlin/de/jfachwert/pruefung/NoopVerfahren.kt
1
1599
/* * Copyright (c) 2017-2020 by Oliver Boehm * * 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 orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 26.03.2017 by oboehm ([email protected]) */ package de.jfachwert.pruefung import de.jfachwert.PruefzifferVerfahren import java.io.Serializable /** * "Noop" steht fuer "No Operation" und bedeutet, dass mit diesem Pruefziffer- * Verfahren keine Validierung stattfindet. Dies kann immer dann verwendet * werden, wenn man die Validierung abschalten will. * * @author oboehm * @since 0.1.0 */ open class NoopVerfahren<T : Serializable> : PruefzifferVerfahren<T> { /** * Meistens ist die letzte Ziffer die Pruefziffer, die hierueber abgefragt * werden kann. * * @param wert Fachwert oder gekapselter Wert * @return meist ein Wert zwischen 0 und 9 */ override fun getPruefziffer(wert: T): T { return wert } /** * Berechnet die Pruefziffer des uebergebenen Wertes. * * @param wert Wert * @return errechnete Pruefziffer */ override fun berechnePruefziffer(wert: T): T { return wert } }
apache-2.0
cashapp/sqldelight
sqldelight-compiler/src/test/query-interface-fixtures/query-requires-type/output/com/sample/JoinedWithUsing.kt
1
159
package com.sample import kotlin.Boolean import kotlin.String public data class JoinedWithUsing( public val name: String, public val is_cool: Boolean, )
apache-2.0
Ribesg/anko
dsl/src/org/jetbrains/android/anko/DSLGenerator.kt
4
3121
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko import org.jetbrains.android.anko.config.AnkoConfiguration import org.jetbrains.android.anko.generator.GenerationState import org.jetbrains.android.anko.render.RenderFacade import org.jetbrains.android.anko.utils.ClassTree import java.io.File class DSLGenerator( val sourceDirectory: File, val platformJars: List<File>, val versionJars: List<File>, val config: AnkoConfiguration, val classTree: ClassTree? = null): Runnable { private val mvnManifest: String get() = File("dsl/props/mvn/AndroidManifest.xml").readText() private fun copy(original: String) { val originalFile = File("dsl/props/mvn/$original") val toCreateFile = File(config.outputDirectory, original) originalFile.copyTo(toCreateFile) } private fun copy(original: String, process: (String) -> String) { val contents = process(File("dsl/props/mvn/$original").readText()) File(config.outputDirectory, original).writeText(contents) } override fun run() { val classTree = this.classTree ?: ClassProcessor(platformJars, versionJars).genClassTree() val generationState = GenerationState(classTree, config) val renderer = RenderFacade(generationState) Writer(renderer).write() if (config.generateMavenArtifact) { // Create res directory val resDirectory = File(config.outputDirectory, "src/main/res/") if (!resDirectory.exists()) { resDirectory.mkdirs() } val artifactVersion = config.version val sdkVersion = File(sourceDirectory, "version.txt").readText() // Write manifest val manifest = mvnManifest.replace("%SDK_VERSION", sdkVersion) File(config.outputDirectory, "src/main/AndroidManifest.xml").writeText(manifest) // Copy gradle wrapper copy("gradlew") copy("gradlew.bat") copy("gradle/wrapper/gradle-wrapper.jar") copy("gradle/wrapper/gradle-wrapper.properties") // Copy gradle build files fun String.substVersions(): String { return replace("%SDK_VERSION", sdkVersion) .replace("%ARTIFACT_VERSION", artifactVersion) .replace("%ORIGINAL_VERSION", config.version) } copy("gradle.properties") { it.substVersions() } copy("build.gradle") { it.substVersions() } } } }
apache-2.0
Ribesg/anko
dsl/testData/functional/appcompat-v7/ComplexListenerSetterTest.kt
2
458
fun android.support.v7.widget.SearchView.onQueryTextListener(init: __SearchView_OnQueryTextListener.() -> Unit) { val listener = __SearchView_OnQueryTextListener() listener.init() setOnQueryTextListener(listener) } fun android.support.v7.widget.SearchView.onSuggestionListener(init: __SearchView_OnSuggestionListener.() -> Unit) { val listener = __SearchView_OnSuggestionListener() listener.init() setOnSuggestionListener(listener) }
apache-2.0
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/RxRegTool.kt
1
16342
package com.tamsiree.rxkit import com.tamsiree.rxkit.RxConstTool.REGEX_CHZ import com.tamsiree.rxkit.RxConstTool.REGEX_DATE import com.tamsiree.rxkit.RxConstTool.REGEX_EMAIL import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD15 import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD18 import com.tamsiree.rxkit.RxConstTool.REGEX_IP import com.tamsiree.rxkit.RxConstTool.REGEX_MOBILE_EXACT import com.tamsiree.rxkit.RxConstTool.REGEX_MOBILE_SIMPLE import com.tamsiree.rxkit.RxConstTool.REGEX_TEL import com.tamsiree.rxkit.RxConstTool.REGEX_URL import com.tamsiree.rxkit.RxConstTool.REGEX_USERNAME import com.tamsiree.rxkit.RxDataTool.Companion.isNullString import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import java.util.regex.Pattern /** * @author Tamsiree * @date 2017/3/15 */ object RxRegTool { //--------------------------------------------正则表达式----------------------------------------- /** * 原文链接:http://caibaojian.com/regexp-example.html * 提取信息中的网络链接:(h|H)(r|R)(e|E)(f|F) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)? * 提取信息中的邮件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* * 提取信息中的图片链接:(s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)? * 提取信息中的IP地址:(\d+)\.(\d+)\.(\d+)\.(\d+) * 提取信息中的中国电话号码(包括移动和固定电话):(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14} * 提取信息中的中国邮政编码:[1-9]{1}(\d+){5} * 提取信息中的中国身份证号码:\d{18}|\d{15} * 提取信息中的整数:\d+ * 提取信息中的浮点数(即小数):(-?\d*)\.?\d+ * 提取信息中的任何数字 :(-?\d*)(\.\d+)? * 提取信息中的中文字符串:[\u4e00-\u9fa5]* * 提取信息中的双字节字符串 (汉字):[^\x00-\xff]* */ /** * 判断是否为真实手机号 * * @param mobiles * @return */ @JvmStatic fun isMobile(mobiles: String?): Boolean { val p = Pattern.compile("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$") val m = p.matcher(mobiles) return m.matches() } /** * 验证银卡卡号 * * @param cardNo * @return */ @JvmStatic fun isBankCard(cardNo: String?): Boolean { val p = Pattern.compile("^\\d{16,19}$|^\\d{6}[- ]\\d{10,13}$|^\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4,7}$") val m = p.matcher(cardNo) return m.matches() } /** * 15位和18位身份证号码的正则表达式 身份证验证 * * @param idCard * @return */ @JvmStatic fun validateIdCard(idCard: String?): Boolean { // 15位和18位身份证号码的正则表达式 val regIdCard = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$" val p = Pattern.compile(regIdCard) return p.matcher(idCard).matches() } //=========================================正则表达式============================================= /** * 验证手机号(简单) * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isMobileSimple(string: String?): Boolean { return isMatch(REGEX_MOBILE_SIMPLE, string) } /** * 验证手机号(精确) * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isMobileExact(string: String?): Boolean { return isMatch(REGEX_MOBILE_EXACT, string) } /** * 验证电话号码 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isTel(string: String?): Boolean { return isMatch(REGEX_TEL, string) } /** * 验证身份证号码15位 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIDCard15(string: String?): Boolean { return isMatch(REGEX_IDCARD15, string) } /** * 验证身份证号码18位 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIDCard18(string: String?): Boolean { return isMatch(REGEX_IDCARD18, string) } /** * 验证身份证号码15或18位 包含以x结尾 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIDCard(string: String?): Boolean { return isMatch(REGEX_IDCARD, string) } /*********************************** 身份证验证开始 */ /** * 身份证号码验证 1、号码的结构 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码, * 八位数字出生日期码,三位数字顺序码和一位数字校验码。 2、地址码(前六位数) * 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。 3、出生日期码(第七位至十四位) * 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 4、顺序码(第十五位至十七位) * 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号, 顺序码的奇数分配给男性,偶数分配给女性。 5、校验码(第十八位数) * (1)十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和 * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 * (2)计算模 Y = mod(S, 11) (3)通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2 */ /** * 功能:身份证的有效验证 * * @param IDStr 身份证号 * @return 有效:返回"有效" 无效:返回String信息 * @throws ParseException */ @JvmStatic fun IDCardValidate(IDStr: String): String { var errorInfo = "" // 记录错误信息 val ValCodeArr = arrayOf("1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2") val Wi = arrayOf("7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2") var Ai = "" // ================ 号码的长度 15位或18位 ================ if (IDStr.length != 15 && IDStr.length != 18) { errorInfo = "身份证号码长度应该为15位或18位。" return errorInfo } // =======================(end)======================== // ================ 数字 除最后以为都为数字 ================ if (IDStr.length == 18) { Ai = IDStr.substring(0, 17) } else if (IDStr.length == 15) { Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15) } if (isNumeric(Ai) == false) { errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。" return errorInfo } // =======================(end)======================== // ================ 出生年月是否有效 ================ val strYear = Ai.substring(6, 10) // 年份 val strMonth = Ai.substring(10, 12) // 月份 val strDay = Ai.substring(12, 14) // 月份 if (isDate("$strYear-$strMonth-$strDay") == false) { errorInfo = "身份证生日无效。" return errorInfo } val gc = GregorianCalendar() val s = SimpleDateFormat("yyyy-MM-dd") try { if (gc[Calendar.YEAR] - strYear.toInt() > 150 || gc.time.time - s.parse( "$strYear-$strMonth-$strDay").time < 0) { errorInfo = "身份证生日不在有效范围。" return errorInfo } } catch (e: NumberFormatException) { e.printStackTrace() } catch (e: ParseException) { e.printStackTrace() } if (strMonth.toInt() > 12 || strMonth.toInt() == 0) { errorInfo = "身份证月份无效" return errorInfo } if (strDay.toInt() > 31 || strDay.toInt() == 0) { errorInfo = "身份证日期无效" return errorInfo } // =====================(end)===================== // ================ 地区码时候有效 ================ val h = GetAreaCode() if (h[Ai.substring(0, 2)] == null) { errorInfo = "身份证地区编码错误。" return errorInfo } // ============================================== // ================ 判断最后一位的值 ================ var TotalmulAiWi = 0 for (i in 0..16) { TotalmulAiWi = (TotalmulAiWi + Ai[i].toString().toInt() * Wi[i].toInt()) } val modValue = TotalmulAiWi % 11 val strVerifyCode = ValCodeArr[modValue] Ai = Ai + strVerifyCode if (IDStr.length == 18) { if (Ai == IDStr == false) { errorInfo = "身份证无效,不是合法的身份证号码" return errorInfo } } else { return "有效" } // =====================(end)===================== return "有效" } /** * 功能:设置地区编码 * * @return Hashtable 对象 */ private fun GetAreaCode(): Hashtable<String, String> { val hashtable = Hashtable<String, String>() hashtable["11"] = "北京" hashtable["12"] = "天津" hashtable["13"] = "河北" hashtable["14"] = "山西" hashtable["15"] = "内蒙古" hashtable["21"] = "辽宁" hashtable["22"] = "吉林" hashtable["23"] = "黑龙江" hashtable["31"] = "上海" hashtable["32"] = "江苏" hashtable["33"] = "浙江" hashtable["34"] = "安徽" hashtable["35"] = "福建" hashtable["36"] = "江西" hashtable["37"] = "山东" hashtable["41"] = "河南" hashtable["42"] = "湖北" hashtable["43"] = "湖南" hashtable["44"] = "广东" hashtable["45"] = "广西" hashtable["46"] = "海南" hashtable["50"] = "重庆" hashtable["51"] = "四川" hashtable["52"] = "贵州" hashtable["53"] = "云南" hashtable["54"] = "西藏" hashtable["61"] = "陕西" hashtable["62"] = "甘肃" hashtable["63"] = "青海" hashtable["64"] = "宁夏" hashtable["65"] = "新疆" hashtable["71"] = "台湾" hashtable["81"] = "香港" hashtable["82"] = "澳门" hashtable["91"] = "国外" return hashtable } /** * 功能:判断字符串是否为数字 * * @param str * @return */ private fun isNumeric(str: String): Boolean { val pattern = Pattern.compile("[0-9]*") val isNum = pattern.matcher(str) return isNum.matches() } /** * 验证邮箱 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isEmail(string: String?): Boolean { return isMatch(REGEX_EMAIL, string) } /** * 验证URL * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isURL(string: String?): Boolean { return isMatch(REGEX_URL, string) } /** * 验证汉字 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isChz(string: String?): Boolean { return isMatch(REGEX_CHZ, string) } /** * 验证用户名 * * 取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isUsername(string: String?): Boolean { return isMatch(REGEX_USERNAME, string) } /** * 验证yyyy-MM-dd格式的日期校验,已考虑平闰年 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isDate(string: String?): Boolean { return isMatch(REGEX_DATE, string) } /** * 验证IP地址 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIP(string: String?): Boolean { return isMatch(REGEX_IP, string) } /** * string是否匹配regex正则表达式字符串 * * @param regex 正则表达式字符串 * @param string 要匹配的字符串 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isMatch(regex: String?, string: String?): Boolean { return !isNullString(string) && Pattern.matches(regex, string) } /** * 验证固定电话号码 * * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 * * **国家(地区) 代码 :**标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字, * 数字之后是空格分隔的国家(地区)代码。 * * **区号(城市代码):**这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— * 对不使用地区或城市代码的国家(地区),则省略该组件。 * * **电话号码:**这包含从 0 到 9 的一个或多个数字 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkPhone(phone: String?): Boolean { val regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$" return Pattern.matches(regex, phone) } /** * 验证整数(正整数和负整数) * * @param digit 一位或多位0-9之间的整数 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkDigit(digit: String?): Boolean { val regex = "\\-?[1-9]\\d+" return Pattern.matches(regex, digit) } /** * 验证整数和浮点数(正负整数和正负浮点数) * * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkDecimals(decimals: String?): Boolean { val regex = "\\-?[1-9]\\d+(\\.\\d+)?" return Pattern.matches(regex, decimals) } /** * 验证空白字符 * * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkBlankSpace(blankSpace: String?): Boolean { val regex = "\\s+" return Pattern.matches(regex, blankSpace) } /** * 验证日期(年月日) * * @param birthday 日期,格式:1992-09-03,或1992.09.03 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkBirthday(birthday: String?): Boolean { val regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}" return Pattern.matches(regex, birthday) } /** * 匹配中国邮政编码 * * @param postcode 邮政编码 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkPostcode(postcode: String?): Boolean { val regex = "[1-9]\\d{5}" return Pattern.matches(regex, postcode) } }
apache-2.0
varpeti/Suli
Android/work/varpe8/homeworks/06/HF06/app/src/androidTest/java/ml/varpeti/hf06/ExampleInstrumentedTest.kt
1
777
package ml.varpeti.hf06 import android.app.PendingIntent.getActivity import android.content.Intent import android.content.pm.ActivityInfo import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* import org.junit.Rule /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("ml.varpeti.hf06", appContext.packageName) } }
unlicense
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/exception/CardException.kt
1
794
package com.stripe.android.exception import com.stripe.android.core.StripeError import com.stripe.android.core.exception.StripeException import java.net.HttpURLConnection /** * An [Exception] indicating that there is a problem with a Card used for a request. * Card errors are the most common type of error you should expect to handle. * They result when the user enters a card that can't be charged for some reason. */ class CardException( stripeError: StripeError, requestId: String? = null ) : StripeException( stripeError, requestId, HttpURLConnection.HTTP_PAYMENT_REQUIRED ) { val code: String? = stripeError.code val param: String? = stripeError.param val declineCode: String? = stripeError.declineCode val charge: String? = stripeError.charge }
mit
zachgrayio/cmdloop
src/main/kotlin/io/zachgray/cmdloop/cmdloop.kt
1
262
package io.zachgray.cmdloop typealias CommandAction = (List<String>, CommandLoop) -> LoopControlOperator fun commandLoop(init: CommandLoopBuilder.() -> Unit) : CommandLoop { val builder = CommandLoopBuilder() builder.init() return builder.build() }
gpl-3.0
stripe/stripe-android
camera-core/src/main/java/com/stripe/android/camera/framework/util/FrameSaver.kt
1
2397
package com.stripe.android.camera.framework.util import androidx.annotation.CheckResult import androidx.annotation.RestrictTo import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.util.LinkedList /** * Save data frames for later retrieval. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) abstract class FrameSaver<Identifier, Frame, MetaData> { private val saveFrameMutex = Mutex() private val savedFrames = mutableMapOf<Identifier, LinkedList<Frame>>() /** * Determine how frames should be classified using [getSaveFrameIdentifier], and then store them * in a map of frames based on that identifier. * * This method keeps track of the total number of saved frames. If the total number or total * size exceeds the maximum allowed, the oldest frames will be dropped. */ suspend fun saveFrame(frame: Frame, metaData: MetaData) { val identifier = getSaveFrameIdentifier(frame, metaData) ?: return return saveFrameMutex.withLock { val maxSavedFrames = getMaxSavedFrames(identifier) val frames = savedFrames.getOrPut(identifier) { LinkedList() } frames.addFirst(frame) while (frames.size > maxSavedFrames) { // saved frames is over size limit, reduce until it's not removeFrame(identifier, frames) } } } /** * Retrieve a copy of the list of saved frames. */ @CheckResult fun getSavedFrames(): Map<Identifier, LinkedList<Frame>> = savedFrames.toMap() /** * Clear all saved frames */ suspend fun reset() = saveFrameMutex.withLock { savedFrames.clear() } protected abstract fun getMaxSavedFrames(savedFrameIdentifier: Identifier): Int /** * Determine if a data frame should be saved for future processing. * * If this method returns a non-null string, the frame will be saved under that identifier. */ protected abstract fun getSaveFrameIdentifier(frame: Frame, metaData: MetaData): Identifier? /** * Remove a frame from this list. The most recently added frames will be at the beginning of * this list, while the least recently added frames will be at the end. */ protected open fun removeFrame(identifier: Identifier, frames: LinkedList<Frame>) { frames.removeLast() } }
mit
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AddressElementActivityContract.kt
1
2553
package com.stripe.android.paymentsheet.addresselement import android.app.Activity import android.content.Context import android.content.Intent import androidx.activity.result.contract.ActivityResultContract import androidx.annotation.ColorInt import androidx.core.os.bundleOf import com.stripe.android.core.injection.DUMMY_INJECTOR_KEY import com.stripe.android.core.injection.InjectorKey import com.stripe.android.view.ActivityStarter import kotlinx.parcelize.Parcelize internal class AddressElementActivityContract : ActivityResultContract<AddressElementActivityContract.Args, AddressLauncherResult>() { override fun createIntent(context: Context, input: Args): Intent { val statusBarColor = (context as? Activity)?.window?.statusBarColor return Intent(context, AddressElementActivity::class.java) .putExtra(EXTRA_ARGS, input.copy(statusBarColor = statusBarColor)) } override fun parseResult(resultCode: Int, intent: Intent?) = intent?.getParcelableExtra<Result>(EXTRA_RESULT)?.addressOptionsResult ?: AddressLauncherResult.Canceled /** * Arguments for launching [AddressElementActivity] to collect an address. * * @param publishableKey the Stripe publishable key * @param config the paymentsheet configuration passed from the merchant * @param injectorKey Parameter needed to perform dependency injection. * If default, a new graph is created */ @Parcelize data class Args internal constructor( internal val publishableKey: String, internal val config: AddressLauncher.Configuration?, @InjectorKey internal val injectorKey: String = DUMMY_INJECTOR_KEY, @ColorInt internal val statusBarColor: Int? = null ) : ActivityStarter.Args { internal companion object { internal fun fromIntent(intent: Intent): Args? { return intent.getParcelableExtra(EXTRA_ARGS) } } } @Parcelize data class Result( val addressOptionsResult: AddressLauncherResult ) : ActivityStarter.Result { override fun toBundle() = bundleOf(EXTRA_RESULT to this) } internal companion object { const val EXTRA_ARGS = "com.stripe.android.paymentsheet.addresselement" + ".AddressElementActivityContract.extra_args" const val EXTRA_RESULT = "com.stripe.android.paymentsheet.addresselement" + ".AddressElementActivityContract.extra_result" } }
mit
Xenoage/Zong
core/src/com/xenoage/zong/core/music/util/StartOrStop.kt
1
252
package com.xenoage.zong.core.music.util /** * The border at which to search for musical elements, * i.e. either the start or the ending. */ enum class StartOrStop { /** Beginning of the element. */ Start, /** Ending of the element. */ Stop }
agpl-3.0
spring-cloud-samples/spring-cloud-contract-samples
producer_webflux_security/src/test/kotlin/com/ideabaker/samples/scc/security/securedproducerwebflux/contract/ContactBase.kt
1
2407
package com.ideabaker.samples.scc.security.securedproducerwebflux.contract import com.ideabaker.samples.scc.security.securedproducerwebflux.config.GlobalSecurityConfig import com.ideabaker.samples.scc.security.securedproducerwebflux.config.SpringSecurityWebFluxConfig import com.ideabaker.samples.scc.security.securedproducerwebflux.model.UserContact import com.ideabaker.samples.scc.security.securedproducerwebflux.service.ContactServiceProvider import com.ideabaker.samples.scc.security.securedproducerwebflux.web.ContactHandler import com.ideabaker.samples.scc.security.securedproducerwebflux.web.Routes import io.restassured.module.webtestclient.RestAssuredWebTestClient import org.junit.jupiter.api.BeforeEach import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary import reactor.core.publisher.Flux /** * * @author Arthur Kazemi<[email protected]> * @since 2019-06-23 22:41 */ @SpringBootTest(classes = [GlobalSecurityConfig::class, SpringSecurityWebFluxConfig::class, ContactBase.Config::class, Routes::class], webEnvironment = SpringBootTest.WebEnvironment.MOCK) abstract class ContactBase { @Autowired lateinit var context: ApplicationContext @BeforeEach fun setup() { RestAssuredWebTestClient.applicationContextSetup(this.context) } @Configuration @EnableAutoConfiguration class Config { @Bean @Primary fun contactHandler(contactService: ContactServiceProvider): ContactHandler { return ContactHandler(contactService = contactService) } @Bean @Primary fun contactService(): ContactServiceProvider { return MockContactService() } } internal class MockContactService : ContactServiceProvider { override fun contactSearch(pattern: String): Flux<UserContact> { if (pattern == "existing") { val contact1 = UserContact("1", "name 1", "[email protected]", true) val contact2 = UserContact("2", "name 2", "[email protected]", false) return Flux.fromArray(arrayOf(contact1, contact2)) } return Flux.empty() } } }
apache-2.0
Xenoage/Zong
core/src/com/xenoage/zong/core/music/MusicElement.kt
1
258
package com.xenoage.zong.core.music import com.xenoage.utils.annotations.Optimized import com.xenoage.utils.annotations.Reason.Performance /** * Interface for all musical elements, * like notes, rests, barlines or directions. */ interface MusicElement
agpl-3.0
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/service/job/PadLockJobService.kt
1
2837
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.service.job import android.app.job.JobParameters import android.app.job.JobService import android.os.PersistableBundle import com.pyamsoft.padlock.Injector import com.pyamsoft.padlock.PadLock import com.pyamsoft.padlock.PadLockComponent import com.pyamsoft.padlock.api.service.JobSchedulerCompat import com.pyamsoft.padlock.api.service.JobSchedulerCompat.JobType.RECHECK import com.pyamsoft.padlock.api.service.JobSchedulerCompat.JobType.SERVICE_TEMP_PAUSE import com.pyamsoft.padlock.model.service.Recheck import com.pyamsoft.padlock.service.RecheckPresenter import com.pyamsoft.padlock.api.service.ServiceManager import timber.log.Timber import javax.inject.Inject class PadLockJobService : JobService() { @field:Inject internal lateinit var presenter: RecheckPresenter @field:Inject internal lateinit var serviceManager: ServiceManager override fun onCreate() { super.onCreate() Injector.obtain<PadLockComponent>(applicationContext) .inject(this) } override fun onDestroy() { super.onDestroy() PadLock.getRefWatcher(this) .watch(this) } override fun onStopJob(params: JobParameters): Boolean { // Returns false to indicate do NOT reschedule return false } private fun handleServicePauseJob() { Timber.d("Restarting service") serviceManager.startService(true) } private fun handleRecheckJob(extras: PersistableBundle) { val packageName = requireNotNull(extras.getString(Recheck.EXTRA_PACKAGE_NAME)) val className = requireNotNull(extras.getString(Recheck.EXTRA_CLASS_NAME)) if (packageName.isNotBlank() && className.isNotBlank()) { Timber.d("Recheck requested for $packageName $className") presenter.recheck(packageName, className) } } override fun onStartJob(params: JobParameters): Boolean { val extras = params.extras val typeName = extras.getString(JobSchedulerCompat.KEY_JOB_TYPE) val type = JobSchedulerCompat.JobType.valueOf(requireNotNull(typeName)) when (type) { SERVICE_TEMP_PAUSE -> handleServicePauseJob() RECHECK -> handleRecheckJob(extras) } // Returns false to indicate this runs on main thread synchronously return false } }
apache-2.0
exponent/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/screencapture/ScreenCaptureModule.kt
2
2088
package abi42_0_0.expo.modules.screencapture import android.app.Activity import android.content.Context import android.view.WindowManager import abi42_0_0.org.unimodules.core.ExportedModule import abi42_0_0.org.unimodules.core.ModuleRegistry import abi42_0_0.org.unimodules.core.Promise import abi42_0_0.org.unimodules.core.errors.CurrentActivityNotFoundException import abi42_0_0.org.unimodules.core.interfaces.ActivityProvider import abi42_0_0.org.unimodules.core.interfaces.ExpoMethod class ScreenCaptureModule(context: Context) : ExportedModule(context) { private lateinit var mActivityProvider: ActivityProvider override fun getName(): String { return NAME } override fun onCreate(moduleRegistry: ModuleRegistry) { mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java) ScreenshotEventEmitter(context, moduleRegistry) } @ExpoMethod fun preventScreenCapture(promise: Promise) { val activity = getCurrentActivity() activity.runOnUiThread { try { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE) } catch (exception: Exception) { promise.reject(ERROR_CODE_PREVENTION, "Failed to prevent screen capture: " + exception) } } promise.resolve(null) } @ExpoMethod fun allowScreenCapture(promise: Promise) { val activity = getCurrentActivity() activity.runOnUiThread { try { activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE) } catch (exception: Exception) { promise.reject(ERROR_CODE_PREVENTION, "Failed to reallow screen capture: " + exception) } } promise.resolve(null) } @Throws(CurrentActivityNotFoundException::class) fun getCurrentActivity(): Activity { val activity = mActivityProvider.currentActivity if (activity != null) { return activity } else { throw CurrentActivityNotFoundException() } } companion object { private val NAME = "ExpoScreenCapture" private const val ERROR_CODE_PREVENTION = "ERR_SCREEN_CAPTURE_PREVENTION" } }
bsd-3-clause
Undin/intellij-rust
src/main/kotlin/org/rust/ide/hints/parameter/RsInlayParameterHintsProvider.kt
2
3086
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints.parameter import com.intellij.codeInsight.hints.HintInfo import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.InlayParameterHintsProvider import com.intellij.codeInsight.hints.Option import com.intellij.psi.PsiElement import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsCallExpr import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsMethodCall import org.rust.lang.core.psi.RsPathExpr import org.rust.lang.core.psi.ext.patText import org.rust.lang.core.psi.ext.qualifiedName import org.rust.lang.core.psi.ext.selfParameter import org.rust.lang.core.psi.ext.valueParameters @Suppress("UnstableApiUsage") class RsInlayParameterHintsProvider : InlayParameterHintsProvider { override fun getSupportedOptions(): List<Option> = listOf(RsInlayParameterHints.smartOption) override fun getDefaultBlackList(): Set<String> = emptySet() override fun getHintInfo(element: PsiElement): HintInfo? { return when (element) { is RsCallExpr -> resolve(element) is RsMethodCall -> resolve(element) else -> null } } override fun getParameterHints(element: PsiElement): List<InlayInfo> = RsInlayParameterHints.provideHints(element) override fun getInlayPresentation(inlayText: String): String = inlayText override fun getBlacklistExplanationHTML(): String { return """ To disable hints for a function use the appropriate pattern:<br /> <b>std::*</b> - functions from the standard library<br /> <b>std::fs::*(*, *)</b> - functions from the <i>std::fs</i> module with two parameters<br /> <b>(*_)</b> - single parameter function where the parameter name ends with <i>_</i><br /> <b>(key, value)</b> - functions with parameters <i>key</i> and <i>value</i><br /> <b>*.put(key, value)</b> - <i>put</i> functions with <i>key</i> and <i>value</i> parameters """.trimIndent() } companion object { private fun resolve(call: RsCallExpr): HintInfo.MethodInfo? { val fn = (call.expr as? RsPathExpr)?.path?.reference?.resolve() as? RsFunction ?: return null val parameters = fn.valueParameters.map { it.patText ?: "_" } return createMethodInfo(fn, parameters) } private fun resolve(methodCall: RsMethodCall): HintInfo.MethodInfo? { val fn = methodCall.reference.resolve() as? RsFunction? ?: return null val parameters = listOfNotNull(fn.selfParameter?.name) + fn.valueParameters.map { it.patText ?: "_" } return createMethodInfo(fn, parameters) } private fun createMethodInfo(function: RsFunction, parameters: List<String>): HintInfo.MethodInfo? { val path = function.qualifiedName ?: return null return HintInfo.MethodInfo(path, parameters, RsLanguage) } } }
mit
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/PastryColorPicker.kt
1
8321
package com.teamwizardry.librarianlib.facade.pastry.layers import com.teamwizardry.librarianlib.albedo.base.buffer.BaseRenderBuffer import com.teamwizardry.librarianlib.albedo.buffer.Primitive import com.teamwizardry.librarianlib.albedo.buffer.VertexBuffer import com.teamwizardry.librarianlib.albedo.shader.Shader import com.teamwizardry.librarianlib.albedo.shader.attribute.VertexLayoutElement import com.teamwizardry.librarianlib.albedo.shader.uniform.FloatUniform import com.teamwizardry.librarianlib.albedo.shader.uniform.Uniform import com.teamwizardry.librarianlib.core.util.* import com.teamwizardry.librarianlib.etcetera.eventbus.Event import com.teamwizardry.librarianlib.facade.layer.GuiDrawContext import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents import com.teamwizardry.librarianlib.facade.layers.RectLayer import com.teamwizardry.librarianlib.facade.layers.SpriteLayer import com.teamwizardry.librarianlib.facade.pastry.PastryBackgroundStyle import com.teamwizardry.librarianlib.math.clamp import com.teamwizardry.librarianlib.mosaic.Mosaic import net.minecraft.util.Identifier import org.lwjgl.glfw.GLFW import java.awt.Color import kotlin.math.max public class PastryColorPicker : GuiLayer(0, 0, 80, 50) { private val gradient = GradientLayer() private val hueLayer = HueLayer() private val colorWell = ColorWellLayer() private var _hue: Float = 0f public var hue: Float get() = _hue set(value) { _hue = value _color = Color(Color.HSBtoRGB(hue, saturation, brightness)) BUS.fire(ColorChangeEvent(color)) } private var _saturation: Float = 0f public var saturation: Float get() = _saturation set(value) { _saturation = value _color = Color(Color.HSBtoRGB(hue, saturation, brightness)) BUS.fire(ColorChangeEvent(color)) } private var _brightness: Float = 0f public var brightness: Float get() = _brightness set(value) { _brightness = value _color = Color(Color.HSBtoRGB(hue, saturation, brightness)) BUS.fire(ColorChangeEvent(color)) } private var _color: Color = Color.white public var color: Color get() = _color set(value) { _color = value val hsb = Color.RGBtoHSB(color.red, color.green, color.blue, null) _hue = hsb[0] _saturation = hsb[1] _brightness = hsb[2] } public class ColorChangeEvent(public val color: Color) : Event() init { this.add(gradient, hueLayer, colorWell) } override fun layoutChildren() { colorWell.size = vec(16, 16) colorWell.pos = vec(this.width - colorWell.width, 0) hueLayer.size = vec(10, this.height) hueLayer.pos = vec(colorWell.x - hueLayer.width - 2, 0) gradient.pos = vec(0, 0) gradient.size = vec(max(4.0, hueLayer.x - 2), this.height) } private inner class GradientLayer : GuiLayer(0, 0, 0, 0) { val background = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0) val square = ColorSquare() var dragging = false init { add(background, square) square.BUS.hook<GuiLayerEvents.MouseDown> { if (square.mouseOver && it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { dragging = true updateSB() } } square.BUS.hook<GuiLayerEvents.MouseUp> { if(it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { dragging = false } } square.BUS.hook<GuiLayerEvents.MouseMove> { if (dragging) { updateSB() } } } private fun updateSB() { if (square.width == 0.0 || square.height == 0.0) return val fraction = square.mousePos / square.size saturation = fraction.x.clamp(0.0, 1.0).toFloat() brightness = (1 - fraction.y).clamp(0.0, 1.0).toFloat() } override fun layoutChildren() { background.frame = bounds square.frame = bounds square.pos += vec(1, 1) square.size -= vec(2, 2) } inner class ColorSquare : GuiLayer(0, 0, 0, 0) { override fun draw(context: GuiDrawContext) { super.draw(context) val minX = 0.0 val minY = 0.0 val maxX = size.xi.toDouble() val maxY = size.yi.toDouble() val buffer = ColorPickerRenderBuffer.SHARED buffer.hue.set(hue) // u/v is saturation/brightness buffer.pos(context.transform, minX, minY, 0).sv(0, 1).endVertex() buffer.pos(context.transform, minX, maxY, 0).sv(0, 0).endVertex() buffer.pos(context.transform, maxX, maxY, 0).sv(1, 0).endVertex() buffer.pos(context.transform, maxX, minY, 0).sv(1, 1).endVertex() buffer.draw(Primitive.QUADS) } } } private inner class HueLayer : GuiLayer(0, 0, 0, 0) { private val background = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0) private val sprite = SpriteLayer(hueSprite) private var dragging = false init { Client.minecraft.textureManager.bindTexture(hueLoc) Client.minecraft.textureManager.getTexture(hueLoc)?.setFilter(false, false) add(background, sprite) sprite.BUS.hook<GuiLayerEvents.MouseDown> { if(sprite.mouseOver && it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { dragging = true updateH() } } sprite.BUS.hook<GuiLayerEvents.MouseUp> { if(it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { dragging = false } } sprite.BUS.hook<GuiLayerEvents.MouseMove> { if(dragging) { updateH() } } } fun updateH() { if (sprite.height == 0.0) return val fraction = sprite.mousePos.y / sprite.height hue = (1 - fraction).clamp(0.0, 1.0).toFloat() } override fun layoutChildren() { background.frame = bounds sprite.frame = bounds sprite.pos += vec(1, 1) sprite.size -= vec(2, 2) } } private inner class ColorWellLayer : GuiLayer(0, 0, 0, 0) { private val background = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0) val colorRect = RectLayer(Color.white, 0, 0, 0, 0) init { add(background, colorRect) colorRect.color_im.set { color } } override fun layoutChildren() { background.frame = this.bounds colorRect.frame = this.bounds.shrink(1.0) } } private companion object { val hueLoc = Identifier("liblib-facade:textures/pastry/colorpicker_hue.png") val hueSprite = Mosaic(hueLoc, 8, 256).getSprite("") } private class ColorPickerRenderBuffer(vbo: VertexBuffer) : BaseRenderBuffer<ColorPickerRenderBuffer>(vbo) { val hue: FloatUniform = +Uniform.float.create("Hue") private val texCoordAttribute = +VertexLayoutElement("TexCoord", VertexLayoutElement.FloatFormat.FLOAT, 2, false) init { bind(colorPickerShader) } fun sv(saturation: Int, value: Int): ColorPickerRenderBuffer { start(texCoordAttribute) putFloat(saturation.toFloat()) putFloat(value.toFloat()) return this } companion object { val colorPickerShader = Shader.build("pastry_color_picker") .vertex(Identifier("liblib-facade:pastry_color_picker.vert")) .fragment(Identifier("liblib-facade:pastry_color_picker.frag")) .build() val SHARED = ColorPickerRenderBuffer(VertexBuffer.SHARED) } } }
lgpl-3.0
tenebras/Spero
src/main/kotlin/com/tenebras/spero/DbConnectionManager.kt
1
401
package com.tenebras.spero import java.sql.Connection import java.sql.DriverManager open class DbConnectionManager(val connectionString: String) { var connection: Connection? = null fun connection(): Connection { if (connection == null || connection!!.isClosed) { connection = DriverManager.getConnection(connectionString) } return connection!! } }
mit
mvarnagiris/expensius
app-core/src/test/kotlin/com/mvcoding/expensius/feature/login/LoginWithAccountPresenterTest.kt
1
1678
/* * Copyright (C) 2016 Mantas Varnagiris. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.mvcoding.expensius.feature.login class LoginWithAccountPresenterTest { // val loginFailuresSubject = PublishSubject<Unit>() // val appUserSubject = BehaviorSubject(anAppUser().withAuthProvider(ANONYMOUS)) // // val appUserService: AppUserService = mock() // val view: LoginWithAccountPresenter.View = mock() // val presenter = LoginWithAccountPresenter(appUserService, rxSchedulers()) // // @Before // fun setUp() { // whenever(appUserService.appUser()).thenReturn(appUserSubject) // whenever(view.loginFailures()).thenReturn(loginFailuresSubject) // } // // @Test // fun closesWhenLoginFails() { // presenter.attach(view) // // loginFailure() // // verify(view).close() // } // // @Test // fun displaysSupportDeveloperWhenLoginSucceeds() { // presenter.attach(view) // // loginWithAccount() // // verify(view).displaySupportDeveloper() // } // // private fun loginWithAccount() = appUserSubject.onNext(anAppUser().withAuthProvider(GOOGLE)) // private fun loginFailure() = loginFailuresSubject.onNext(Unit) }
gpl-3.0
kotlinx/kotlinx.html
src/commonMain/kotlin/generated/gen-tags-c.kt
1
4264
package kotlinx.html import kotlinx.html.* import kotlinx.html.impl.* import kotlinx.html.attributes.* /******************************************************************************* DO NOT EDIT This file was generated by module generate *******************************************************************************/ @Suppress("unused") open class CANVAS(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("canvas", consumer, initialAttributes, null, false, false), HtmlBlockInlineTag { var width : String get() = attributeStringString.get(this, "width") set(newValue) {attributeStringString.set(this, "width", newValue)} var height : String get() = attributeStringString.get(this, "height") set(newValue) {attributeStringString.set(this, "height", newValue)} } val CANVAS.asFlowContent : FlowContent get() = this val CANVAS.asPhrasingContent : PhrasingContent get() = this @Suppress("unused") open class CAPTION(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("caption", consumer, initialAttributes, null, false, false), HtmlBlockTag { } @Suppress("unused") open class CITE(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("cite", consumer, initialAttributes, null, true, false), HtmlBlockInlineTag { } val CITE.asFlowContent : FlowContent get() = this val CITE.asPhrasingContent : PhrasingContent get() = this @Suppress("unused") open class CODE(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("code", consumer, initialAttributes, null, true, false), HtmlBlockInlineTag { } val CODE.asFlowContent : FlowContent get() = this val CODE.asPhrasingContent : PhrasingContent get() = this @Suppress("unused") open class COL(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("col", consumer, initialAttributes, null, false, true), CommonAttributeGroupFacade { var span : String get() = attributeStringString.get(this, "span") set(newValue) {attributeStringString.set(this, "span", newValue)} } @Suppress("unused") open class COLGROUP(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("colgroup", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacade { var span : String get() = attributeStringString.get(this, "span") set(newValue) {attributeStringString.set(this, "span", newValue)} } /** * Table column */ @HtmlTagMarker inline fun COLGROUP.col(classes : String? = null, crossinline block : COL.() -> Unit = {}) : Unit = COL(attributesMapOf("class", classes), consumer).visit(block) @Suppress("unused") open class COMMAND(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("command", consumer, initialAttributes, null, true, true), CommonAttributeGroupFacadeFlowMetaDataPhrasingContent { var type : CommandType get() = attributeCommandTypeEnumCommandTypeValues.get(this, "type") set(newValue) {attributeCommandTypeEnumCommandTypeValues.set(this, "type", newValue)} var label : String get() = attributeStringString.get(this, "label") set(newValue) {attributeStringString.set(this, "label", newValue)} var icon : String get() = attributeStringString.get(this, "icon") set(newValue) {attributeStringString.set(this, "icon", newValue)} var disabled : Boolean get() = attributeBooleanTicker.get(this, "disabled") set(newValue) {attributeBooleanTicker.set(this, "disabled", newValue)} var checked : Boolean get() = attributeBooleanTicker.get(this, "checked") set(newValue) {attributeBooleanTicker.set(this, "checked", newValue)} var radioGroup : String get() = attributeStringString.get(this, "radiogroup") set(newValue) {attributeStringString.set(this, "radiogroup", newValue)} } val COMMAND.asFlowContent : FlowContent get() = this val COMMAND.asMetaDataContent : MetaDataContent get() = this val COMMAND.asPhrasingContent : PhrasingContent get() = this
apache-2.0
androidx/androidx
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/ExternalRequestProcessor.kt
3
8825
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package androidx.camera.camera2.pipe.compat import android.hardware.camera2.CaptureRequest import android.view.Surface import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.CameraController import androidx.camera.camera2.pipe.CameraGraph import androidx.camera.camera2.pipe.CameraId import androidx.camera.camera2.pipe.CaptureSequence import androidx.camera.camera2.pipe.CaptureSequenceProcessor import androidx.camera.camera2.pipe.Metadata import androidx.camera.camera2.pipe.Request import androidx.camera.camera2.pipe.RequestMetadata import androidx.camera.camera2.pipe.RequestNumber import androidx.camera.camera2.pipe.RequestProcessor import androidx.camera.camera2.pipe.RequestTemplate import androidx.camera.camera2.pipe.StreamId import androidx.camera.camera2.pipe.core.Log import androidx.camera.camera2.pipe.graph.GraphListener import androidx.camera.camera2.pipe.graph.GraphRequestProcessor import kotlin.reflect.KClass import kotlinx.atomicfu.atomic @RequiresApi(21) class ExternalCameraController( private val graphConfig: CameraGraph.Config, private val graphListener: GraphListener, private val requestProcessor: RequestProcessor ) : CameraController { private val sequenceProcessor = ExternalCaptureSequenceProcessor(graphConfig, requestProcessor) private val graphProcessor: GraphRequestProcessor = GraphRequestProcessor.from( sequenceProcessor ) private var started = atomic(false) override fun start() { if (started.compareAndSet(expect = false, update = true)) { graphListener.onGraphStarted(graphProcessor) } } override fun stop() { if (started.compareAndSet(expect = true, update = false)) { graphListener.onGraphStopped(graphProcessor) } } override fun close() { graphProcessor.close() } override fun updateSurfaceMap(surfaceMap: Map<StreamId, Surface>) { sequenceProcessor.surfaceMap = surfaceMap } } @Suppress("DEPRECATION") @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java internal class ExternalCaptureSequenceProcessor( private val graphConfig: CameraGraph.Config, private val processor: RequestProcessor ) : CaptureSequenceProcessor<Request, ExternalCaptureSequenceProcessor.ExternalCaptureSequence> { private val internalRequestNumbers = atomic(0L) private val internalSequenceNumbers = atomic(0) private val closed = atomic(false) private var _surfaceMap: Map<StreamId, Surface>? = null var surfaceMap: Map<StreamId, Surface>? get() = synchronized(this) { _surfaceMap } set(value) = synchronized(this) { _surfaceMap = value } override fun build( isRepeating: Boolean, requests: List<Request>, defaultParameters: Map<*, Any?>, requiredParameters: Map<*, Any?>, listeners: List<Request.Listener>, sequenceListener: CaptureSequence.CaptureSequenceListener ): ExternalCaptureSequence? { if (closed.value) { return null } val streamToSurfaceMap = surfaceMap if (streamToSurfaceMap == null) { Log.warn { "Cannot create an ExternalCaptureSequence until Surfaces are available!" } return null } val metadata = requests.map { request -> val parameters = defaultParameters + request.parameters + requiredParameters ExternalRequestMetadata( graphConfig.defaultTemplate, streamToSurfaceMap, parameters, isRepeating, request, RequestNumber(internalRequestNumbers.incrementAndGet()) ) } return ExternalCaptureSequence( graphConfig.camera, isRepeating, requests, metadata, defaultParameters, requiredParameters, listeners, sequenceListener ) } override fun submit(captureSequence: ExternalCaptureSequence): Int { check(!closed.value) check(captureSequence.captureRequestList.isNotEmpty()) if (captureSequence.repeating) { check(captureSequence.captureRequestList.size == 1) processor.startRepeating( captureSequence.captureRequestList.single(), captureSequence.defaultParameters, captureSequence.requiredParameters, captureSequence.listeners ) } else { if (captureSequence.captureRequestList.size == 1) { processor.submit( captureSequence.captureRequestList.single(), captureSequence.defaultParameters, captureSequence.requiredParameters, captureSequence.listeners ) } else { processor.submit( captureSequence.captureRequestList, captureSequence.defaultParameters, captureSequence.requiredParameters, captureSequence.listeners ) } } return internalSequenceNumbers.incrementAndGet() } override fun abortCaptures() { processor.abortCaptures() } override fun stopRepeating() { processor.stopRepeating() } override fun close() { if (closed.compareAndSet(expect = false, update = true)) { processor.close() } } internal class ExternalCaptureSequence( override val cameraId: CameraId, override val repeating: Boolean, override val captureRequestList: List<Request>, override val captureMetadataList: List<RequestMetadata>, val defaultParameters: Map<*, Any?>, val requiredParameters: Map<*, Any?>, override val listeners: List<Request.Listener>, override val sequenceListener: CaptureSequence.CaptureSequenceListener, ) : CaptureSequence<Request> { @Volatile private var _sequenceNumber: Int? = null override var sequenceNumber: Int get() { if (_sequenceNumber == null) { // If the sequence id has not been submitted, it means the call to capture or // setRepeating has not yet returned. The callback methods should never be // synchronously invoked, so the only case this should happen is if a second // thread attempted to invoke one of the callbacks before the initial call // completed. By locking against the captureSequence object here and in the // capture call, we can block the callback thread until the sequenceId is // available. synchronized(this) { return checkNotNull(_sequenceNumber) { "SequenceNumber has not been set for $this!" } } } return checkNotNull(_sequenceNumber) { "SequenceNumber has not been set for $this!" } } set(value) { _sequenceNumber = value } } @Suppress("UNCHECKED_CAST") internal class ExternalRequestMetadata( override val template: RequestTemplate, override val streams: Map<StreamId, Surface>, private val parameters: Map<*, Any?>, override val repeating: Boolean, override val request: Request, override val requestNumber: RequestNumber ) : RequestMetadata { override fun <T> get(key: CaptureRequest.Key<T>): T? = parameters[key] as T? override fun <T> get(key: Metadata.Key<T>): T? = parameters[key] as T? override fun <T> getOrDefault(key: CaptureRequest.Key<T>, default: T): T = get(key) ?: default override fun <T> getOrDefault(key: Metadata.Key<T>, default: T): T = get(key) ?: default override fun <T : Any> unwrapAs(type: KClass<T>): T? = null } }
apache-2.0
mickele/DBFlow
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/QueryModelDefinition.kt
1
5836
package com.raizlabs.android.dbflow.processor.definition import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.QueryModel import com.raizlabs.android.dbflow.processor.ClassNames import com.raizlabs.android.dbflow.processor.ProcessorUtils import com.raizlabs.android.dbflow.processor.definition.column.ColumnDefinition import com.raizlabs.android.dbflow.processor.definition.CustomTypeConverterPropertyMethod import com.raizlabs.android.dbflow.processor.definition.LoadFromCursorMethod import com.raizlabs.android.dbflow.processor.definition.MethodDefinition import com.raizlabs.android.dbflow.processor.ProcessorManager import com.raizlabs.android.dbflow.processor.utils.ElementUtility import com.raizlabs.android.dbflow.processor.ColumnValidator import com.squareup.javapoet.* import java.util.* import javax.lang.model.element.Element import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.type.MirroredTypeException /** * Description: */ class QueryModelDefinition(typeElement: Element, processorManager: ProcessorManager) : BaseTableDefinition(typeElement, processorManager) { var databaseTypeName: TypeName? = null var allFields: Boolean = false var implementsLoadFromCursorListener = false internal var methods: Array<MethodDefinition> init { val queryModel = typeElement.getAnnotation(QueryModel::class.java) if (queryModel != null) { try { queryModel.database } catch (mte: MirroredTypeException) { databaseTypeName = TypeName.get(mte.typeMirror) } } elementClassName?.let { databaseTypeName?.let { it1 -> processorManager.addModelToDatabase(it, it1) } } if (element is TypeElement) { implementsLoadFromCursorListener = ProcessorUtils.implementsClass(manager.processingEnvironment, ClassNames.LOAD_FROM_CURSOR_LISTENER.toString(), element as TypeElement) } methods = arrayOf<MethodDefinition>(LoadFromCursorMethod(this)) } override fun prepareForWrite() { classElementLookUpMap.clear() columnDefinitions.clear() packagePrivateList.clear() val queryModel = typeElement?.getAnnotation(QueryModel::class.java) if (queryModel != null) { databaseDefinition = manager.getDatabaseHolderDefinition(databaseTypeName)?.databaseDefinition setOutputClassName(databaseDefinition?.classSeparator + DBFLOW_QUERY_MODEL_TAG) allFields = queryModel.allFields typeElement?.let { createColumnDefinitions(it) } } } override val extendsClass: TypeName? get() = ParameterizedTypeName.get(ClassNames.QUERY_MODEL_ADAPTER, elementClassName) override fun onWriteDefinition(typeBuilder: TypeSpec.Builder) { elementClassName?.let { className -> columnDefinitions.forEach { it.addPropertyDefinition(typeBuilder, className) } } val customTypeConverterPropertyMethod = CustomTypeConverterPropertyMethod(this) customTypeConverterPropertyMethod.addToType(typeBuilder) val constructorCode = CodeBlock.builder() constructorCode.addStatement("super(databaseDefinition)") customTypeConverterPropertyMethod.addCode(constructorCode) InternalAdapterHelper.writeGetModelClass(typeBuilder, elementClassName) typeBuilder.addMethod(MethodSpec.constructorBuilder().addParameter(ClassNames.DATABASE_HOLDER, "holder").addParameter(ClassNames.BASE_DATABASE_DEFINITION_CLASSNAME, "databaseDefinition").addCode(constructorCode.build()).addModifiers(Modifier.PUBLIC).build()) for (method in methods) { val methodSpec = method.methodSpec if (methodSpec != null) { typeBuilder.addMethod(methodSpec) } } typeBuilder.addMethod(MethodSpec.methodBuilder("newInstance") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(elementClassName) .addStatement("return new \$T()", elementClassName).build()) } override fun createColumnDefinitions(typeElement: TypeElement) { val variableElements = ElementUtility.getAllElements(typeElement, manager) for (element in variableElements) { classElementLookUpMap.put(element.simpleName.toString(), element) } val columnValidator = ColumnValidator() for (variableElement in variableElements) { // no private static or final fields val isAllFields = ElementUtility.isValidAllFields(allFields, element) // package private, will generate helper val isPackagePrivate = ElementUtility.isPackagePrivate(element) val isPackagePrivateNotInSamePackage = isPackagePrivate && !ElementUtility.isInSamePackage(manager, element, this.element) if (variableElement.getAnnotation(Column::class.java) != null || isAllFields) { val columnDefinition = ColumnDefinition(manager, variableElement, this, isPackagePrivateNotInSamePackage) if (columnValidator.validate(manager, columnDefinition)) { columnDefinitions.add(columnDefinition) if (isPackagePrivate) { packagePrivateList.add(columnDefinition) } } } } } override // Shouldn't include any val primaryColumnDefinitions: List<ColumnDefinition> get() = ArrayList() override val propertyClassName: ClassName get() = outputClassName companion object { private val DBFLOW_QUERY_MODEL_TAG = "QueryTable" } }
mit
androidx/androidx
compose/material3/material3/integration-tests/material3-catalog/src/main/java/androidx/compose/material3/catalog/library/ui/component/Component.kt
3
5906
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.catalog.library.ui.component import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.consumedWindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.catalog.library.R import androidx.compose.material3.catalog.library.model.Component import androidx.compose.material3.catalog.library.model.Example import androidx.compose.material3.catalog.library.model.Theme import androidx.compose.material3.catalog.library.ui.common.CatalogScaffold import androidx.compose.material3.catalog.library.ui.example.ExampleItem import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @OptIn(ExperimentalLayoutApi::class) @Composable fun Component( component: Component, theme: Theme, onThemeChange: (theme: Theme) -> Unit, onExampleClick: (example: Example) -> Unit, onBackClick: () -> Unit ) { val ltr = LocalLayoutDirection.current CatalogScaffold( topBarTitle = component.name, showBackNavigationIcon = true, theme = theme, guidelinesUrl = component.guidelinesUrl, docsUrl = component.docsUrl, sourceUrl = component.sourceUrl, onThemeChange = onThemeChange, onBackClick = onBackClick ) { paddingValues -> LazyColumn( modifier = Modifier.consumedWindowInsets(paddingValues), contentPadding = PaddingValues( start = paddingValues.calculateStartPadding(ltr) + ComponentPadding, top = paddingValues.calculateTopPadding() + ComponentPadding, end = paddingValues.calculateEndPadding(ltr) + ComponentPadding, bottom = paddingValues.calculateBottomPadding() + ComponentPadding ) ) { item { Box( modifier = Modifier .fillMaxWidth() .padding(vertical = ComponentIconVerticalPadding) ) { Image( painter = painterResource(id = component.icon), contentDescription = null, modifier = Modifier .size(ComponentIconSize) .align(Alignment.Center), colorFilter = if (component.tintIcon) { ColorFilter.tint(LocalContentColor.current) } else { null } ) } } item { Text( text = stringResource(id = R.string.description), style = MaterialTheme.typography.bodyLarge ) Spacer(modifier = Modifier.height(ComponentPadding)) Text( text = component.description, style = MaterialTheme.typography.bodyMedium ) Spacer(modifier = Modifier.height(ComponentDescriptionPadding)) } item { Text( text = stringResource(id = R.string.examples), style = MaterialTheme.typography.bodyLarge ) Spacer(modifier = Modifier.height(ComponentPadding)) } if (component.examples.isNotEmpty()) { items(component.examples) { example -> ExampleItem( example = example, onClick = onExampleClick ) Spacer(modifier = Modifier.height(ExampleItemPadding)) } } else { item { Text( text = stringResource(id = R.string.no_examples), style = MaterialTheme.typography.bodyMedium ) Spacer(modifier = Modifier.height(ComponentPadding)) } } } } } private val ComponentIconSize = 108.dp private val ComponentIconVerticalPadding = 42.dp private val ComponentPadding = 16.dp private val ComponentDescriptionPadding = 32.dp private val ExampleItemPadding = 8.dp
apache-2.0
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_shader_objects.kt
1
27586
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_shader_objects = "ARBShaderObjects".nativeClassGL("ARB_shader_objects", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. This extension adds API calls that are necessary to manage shader objects and program objects as defined in the OpenGL 2.0 white papers by 3Dlabs. The generation of an executable that runs on one of OpenGL's programmable units is modeled to that of developing a typical C/C++ application. There are one or more source files, each of which are stored by OpenGL in a shader object. Each shader object (source file) needs to be compiled and attached to a program object. Once all shader objects are compiled successfully, the program object needs to be linked to produce an executable. This executable is part of the program object, and can now be loaded onto the programmable units to make it part of the current OpenGL state. Both the compile and link stages generate a text string that can be queried to get more information. This information could be, but is not limited to, compile errors, link errors, optimization hints, etc. Values for uniform variables, declared in a shader, can be set by the application and used to control a shader's behavior. This extension defines functions for creating shader objects and program objects, for compiling shader objects, for linking program objects, for attaching shader objects to program objects, and for using a program object as part of current state. Functions to load uniform values are also defined. Some house keeping functions, like deleting an object and querying object state, are also provided. Although this extension defines the API for creating shader objects, it does not define any specific types of shader objects. It is assumed that this extension will be implemented along with at least one such additional extension for creating a specific type of OpenGL 2.0 shader (e.g., the ${ARB_fragment_shader.link} extension or the ${ARB_vertex_shader.link} extension). ${GL20.promoted} """ IntConstant( "Accepted by the {@code pname} argument of GetHandleARB.", "PROGRAM_OBJECT_ARB"..0x8B40 ) val Parameters = IntConstant( "Accepted by the {@code pname} parameter of GetObjectParameter{fi}vARB.", "OBJECT_TYPE_ARB"..0x8B4E, "OBJECT_SUBTYPE_ARB"..0x8B4F, "OBJECT_DELETE_STATUS_ARB"..0x8B80, "OBJECT_COMPILE_STATUS_ARB"..0x8B81, "OBJECT_LINK_STATUS_ARB"..0x8B82, "OBJECT_VALIDATE_STATUS_ARB"..0x8B83, "OBJECT_INFO_LOG_LENGTH_ARB"..0x8B84, "OBJECT_ATTACHED_OBJECTS_ARB"..0x8B85, "OBJECT_ACTIVE_UNIFORMS_ARB"..0x8B86, "OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB"..0x8B87, "OBJECT_SHADER_SOURCE_LENGTH_ARB"..0x8B88 ).javaDocLinks IntConstant( "Returned by the {@code params} parameter of GetObjectParameter{fi}vARB.", "SHADER_OBJECT_ARB"..0x8B48 ) IntConstant( "Returned by the {@code type} parameter of GetActiveUniformARB.", "FLOAT_VEC2_ARB"..0x8B50, "FLOAT_VEC3_ARB"..0x8B51, "FLOAT_VEC4_ARB"..0x8B52, "INT_VEC2_ARB"..0x8B53, "INT_VEC3_ARB"..0x8B54, "INT_VEC4_ARB"..0x8B55, "BOOL_ARB"..0x8B56, "BOOL_VEC2_ARB"..0x8B57, "BOOL_VEC3_ARB"..0x8B58, "BOOL_VEC4_ARB"..0x8B59, "FLOAT_MAT2_ARB"..0x8B5A, "FLOAT_MAT3_ARB"..0x8B5B, "FLOAT_MAT4_ARB"..0x8B5C, "SAMPLER_1D_ARB"..0x8B5D, "SAMPLER_2D_ARB"..0x8B5E, "SAMPLER_3D_ARB"..0x8B5F, "SAMPLER_CUBE_ARB"..0x8B60, "SAMPLER_1D_SHADOW_ARB"..0x8B61, "SAMPLER_2D_SHADOW_ARB"..0x8B62, "SAMPLER_2D_RECT_ARB"..0x8B63, "SAMPLER_2D_RECT_SHADOW_ARB"..0x8B64 ) void( "DeleteObjectARB", """ Either deletes the object, or flags it for deletion. An object that is attached to a container object is not deleted until it is no longer attached to any container object, for any context. If it is still attached to at least one container object, the object is flagged for deletion. If the object is part of the current rendering state, it is not deleted until it is no longer part of the current rendering state for any context. If the object is still part of the rendering state of at least one context, it is flagged for deletion. If an object is flagged for deletion, its Boolean status bit #OBJECT_DELETE_STATUS_ARB is set to true. DeleteObjectARB will silently ignore the value zero. When a container object is deleted, it will detach each attached object as part of the deletion process. When an object is deleted, all information for the object referenced is lost. The data for the object is also deleted. """, GLhandleARB.IN("obj", "the shader object to delete") ) GLhandleARB( "GetHandleARB", "Returns the handle to an object that is in use as part of current state.", GLenum.IN("pname", "the state item for which the current object is to be returned", "#PROGRAM_OBJECT_ARB") ) void( "DetachObjectARB", "Detaches an object from the container object it is attached to.", GLhandleARB.IN("containerObj", "the container object"), GLhandleARB.IN("attachedObj", "the object to detach") ) GLhandleARB( "CreateShaderObjectARB", "Creates a shader object.", GLenum.IN("shaderType", "the type of the shader object to be created", "ARBVertexShader#VERTEX_SHADER_ARB ARBFragmentShader#FRAGMENT_SHADER_ARB") ) void( "ShaderSourceARB", """ Sets the source code for the specified shader object {@code shaderObj} to the text strings in the {@code string} array. If the object previously had source code loaded into it, it is completely replaced. The strings that are loaded into a shader object are expected to form the source code for a valid shader as defined in the OpenGL Shading Language Specification. """, GLhandleARB.IN("shaderObj", "the shader object"), AutoSize("string", "length")..GLsizei.IN("count", "the number of strings in the array"), PointerArray(GLcharARB_p, "string", "length")..const..GLcharARB_pp.IN("string", "an array of pointers to one or more, optionally null terminated, character strings that make up the source code"), nullable..const..GLint_p.IN( "length", """ an array with the number of charARBs in each string (the string length). Each element in this array can be set to negative one (or smaller), indicating that its accompanying string is null terminated. If {@code length} is set to $NULL, all strings in the {@code string} argument are considered null terminated. """ ) ) void( "CompileShaderARB", """ Compiles a shader object. Each shader object has a Boolean status, #OBJECT_COMPILE_STATUS_ARB, that is modified as a result of compilation. This status can be queried with #GetObjectParameteriARB(). This status will be set to GL11#TRUE if the shader {@code shaderObj} was compiled without errors and is ready for use, and GL11#FALSE otherwise. Compilation can fail for a variety of reasons as listed in the OpenGL Shading Language Specification. If CompileShaderARB failed, any information about a previous compile is lost and is not restored. Thus a failed compile does not restore the old state of {@code shaderObj}. If {@code shaderObj} does not reference a shader object, the error GL11#INVALID_OPERATION is generated. Note that changing the source code of a shader object, through ShaderSourceARB, does not change its compile status #OBJECT_COMPILE_STATUS_ARB. Each shader object has an information log that is modified as a result of compilation. This information log can be queried with #GetInfoLogARB() to obtain more information about the compilation attempt. """, GLhandleARB.IN("shaderObj", "the shader object to compile") ) GLhandleARB( "CreateProgramObjectARB", """ Creates a program object. A program object is a container object. Shader objects are attached to a program object with the command AttachObjectARB. It is permissible to attach shader objects to program objects before source code has been loaded into the shader object, or before the shader object has been compiled. It is permissible to attach multiple shader objects of the same type to a single program object, and it is permissible to attach a shader object to more than one program object. """ ) void( "AttachObjectARB", "Attaches an object to a container object.", GLhandleARB.IN("containerObj", "the container object"), GLhandleARB.IN("obj", "the object to attach") ) void( "LinkProgramARB", """ Links a program object. Each program object has a Boolean status, #OBJECT_LINK_STATUS_ARB, that is modified as a result of linking. This status can be queried with #GetObjectParameteriARB(). This status will be set to GL11#TRUE if a valid executable is created, and GL11#FALSE otherwise. Linking can fail for a variety of reasons as specified in the OpenGL Shading Language Specification. Linking will also fail if one or more of the shader objects, attached to {@code programObj}, are not compiled successfully, or if more active uniform or active sampler variables are used in {@code programObj} than allowed. If LinkProgramARB failed, any information about a previous link is lost and is not restored. Thus a failed link does not restore the old state of {@code programObj}. If {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. Each program object has an information log that is modified as a result of a link operation. This information log can be queried with #GetInfoLogARB() to obtain more information about the link operation. """, GLhandleARB.IN("programObj", "the program object to link") ) void( "UseProgramObjectARB", """ Installs the executable code as part of current rendering state if the program object {@code programObj} contains valid executable code, i.e. has been linked successfully. If UseProgramObjectARB is called with the handle set to 0, it is as if the GL had no programmable stages and the fixed functionality paths will be used instead. If {@code programObj} cannot be made part of the current rendering state, an GL11#INVALID_OPERATION error will be generated and the current rendering state left unmodified. This error will be set, for example, if {@code programObj} has not been linked successfully. If {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. While a program object is in use, applications are free to modify attached shader objects, compile attached shader objects, attach additional shader objects, and detach shader objects. This does not affect the link status #OBJECT_LINK_STATUS_ARB of the program object. This does not affect the executable code that is part of the current state either. That executable code is only affected when the program object has been re-linked successfully. After such a successful re-link, the #LinkProgramARB() command will install the generated executable code as part of the current rendering state if the specified program object was already in use as a result of a previous call to UseProgramObjectARB. If this re-link failed, then the executable code part of the current state does not change. """, GLhandleARB.IN("programObj", "the program object to use") ) void( "ValidateProgramARB", """ Validates the program object {@code programObj} against the GL state at that moment. Each program object has a Boolean status, #OBJECT_VALIDATE_STATUS_ARB, that is modified as a result of validation. This status can be queried with #GetObjectParameteriARB(). If validation succeeded this status will be set to GL11#TRUE, otherwise it will be set to GL11#FALSE. If validation succeeded the program object is guaranteed to execute, given the current GL state. If validation failed, the program object is guaranteed to not execute, given the current GL state. If {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. ValidateProgramARB will validate at least as much as is done when a rendering command is issued, and it could validate more. For example, it could give a hint on how to optimize some piece of shader code. ValidateProgramARB will store its information in the info log. This information will either be an empty string or it will contain validation information. ValidateProgramARB is typically only useful during application development. An application should not expect different OpenGL implementations to produce identical information. """, GLhandleARB.IN("programObj", "the program object to validate") ) val uniformLocation = GLint.IN("location", "the uniform variable location") val uniformX = "the uniform x value" val uniformY = "the uniform y value" val uniformZ = "the uniform z value" val uniformW = "the uniform w value" void( "Uniform1fARB", "float version of #Uniform4fARB().", uniformLocation, GLfloat.IN("v0", uniformX) ) void( "Uniform2fARB", "vec2 version of #Uniform4fARB().", uniformLocation, GLfloat.IN("v0", uniformX), GLfloat.IN("v1", uniformY) ) void( "Uniform3fARB", "vec3 version of #Uniform4fARB().", uniformLocation, GLfloat.IN("v0", uniformX), GLfloat.IN("v1", uniformY), GLfloat.IN("v2", uniformZ) ) void( "Uniform4fARB", "Loads a vec4 value into a uniform variable of the program object that is currently in use.", GLint.IN("location", "the uniform variable location"), GLfloat.IN("v0", uniformX), GLfloat.IN("v1", uniformY), GLfloat.IN("v2", uniformZ), GLfloat.IN("v3", uniformW) ) void( "Uniform1iARB", "int version of #Uniform1fARB().", uniformLocation, GLint.IN("v0", uniformX) ) void( "Uniform2iARB", "ivec2 version of #Uniform2fARB().", uniformLocation, GLint.IN("v0", uniformX), GLint.IN("v1", uniformY) ) void( "Uniform3iARB", "ivec3 version of #Uniform3fARB().", uniformLocation, GLint.IN("v0", uniformX), GLint.IN("v1", uniformY), GLint.IN("v2", uniformZ) ) void( "Uniform4iARB", "ivec4 version of #Uniform4fARB().", uniformLocation, GLint.IN("v0", uniformX), GLint.IN("v1", uniformY), GLint.IN("v2", uniformZ), GLint.IN("v3", uniformW) ) void( "Uniform1fvARB", "Loads floating-point values {@code count} times into a uniform location defined as an array of float values.", uniformLocation, AutoSize("value")..GLsizei.IN("count", "the number of float values to load"), const..GLfloat_p.IN("value", "the values to load") ) void( "Uniform2fvARB", "Loads floating-point values {@code count} times into a uniform location defined as an array of vec2 vectors.", uniformLocation, AutoSize(2, "value")..GLsizei.IN("count", "the number of vec2 vectors to load"), const..GLfloat_p.IN("value", "the values to load") ) void( "Uniform3fvARB", "Loads floating-point values {@code count} times into a uniform location defined as an array of vec3 vectors.", uniformLocation, AutoSize(3, "value")..GLsizei.IN("count", "the number of vec3 vectors to load"), const..GLfloat_p.IN("value", "the values to load") ) void( "Uniform4fvARB", "Loads floating-point values {@code count} times into a uniform location defined as an array of vec4 vectors.", uniformLocation, AutoSize(4, "value")..GLsizei.IN("count", "the number of vec4 vectors to load"), const..GLfloat_p.IN("value", "the values to load") ) void( "Uniform1ivARB", "Loads integer values {@code count} times into a uniform location defined as an array of integer values.", uniformLocation, AutoSize("value")..GLsizei.IN("count", "the number of integer values to load"), const..GLint_p.IN("value", "the values to load") ) void( "Uniform2ivARB", "Loads integer values {@code count} times into a uniform location defined as an array of ivec2 vectors.", uniformLocation, AutoSize(2, "value")..GLsizei.IN("count", "the number of ivec2 vectors to load"), const..GLint_p.IN("value", "the values to load") ) void( "Uniform3ivARB", "Loads integer values {@code count} times into a uniform location defined as an array of ivec3 vectors.", uniformLocation, AutoSize(3, "value")..GLsizei.IN("count", "the number of ivec3 vectors to load"), const..GLint_p.IN("value", "the values to load") ) void( "Uniform4ivARB", "Loads integer values {@code count} times into a uniform location defined as an array of ivec4 vectors.", uniformLocation, AutoSize(4, "value")..GLsizei.IN("count", "the number of ivec4 vectors to load"), const..GLint_p.IN("value", "the values to load") ) val transpose = GLboolean.IN("transpose", "if GL11#FALSE, the matrix is specified in column major order, otherwise in row major order") void( "UniformMatrix2fvARB", "Loads a 2x2 matrix of floating-point values {@code count} times into a uniform location defined as a matrix or an array of matrices.", uniformLocation, AutoSize(2 x 2, "value")..GLsizei.IN("count", "the number of 2x2 matrices to load"), transpose, const..GLfloat_p.IN("value", "the matrix values to load") ) void( "UniformMatrix3fvARB", "Loads a 3x3 matrix of floating-point values {@code count} times into a uniform location defined as a matrix or an array of matrices.", uniformLocation, AutoSize(3 x 3, "value")..GLsizei.IN("count", "the number of 3x3 matrices to load"), transpose, const..GLfloat_p.IN("value", "the matrix values to load") ) void( "UniformMatrix4fvARB", "Loads a 4x4 matrix of floating-point values {@code count} times into a uniform location defined as a matrix or an array of matrices.", uniformLocation, AutoSize(4 x 4, "value")..GLsizei.IN("count", "the number of 4x4 matrices to load"), transpose, const..GLfloat_p.IN("value", "the matrix values to load") ) void( "GetObjectParameterfvARB", "Returns object specific parameter values.", GLhandleARB.IN("obj", "the object to query"), GLenum.IN("pname", "the parameter to query"), Check(1)..GLfloat_p.OUT("params", "a buffer in which to return the parameter value") ) void( "GetObjectParameterivARB", "Returns object specific parameter values.", GLhandleARB.IN("obj", "the object to query"), GLenum.IN("pname", "the parameter to query", Parameters), Check(1)..ReturnParam..GLint_p.OUT("params", "a buffer in which to return the parameter value") ) void( "GetInfoLogARB", """ A string that contains information about the last link or validation attempt and last compilation attempt are kept per program or shader object. This string is called the info log and can be obtained with this command. This string will be null terminated. The number of characters in the info log is given by #OBJECT_INFO_LOG_LENGTH_ARB, which can be queried with #GetObjectParameteriARB(). If {@code obj} is a shader object, the returned info log will either be an empty string or it will contain information about the last compilation attempt for that object. If {@code obj} is a program object, the returned info log will either be an empty string or it will contain information about the last link attempt or last validation attempt for that object. If {@code obj} is not of type #PROGRAM_OBJECT_ARB or #SHADER_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. If an error occurred, the return parameters {@code length} and {@code infoLog} will be unmodified. The info log is typically only useful during application development and an application should not expect different OpenGL implementations to produce identical info logs. """, GLhandleARB.IN("obj", "the shader object to query"), AutoSize("infoLog")..GLsizei.IN("maxLength", "the maximum number of characters the GL is allowed to write into {@code infoLog}"), Check(1)..nullable..GLsizei_p.OUT( "length", """ the actual number of characters written by the GL into {@code infoLog} is returned in {@code length}, excluding the null termination. If {@code length} is $NULL then the GL ignores this parameter. """ ), Return( "length", "glGetObjectParameteriARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB)", heapAllocate = true )..GLcharARB_p.OUT("infoLog", "a buffer in which to return the info log") ) void( "GetAttachedObjectsARB", """ Returns the handles of objects attached to {@code containerObj} in {@code obj}. . The number of objects attached to {@code containerObj} is given by #OBJECT_ATTACHED_OBJECTS_ARB, which can be queried with #GetObjectParameteriARB(). If {@code containerObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. If an error occurred, the return parameters {@code count} and {@code obj} will be unmodified. """, GLhandleARB.IN("containerObj", "the container object to query"), AutoSize("obj")..GLsizei.IN("maxCount", "the maximum number of handles the GL is allowed to write into {@code obj}"), Check(1)..nullable..GLsizei_p.OUT( "count", "a buffer in which to return the actual number of object handles written by the GL into {@code obj}. If $NULL then the GL ignores this parameter." ), GLhandleARB_p.OUT("obj", "a buffer in which to return the attached object handles") ) GLint( "GetUniformLocationARB", """ Returns the location of uniform variable {@code name}. {@code name} has to be a null terminated string, without white space. The value of -1 will be returned if {@code name} does not correspond to an active uniform variable name in {@code programObj} or if {@code name} starts with the reserved prefix "gl_". If {@code programObj} has not been successfully linked, or if {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. The location of a uniform variable does not change until the next link command is issued. A valid {@code name} cannot be a structure, an array of structures, or a subcomponent of a vector or a matrix. In order to identify a valid {@code name}, the "." (dot) and "[]" operators can be used in {@code name} to operate on a structure or to operate on an array. The first element of a uniform array is identified using the name of the uniform array appended with "[0]". Except if the last part of the string {@code name} indicates a uniform array, then the location of the first element of that array can be retrieved by either using the name of the uniform array, or the name of the uniform array appended with "[0]". """, GLhandleARB.IN("programObj", "the program object to query"), const..GLcharARB_p.IN("name", "the name of the uniform variable whose location is to be queried") ) void( "GetActiveUniformARB", """ Determines which of the declared uniform variables are active and their sizes and types. This command provides information about the uniform selected by {@code index}. The {@code index} of 0 selects the first active uniform, and {@code index} of #OBJECT_ACTIVE_UNIFORMS_ARB - 1 selects the last active uniform. The value of #OBJECT_ACTIVE_UNIFORMS_ARB can be queried with #GetObjectParameteriARB(). If {@code index} is greater than or equal to #OBJECT_ACTIVE_UNIFORMS_ARB, the error GL11#INVALID_VALUE is generated. If an error occurred, the return parameters {@code length}, {@code size}, {@code type} and {@code name} will be unmodified. The returned uniform name can be the name of built-in uniform state as well. The length of the longest uniform name in {@code programObj} is given by #OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, which can be queried with #GetObjectParameteriARB(). Each uniform variable, declared in a shader, is broken down into one or more strings using the "." (dot) and "[]" operators, if necessary, to the point that it is legal to pass each string back into #GetUniformLocationARB(). Each of these strings constitutes one active uniform, and each string is assigned an index. If one or more elements of an array are active, GetActiveUniformARB will return the name of the array in {@code name}, subject to the restrictions listed above. The type of the array is returned in {@code type}. The {@code size} parameter contains the highest array element index used, plus one. The compiler or linker determines the highest index used. There will be only one active uniform reported by the GL per uniform array. This command will return as much information about active uniforms as possible. If no information is available, {@code length} will be set to zero and {@code name} will be an empty string. This situation could arise if GetActiveUniformARB is issued after a failed link. """, GLhandleARB.IN( "programObj", """ a handle to a program object for which the command #LinkProgramARB() has been issued in the past. It is not necessary for {@code programObj} to have been linked successfully. The link could have failed because the number of active uniforms exceeded the limit. """ ), GLuint.IN("index", "the uniform index"), AutoSize("name")..GLsizei.IN("maxLength", "the maximum number of characters the GL is allowed to write into {@code name}."), Check(1)..nullable..GLsizei_p.IN( "length", """ a buffer in which to return the actual number of characters written by the GL into {@code name}. This count excludes the null termination. If {@code length} is $NULL then the GL ignores this parameter. """ ), Check(1)..GLint_p.OUT("size", "a buffer in which to return the uniform size. The size is in units of the type returned in {@code type}."), Check(1)..GLenum_p.OUT("type", "a buffer in which to return the uniform type"), Return( "length", "glGetObjectParameteriARB(programObj, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB)" )..GLcharARB_p.OUT("name", "a buffer in which to return the uniform name") ) void( "GetUniformfvARB", "Returns the floating-point value or values of a uniform.", GLhandleARB.IN("programObj", "the program object to query"), uniformLocation, Check(1)..ReturnParam..GLfloat_p.OUT("params", "a buffer in which to return the uniform values") ) void( "GetUniformivARB", "Returns the integer value or values of a uniform.", GLhandleARB.IN("programObj", "the program object to query"), uniformLocation, Check(1)..ReturnParam..GLint_p.OUT("params", "a buffer in which to return the uniform values") ) void( "GetShaderSourceARB", """ Returns the string making up the source code for a shader object. The string {@code source} is a concatenation of the strings passed to OpenGL using #ShaderSourceARB(). The length of this concatenation is given by #OBJECT_SHADER_SOURCE_LENGTH_ARB, which can be queried with #GetObjectParameteriARB(). If {@code obj} is not of type #SHADER_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. If an error occurred, the return parameters {@code length} and {@code source} will be unmodified. """, GLhandleARB.IN("obj", "the shader object to query"), AutoSize("source")..GLsizei.IN("maxLength", "the maximum number of characters the GL is allowed to write into {@code source}"), Check(1)..nullable..GLsizei_p.OUT( "length", """ a buffer in which to return the actual number of characters written by the GL into {@code source}, excluding the null termination. If {@code length} is $NULL then the GL ignores this parameter. """ ), Return( "length", "glGetObjectParameteriARB(obj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB)", heapAllocate = true )..GLcharARB_p.OUT("source", "a buffer in which to return the shader object source") ) }
bsd-3-clause
dropbox/Store
store-rx3/src/main/kotlin/com/dropbox/store/rx3/RxSourceOfTruth.kt
1
2573
package com.dropbox.store.rx3 import com.dropbox.android.external.store4.SourceOfTruth import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Maybe import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.rx3.await /** * Creates a [Maybe] source of truth that is accessible via [reader], [writer], [delete] and * [deleteAll]. * * @param reader function for reading records from the source of truth * @param writer function for writing updates to the backing source of truth * @param delete function for deleting records in the source of truth for the given key * @param deleteAll function for deleting all records in the source of truth * */ fun <Key : Any, Input : Any, Output : Any> SourceOfTruth.Companion.ofMaybe( reader: (Key) -> Maybe<Output>, writer: (Key, Input) -> Completable, delete: ((Key) -> Completable)? = null, deleteAll: (() -> Completable)? = null ): SourceOfTruth<Key, Input, Output> { val deleteFun: (suspend (Key) -> Unit)? = if (delete != null) { key -> delete(key).await() } else null val deleteAllFun: (suspend () -> Unit)? = deleteAll?.let { { deleteAll().await() } } return of( nonFlowReader = { key -> reader.invoke(key).await() }, writer = { key, output -> writer.invoke(key, output).await() }, delete = deleteFun, deleteAll = deleteAllFun ) } /** * Creates a ([Flowable]) source of truth that is accessed via [reader], [writer], [delete] and * [deleteAll]. * * @param reader function for reading records from the source of truth * @param writer function for writing updates to the backing source of truth * @param delete function for deleting records in the source of truth for the given key * @param deleteAll function for deleting all records in the source of truth * */ fun <Key : Any, Input : Any, Output : Any> SourceOfTruth.Companion.ofFlowable( reader: (Key) -> Flowable<Output>, writer: (Key, Input) -> Completable, delete: ((Key) -> Completable)? = null, deleteAll: (() -> Completable)? = null ): SourceOfTruth<Key, Input, Output> { val deleteFun: (suspend (Key) -> Unit)? = if (delete != null) { key -> delete(key).await() } else null val deleteAllFun: (suspend () -> Unit)? = deleteAll?.let { { deleteAll().await() } } return of( reader = { key -> reader.invoke(key).asFlow() }, writer = { key, output -> writer.invoke(key, output).await() }, delete = deleteFun, deleteAll = deleteAllFun ) }
apache-2.0
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/QCOM_binning_control.kt
1
947
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles.templates import org.lwjgl.generator.* import org.lwjgl.opengles.* val QCOM_binning_control = "QCOMBinningControl".nativeClassGLES("QCOM_binning_control", postfix = QCOM) { documentation = """ Native bindings to the $registryLink extension. This extension adds some new hints to give more control to application developers over the driver's binning algorithm. Only change this state right before changing rendertargets or right after a swap or there will be a large performance penalty. """ IntConstant( "Accepted by the {@code target} parameter of Hint.", "BINNING_CONTROL_HINT_QCOM"..0x8FB0 ) IntConstant( "Accepted by the {@code hint} parameter of Hint.", "CPU_OPTIMIZED_QCOM"..0x8FB1, "GPU_OPTIMIZED_QCOM"..0x8FB2, "RENDER_DIRECT_TO_FRAMEBUFFER_QCOM"..0x8FB3, "DONT_CARE"..0x1100 ) }
bsd-3-clause
google/android-auto-companion-android
trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/testutils/FakeLifecycleOwner.kt
1
1008
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.google.android.libraries.car.trustagent.testutils import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry /** Androidx provides TestLifecycleOwner but it's not available in google3. */ class FakeLifecycleOwner : LifecycleOwner { val registry = LifecycleRegistry(this) override fun getLifecycle(): Lifecycle { return registry } }
apache-2.0
esofthead/mycollab
mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/ComponentRelayEmailNotificationActionImpl.kt
3
8499
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.schedule.email.service import com.hp.gagawa.java.elements.A import com.hp.gagawa.java.elements.Span import com.mycollab.common.MonitorTypeConstants import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.common.i18n.OptionI18nEnum import com.mycollab.core.MyCollabException import com.mycollab.core.utils.StringUtils import com.mycollab.html.FormatUtils import com.mycollab.html.LinkUtils import com.mycollab.module.mail.MailUtils import com.mycollab.module.project.ProjectLinkGenerator import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.domain.ProjectRelayEmailNotification import com.mycollab.module.project.i18n.ComponentI18nEnum import com.mycollab.module.project.domain.Component.Field import com.mycollab.module.project.domain.SimpleComponent import com.mycollab.module.project.service.ComponentService import com.mycollab.module.user.AccountLinkGenerator import com.mycollab.module.user.service.UserService import com.mycollab.schedule.email.ItemFieldMapper import com.mycollab.schedule.email.MailContext import com.mycollab.schedule.email.format.FieldFormat import com.mycollab.schedule.email.format.I18nFieldFormat import com.mycollab.schedule.email.project.ComponentRelayEmailNotificationAction import com.mycollab.spring.AppContextUtil import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanDefinition import org.springframework.context.annotation.Scope import org.springframework.stereotype.Service /** * @author MyCollab Ltd * @since 6.0.0 */ @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) class ComponentRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleComponent>(), ComponentRelayEmailNotificationAction { @Autowired private lateinit var componentService: ComponentService private val mapper = ComponentFieldNameMapper() override fun buildExtraTemplateVariables(context: MailContext<SimpleComponent>) { val emailNotification = context.emailNotification val summary = bean!!.name val summaryLink = ProjectLinkGenerator.generateComponentPreviewFullLink(siteUrl, bean!!.projectid, bean!!.id) val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else "" val userAvatar = LinkUtils.newAvatar(avatarId) val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}" val actionEnum = when (emailNotification.action) { MonitorTypeConstants.CREATE_ACTION -> ComponentI18nEnum.MAIL_CREATE_ITEM_HEADING MonitorTypeConstants.UPDATE_ACTION -> ComponentI18nEnum.MAIL_UPDATE_ITEM_HEADING MonitorTypeConstants.ADD_COMMENT_ACTION -> ComponentI18nEnum.MAIL_COMMENT_ITEM_HEADING else -> throw MyCollabException("Not support action ${emailNotification.action}") } contentGenerator.putVariable("projectName", bean!!.projectName) contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid)) contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser)) contentGenerator.putVariable("name", summary) contentGenerator.putVariable("summaryLink", summaryLink) } override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleComponent? = componentService.findById(notification.typeid.toInt(), notification.saccountid) override fun getItemName(): String = StringUtils.trim(bean!!.description, 100) override fun getProjectName(): String = bean!!.projectName override fun getCreateSubject(context: MailContext<SimpleComponent>): String = context.getMessage( ComponentI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getCreateSubjectNotification(context: MailContext<SimpleComponent>): String = context.getMessage( ComponentI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), componentLink()) override fun getUpdateSubject(context: MailContext<SimpleComponent>): String = context.getMessage( ComponentI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getUpdateSubjectNotification(context: MailContext<SimpleComponent>): String = context.getMessage( ComponentI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), componentLink()) override fun getCommentSubject(context: MailContext<SimpleComponent>): String = context.getMessage( ComponentI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getCommentSubjectNotification(context: MailContext<SimpleComponent>): String = context.getMessage( ComponentI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), componentLink()) private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).appendText(bean!!.projectName).write() private fun userLink(context: MailContext<SimpleComponent>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).appendText(context.changeByUserFullName).write() private fun componentLink() = A(ProjectLinkGenerator.generateComponentPreviewLink(bean!!.projectid, bean!!.id)).appendText(getItemName()).write() override fun getItemFieldMapper(): ItemFieldMapper = mapper override fun getType(): String = ProjectTypeConstants.COMPONENT override fun getTypeId(): String = "${bean!!.id}" class ComponentFieldNameMapper : ItemFieldMapper() { init { put(Field.description, GenericI18Enum.FORM_DESCRIPTION, true) put(Field.status, I18nFieldFormat(Field.status.name, GenericI18Enum.FORM_STATUS, OptionI18nEnum.StatusI18nEnum::class.java)) put(Field.userlead, LeadFieldFormat(Field.userlead.name, ComponentI18nEnum.FORM_LEAD)) } } class LeadFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) { override fun formatField(context: MailContext<*>): String { val component = context.wrappedBean as SimpleComponent return if (component.userlead != null) { val userAvatarLink = MailUtils.getAvatarLink(component.userLeadAvatarId, 16) val img = FormatUtils.newImg("avatar", userAvatarLink) val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(component.saccountid), component.userlead) val link = FormatUtils.newA(userLink, component.userLeadFullName!!) FormatUtils.newLink(img, link).write() } else Span().write() } override fun formatField(context: MailContext<*>, value: String): String { if (StringUtils.isBlank(value)) { return Span().write() } val userService = AppContextUtil.getSpringBean(UserService::class.java) val user = userService.findUserByUserNameInAccount(value, context.saccountid) return if (user != null) { val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16) val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid), user.username) val img = FormatUtils.newImg("avatar", userAvatarLink) val link = FormatUtils.newA(userLink, user.displayName!!) FormatUtils.newLink(img, link).write() } else value } } }
agpl-3.0
stfalcon-studio/uaroads_android
app/src/main/java/com/stfalcon/new_uaroads_android/features/findroute/FindRouteSubComponent.kt
1
1029
/* * Copyright (c) 2017 stfalcon.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stfalcon.new_uaroads_android.features.findroute import dagger.Subcomponent import dagger.android.AndroidInjector /* * Created by Anton Bevza on 4/5/17. */ @Subcomponent(modules = arrayOf(FindRouteModule::class)) interface FindRouteSubComponent : AndroidInjector<FindRouteFragment> { @Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<FindRouteFragment>() }
apache-2.0
inorichi/tachiyomi-extensions
src/en/merakiscans/src/eu/kanade/tachiyomi/extension/en/merakiscans/MerakiScans.kt
1
5436
package eu.kanade.tachiyomi.extension.en.merakiscans import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.OkHttpClient import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import java.text.ParseException import java.text.SimpleDateFormat import java.util.Locale class MerakiScans : ParsedHttpSource() { override val name = "MerakiScans" override val baseUrl = "https://merakiscans.com" override val lang = "en" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient companion object { val dateFormat by lazy { SimpleDateFormat("MMM dd, yyyy", Locale.US) } } override fun popularMangaSelector() = "#all > #listitem > a" override fun latestUpdatesSelector() = "#mangalisthome > #mangalistitem > #mangaitem > #manganame > a" override fun popularMangaRequest(page: Int) = GET("$baseUrl/manga", headers) override fun latestUpdatesRequest(page: Int) = GET(baseUrl, headers) override fun popularMangaFromElement(element: Element) = SManga.create().apply { setUrlWithoutDomain(element.attr("href")) title = element.select("h1.title").text().trim() } override fun latestUpdatesFromElement(element: Element) = SManga.create().apply { setUrlWithoutDomain(element.attr("href")) title = element.text().trim() } override fun popularMangaNextPageSelector(): String? = null override fun latestUpdatesNextPageSelector(): String? = null override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = GET("$baseUrl/manga", headers) override fun searchMangaSelector() = popularMangaSelector() // This makes it so that if somebody searches for "views" it lists everything, also includes #'s. private fun searchMangaSelector(query: String) = "#all > #listitem > a:contains($query)" override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element) override fun searchMangaNextPageSelector(): String? = null private fun searchMangaParse(response: Response, query: String): MangasPage { val document = response.asJsoup() val mangas = document.select(searchMangaSelector(query)).map { element -> searchMangaFromElement(element) } return MangasPage(mangas, false) } override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response, query) } } override fun mangaDetailsParse(document: Document) = SManga.create().apply { val infoElement = document.select("#content2") author = infoElement.select("#detail_list > li:nth-child(5)").text().replace("Author:", "").trim() artist = infoElement.select("#detail_list > li:nth-child(7)").text().replace("Artist:", "").trim() genre = infoElement.select("#detail_list > li:nth-child(11) > a").joinToString { it.text().trim() } status = infoElement.select("#detail_list > li:nth-child(9)").text().replace("Status:", "").trim().let { parseStatus(it) } description = infoElement.select("#detail_list > span").text().trim() thumbnail_url = infoElement.select("#info > #image > #cover_img").attr("abs:src") } private fun parseStatus(status: String) = when { status.contains("Ongoing") -> SManga.ONGOING status.contains("Completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "#chapter_table > tbody > #chapter-head" override fun chapterFromElement(element: Element) = SChapter.create().apply { setUrlWithoutDomain(element.attr("data-href")) name = element.select("td:nth-child(1)").text().trim() date_upload = element.select("td:nth-child(2)").text().trim().let { parseChapterDate(it) } } private fun parseChapterDate(date: String): Long { return try { dateFormat.parse(date.replace(Regex("(st|nd|rd|th)"), ""))?.time ?: 0L } catch (e: ParseException) { 0L } } override fun pageListParse(document: Document): List<Page> { val doc = document.toString() val imgarray = doc.substringAfter("var images = [").substringBefore("];").split(",").map { it.replace("\"", "") } val mangaslug = doc.substringAfter("var manga_slug = \"").substringBefore("\";") val chapnum = doc.substringAfter("var viewschapter = \"").substringBefore("\";") return imgarray.mapIndexed { i, image -> Page(i, "", "$baseUrl/manga/$mangaslug/$chapnum/$image") } } override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used") override fun getFilterList() = FilterList() }
apache-2.0
ligee/kotlin-jupyter
jupyter-lib/api-annotations/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/annotations/JupyterSymbolProcessor.kt
1
2989
package org.jetbrains.kotlinx.jupyter.api.annotations import com.google.devtools.ksp.getAllSuperTypes import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import java.io.File import java.util.Spliterators import java.util.concurrent.locks.ReentrantLock import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.concurrent.withLock class JupyterSymbolProcessor( private val logger: KSPLogger, private val generatedFilesPath: File ) : SymbolProcessor { private val fqnMap = mapOf( "org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinitionProducer" to "producers", "org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition" to "definitions" ) private val annotationFqn = JupyterLibrary::class.qualifiedName!! private val annotationSimpleName = JupyterLibrary::class.simpleName!! private val fileLock = ReentrantLock() override fun process(resolver: Resolver): List<KSAnnotated> { generatedFilesPath.deleteRecursively() generatedFilesPath.mkdirs() resolver .getAllFiles() .flatMap { it.declarations } .filterIsInstance<KSClassDeclaration>() .asParallelStream() .forEach(::processClass) return emptyList() } private fun processClass(clazz: KSClassDeclaration) { if (!hasLibraryAnnotation(clazz)) return val classFqn = clazz.qualifiedName?.asString() ?: throw Exception("Class $clazz was marked with $annotationSimpleName, but it has no qualified name (anonymous?).") logger.info("Class $classFqn has $annotationSimpleName annotation") val supertypes = clazz.getAllSuperTypes().mapNotNull { it.declaration.qualifiedName }.map { it.asString() } val significantSupertypes = supertypes.filter { it in fqnMap }.toList() if (significantSupertypes.isEmpty()) { logger.warn( "Class $classFqn has $annotationSimpleName annotation, " + "but doesn't implement one of Jupyter integration interfaces" ) return } fileLock.withLock { for (fqn in significantSupertypes) { val fileName = fqnMap[fqn]!! val file = generatedFilesPath.resolve(fileName) file.appendText(classFqn + "\n") } } } private fun hasLibraryAnnotation(clazz: KSClassDeclaration): Boolean { return clazz.annotations.any { it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationFqn } } private fun <T> Sequence<T>.asParallelStream(): Stream<T> { return StreamSupport.stream({ Spliterators.spliteratorUnknownSize(iterator(), 0) }, 0, true) } }
apache-2.0
luanalbineli/popularmovies
app/src/main/java/com/themovielist/moviedetail/review/MovieReviewListDialogPresenter.kt
1
2083
package com.themovielist.moviedetail.review import com.themovielist.model.MovieReviewModel import com.themovielist.model.response.PaginatedArrayResponseModel import com.themovielist.repository.movie.MovieRepository import io.reactivex.disposables.Disposable import timber.log.Timber import javax.inject.Inject class MovieReviewListDialogPresenter @Inject internal constructor(private val mMovieRepository: MovieRepository) : MovieReviewListDialogContract.Presenter { private lateinit var mView: MovieReviewListDialogContract.View private var mPageIndex: Int = 0 private var mSubscription: Disposable? = null private var mMovieId: Int = 0 override fun setView(view: MovieReviewListDialogContract.View) { mView = view } override fun start(movieReviewList: List<MovieReviewModel>, movieId: Int, hasMore: Boolean) { mView.addReviewsToList(movieReviewList) if (hasMore) { mView.enableLoadMoreListener() } mMovieId = movieId } override fun onListEndReached() { if (mSubscription != null) { return } mView.showLoadingIndicator() mPageIndex++ val observable = mMovieRepository.getReviewsByMovieId(mPageIndex, mMovieId) mSubscription = observable.subscribe({ response -> this.handleSuccessLoadMovieReview(response) }, { error -> this.handleErrorLoadMovieReview(error) }) } private fun handleSuccessLoadMovieReview(response: PaginatedArrayResponseModel<MovieReviewModel>) { mView.addReviewsToList(response.results) if (!response.hasMorePages()) { mView.disableLoadMoreListener() } mSubscription = null } private fun handleErrorLoadMovieReview(throwable: Throwable) { Timber.e(throwable, "An error occurred while tried to get the movie reviews for page: " + mPageIndex) mPageIndex-- mView.showErrorLoadingReviews() mSubscription = null } override fun tryLoadReviewsAgain() { onListEndReached() } }
apache-2.0
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/run/execution/ui/QueryResultTable.kt
1
3828
/* * Copyright (C) 2019-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.processor.run.execution.ui import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.ui.table.TableView import uk.co.reecedunn.intellij.plugin.core.ui.layout.columnInfo import uk.co.reecedunn.intellij.plugin.core.ui.layout.columns import uk.co.reecedunn.intellij.plugin.processor.query.QueryResult import uk.co.reecedunn.intellij.plugin.processor.resources.PluginApiBundle import javax.swing.JScrollPane data class QueryResultReference(private val textOffset: Int, internal var element: PsiElement? = null) { val offset: Int get() = element?.textOffset ?: textOffset } private val RESULT_INDEX_COLUMN = columnInfo<Pair<QueryResult, QueryResultReference>, Long>( heading = PluginApiBundle.message("query.result.table.index.column.label"), getter = { (first) -> first.position }, sortable = false ) private val RESULT_ITEM_TYPE_COLUMN = columnInfo<Pair<QueryResult, QueryResultReference>, String>( heading = PluginApiBundle.message("query.result.table.item-type.column.label"), getter = { (first) -> first.type }, sortable = false ) private val RESULT_MIME_TYPE_COLUMN = columnInfo<Pair<QueryResult, QueryResultReference>, String>( heading = PluginApiBundle.message("query.result.table.mime-type.column.label"), getter = { (first) -> first.mimetype }, sortable = false ) class QueryResultTable : TableView<Pair<QueryResult, QueryResultReference>>(), QueryTable { init { columns { add(RESULT_INDEX_COLUMN) add(RESULT_ITEM_TYPE_COLUMN) add(RESULT_MIME_TYPE_COLUMN) } setEnableAntialiasing(true) updateEmptyText(running = false, exception = false) } private fun updateEmptyText(running: Boolean, exception: Boolean) { when { exception -> emptyText.text = PluginApiBundle.message("query.result.table.has-exception") running -> emptyText.text = runningText else -> emptyText.text = PluginApiBundle.message("query.result.table.no-results") } } override var runningText: String = PluginApiBundle.message("query.result.table.results-pending") set(value) { field = value updateEmptyText(isRunning, hasException) } override var isRunning: Boolean = false set(value) { field = value updateEmptyText(isRunning, hasException) } override var hasException: Boolean = false set(value) { field = value updateEmptyText(isRunning, hasException) } override val itemCount: Int get() = rowCount fun addRow(entry: QueryResult, offset: Int) { listTableModel.addRow(Pair(entry, QueryResultReference(offset))) } fun updateQueryReferences(psiFile: PsiFile) { (0 until itemCount).forEach { val item = listTableModel.getItem(it) item.second.element = psiFile.findElementAt(item.second.offset) } } } fun JScrollPane.queryResultTable(init: QueryResultTable.() -> Unit): QueryResultTable { val view = QueryResultTable() view.init() setViewportView(view) return view }
apache-2.0
kamontat/CheckIDNumberA
app/src/main/java/com/kamontat/checkidnumber/model/strategy/idnumber/ThailandIDNumberStrategy.kt
1
1232
package com.kamontat.checkidnumber.model.strategy.idnumber import com.kamontat.checkidnumber.api.constants.Status /** * @author kamontat * * * @version 1.0 * * * @since Thu 11/May/2017 - 11:47 PM */ class ThailandIDNumberStrategy : IDNumberStrategy { override val idLength: Int get() = 13 override fun checking(id: String?): Status { if (id == null || id == "") return Status.NOT_CREATE val splitID = id.toCharArray() when { splitID[0] == '9' -> return Status.NOT_NINE splitID.size != idLength -> return Status.UNMATCHED_LENGTH else -> { var total: Int = 0 (1..12).forEach { i -> val digit = Character.getNumericValue(splitID[i - 1]) total += (14 - i) * digit } total %= 11 val lastDigit = Character.getNumericValue(splitID[splitID.size - 1]) when { total <= 1 -> if (lastDigit == 1 - total) return Status.OK else -> if (total > 1) if (lastDigit == 11 - total) return Status.OK } return Status.UNCORRECTED } } } }
mit
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_search/analytic/CourseContentSearchScreenOpenedAnalyticEvent.kt
2
589
package org.stepik.android.domain.course_search.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent class CourseContentSearchScreenOpenedAnalyticEvent( courseId: Long, courseTitle: String ) : AnalyticEvent { companion object { private const val PARAM_COURSE = "course" private const val PARAM_TITLE = "title" } override val name: String = "Course content search screen opened" override val params: Map<String, Any> = mapOf( PARAM_COURSE to courseId, PARAM_TITLE to courseTitle ) }
apache-2.0
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubService.kt
1
1029
package eu.kanade.tachiyomi.data.updater.github import eu.kanade.tachiyomi.network.NetworkHelper import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Used to connect with the Github API. */ interface GithubService { companion object { fun create(): GithubService { val restAdapter = Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(Injekt.get<NetworkHelper>().client) .build() return restAdapter.create(GithubService::class.java) } } @GET("/repos/NerdNumber9/tachiyomi/releases/latest") fun getLatestVersion(): Observable<GithubRelease> }
apache-2.0
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/bean/info/Organization.kt
1
4508
package com.gkzxhn.mygithub.bean.info import android.os.Parcel import android.os.Parcelable import android.text.TextUtils /** * Created by 方 on 2017/10/27. */ data class Organization( val login: String, //github val id: Int, //1 val url: String, //https://api.github.com/orgs/github val repos_url: String, //https://api.github.com/orgs/github/repos val events_url: String, //https://api.github.com/orgs/github/events val hooks_url: String, //https://api.github.com/orgs/github/hooks val issues_url: String, //https://api.github.com/orgs/github/issues val members_url: String, //https://api.github.com/orgs/github/members{/member} val public_members_url: String, //https://api.github.com/orgs/github/public_members{/member} val avatar_url: String, //https://github.com/images/error/octocat_happy.gif val description: String, //A great organization val name: String, //github val company: String, //GitHub val blog: String, //https://github.com/blog val location: String, //San Francisco val email: String, //[email protected] val public_repos: Int, //2 val public_gists: Int, //1 val followers: Int, //20 val following: Int, //0 val html_url: String, //https://github.com/octocat val created_at: String, //2008-01-14T04:33:35Z val type: String, //Organization val total_private_repos: Int, //100 val owned_private_repos: Int, //100 val private_gists: Int, //81 val disk_usage: Int, //10000 val collaborators: Int, //8 val billing_email: String, //[email protected] val plan: Plan?, val default_repository_settings: String, //read val members_can_create_repositories: Boolean //true ) : Parcelable { constructor(source: Parcel) : this( source.readString(), source.readInt(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readInt(), source.readInt(), source.readInt(), source.readInt(), source.readString(), source.readString(), source.readString(), source.readInt(), source.readInt(), source.readInt(), source.readInt(), source.readInt(), source.readString(), source.readParcelable<Plan?>(Plan::class.java.classLoader), source.readString(), 1 == source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(login) writeInt(id) writeString(if (TextUtils.isEmpty(url)) "" else url) writeString(if (TextUtils.isEmpty(repos_url)) "" else repos_url) writeString(if (TextUtils.isEmpty(events_url)) "" else events_url) writeString(if (TextUtils.isEmpty(hooks_url)) "" else hooks_url) writeString(if (TextUtils.isEmpty(issues_url)) "" else issues_url) writeString(if (TextUtils.isEmpty(members_url)) "" else members_url) writeString(if (TextUtils.isEmpty(public_members_url)) "" else public_members_url) writeString(avatar_url) writeString(if (TextUtils.isEmpty(description)) "" else description) writeString(if (TextUtils.isEmpty(name)) "" else name) writeString(if (TextUtils.isEmpty(company)) "" else company) writeString(if (TextUtils.isEmpty(blog)) "" else blog) writeString(if (TextUtils.isEmpty(location)) "" else location) writeString(if (TextUtils.isEmpty(email)) "" else email) writeInt(public_repos) writeInt(public_gists) writeInt(followers) writeInt(following) writeString(if (TextUtils.isEmpty(html_url)) "" else html_url) writeString(if (TextUtils.isEmpty(created_at)) "" else created_at) writeString(if (TextUtils.isEmpty(type)) "" else type) writeInt(total_private_repos) writeInt(owned_private_repos) writeInt(private_gists) writeInt(disk_usage) writeInt(collaborators) writeString(if (TextUtils.isEmpty(billing_email)) "" else billing_email) writeParcelable(plan, 0) writeString(if (TextUtils.isEmpty(default_repository_settings)) "" else default_repository_settings) writeInt((if (members_can_create_repositories) 1 else 0)) } companion object { @JvmField val CREATOR: Parcelable.Creator<Organization> = object : Parcelable.Creator<Organization> { override fun createFromParcel(source: Parcel): Organization = Organization(source) override fun newArray(size: Int): Array<Organization?> = arrayOfNulls(size) } } }
gpl-3.0
paslavsky/music-sync-manager
msm-server/src/main/kotlin/net/paslavsky/msm/domain/DomainObject.kt
1
808
package net.paslavsky.msm.domain import javax.persistence.MappedSuperclass import javax.persistence.EmbeddedId import javax.persistence.Version /** * Abstract class that represent Domain objects of the MSM * * @author Andrey Paslavsky * @version 1.0 */ MappedSuperclass public abstract class DomainObject { public EmbeddedId var id: ID = ID() public Version var version: Int = -1 override fun toString(): String = "${javaClass.getSimpleName()}#$id" override fun hashCode(): Int = 37 + 17 * (id xor (id shl 32)).toInt() override fun equals(other: Any?): Boolean = when { other == null -> false this identityEquals other -> true other is DomainObject && javaClass == other.javaClass -> id == other.id && version == other.version else -> false } }
apache-2.0
exponentjs/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopHttpErrorEvent.kt
2
784
package abi42_0_0.host.exp.exponent.modules.api.components.webview.events import abi42_0_0.com.facebook.react.bridge.WritableMap import abi42_0_0.com.facebook.react.uimanager.events.Event import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when a http error is received from the server. */ class TopHttpErrorEvent(viewId: Int, private val mEventData: WritableMap) : Event<TopHttpErrorEvent>(viewId) { companion object { const val EVENT_NAME = "topHttpError" } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, eventName, mEventData) }
bsd-3-clause
google/where-am-i
app/src/main/java/com/google/wear/whereami/kt/builders.kt
1
3058
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.google.wear.whereami.kt import androidx.wear.tiles.* fun text(fn: LayoutElementBuilders.Text.Builder.() -> Unit): LayoutElementBuilders.Text { val builder = LayoutElementBuilders.Text.Builder() fn(builder) return builder.build() } fun modifiers(fn: ModifiersBuilders.Modifiers.Builder.() -> Unit): ModifiersBuilders.Modifiers { val builder = ModifiersBuilders.Modifiers.Builder() fn(builder) return builder.build() } fun activityClickable( packageName: String, activity: String ) = ModifiersBuilders.Clickable.Builder() .setOnClick( ActionBuilders.LaunchAction.Builder() .setAndroidActivity( ActionBuilders.AndroidActivity.Builder() .setPackageName(packageName) .setClassName(activity) .build() ) .build() ).build() fun fontStyle(fn: LayoutElementBuilders.FontStyle.Builder.() -> Unit): LayoutElementBuilders.FontStyle { val builder = LayoutElementBuilders.FontStyle.Builder() fn(builder) return builder.build() } fun TimelineBuilders.TimelineEntry.Builder.layout(fn: () -> LayoutElementBuilders.LayoutElement) { setLayout(LayoutElementBuilders.Layout.Builder().setRoot(fn()).build()) } fun tile(fn: TileBuilders.Tile.Builder.() -> Unit): TileBuilders.Tile { val builder = TileBuilders.Tile.Builder() fn(builder) return builder.build() } fun TileBuilders.Tile.Builder.timeline(fn: TimelineBuilders.Timeline.Builder.() -> Unit) { val builder = TimelineBuilders.Timeline.Builder() builder.fn() setTimeline(builder.build()) } fun column(fn: LayoutElementBuilders.Column.Builder.() -> Unit): LayoutElementBuilders.Column { val builder = LayoutElementBuilders.Column.Builder() builder.fn() return builder.build() } fun TimelineBuilders.Timeline.Builder.timelineEntry(fn: TimelineBuilders.TimelineEntry.Builder.() -> Unit) { val builder = TimelineBuilders.TimelineEntry.Builder() fn(builder) addTimelineEntry(builder.build()) } fun Float.toSpProp() = DimensionBuilders.SpProp.Builder().setValue(this).build() fun Float.toDpProp() = DimensionBuilders.DpProp.Builder().setValue(this).build() fun Int.toColorProp(): ColorBuilders.ColorProp = ColorBuilders.ColorProp.Builder().setArgb(this).build() fun String.toContentDescription() = ModifiersBuilders.Semantics.Builder().setContentDescription( this ).build()
apache-2.0
Heiner1/AndroidAPS
combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt
1
3450
package info.nightscout.androidaps.plugins.pump.combo import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.combo.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.RuffyScripter import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` class ComboPluginTest : TestBase() { @Mock lateinit var rh: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync @Mock lateinit var sp: SP @Mock lateinit var context: Context @Mock lateinit var dateUtil: DateUtil @Mock lateinit var ruffyScripter: RuffyScripter val injector = HasAndroidInjector { AndroidInjector { if (it is PumpEnactResult) { it.rh = rh } } } private lateinit var comboPlugin: ComboPlugin @Before fun prepareMocks() { `when`(rh.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") `when`(rh.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") comboPlugin = ComboPlugin(injector, aapsLogger, RxBus(aapsSchedulers, aapsLogger), rh, profileFunction, sp, commandQueue, context, pumpSync, dateUtil, ruffyScripter) } @Test fun invalidBasalRateOnComboPumpShouldLimitLoopInvocation() { comboPlugin.setPluginEnabled(PluginType.PUMP, true) comboPlugin.setValidBasalRateProfileSelectedOnPump(false) var c = Constraint(true) c = comboPlugin.isLoopInvocationAllowed(c) Assert.assertEquals("Combo: No valid basal rate read from pump", c.getReasons(aapsLogger)) Assert.assertEquals(false, c.value()) comboPlugin.setPluginEnabled(PluginType.PUMP, false) } @Test fun `generate bolus ID from timestamp and amount`() { val now = System.currentTimeMillis() val pumpTimestamp = now - now % 1000 // same timestamp, different bolus leads to different fake timestamp Assert.assertNotEquals( comboPlugin.generatePumpBolusId(Bolus(pumpTimestamp, 0.1, true)), comboPlugin.generatePumpBolusId(Bolus(pumpTimestamp, 0.3, true)) ) // different timestamp, same bolus leads to different fake timestamp Assert.assertNotEquals( comboPlugin.generatePumpBolusId(Bolus(pumpTimestamp, 0.3, true)), comboPlugin.generatePumpBolusId(Bolus(pumpTimestamp + 60 * 1000, 0.3, true)) ) // generated timestamp has second-precision val bolus = Bolus(pumpTimestamp, 0.2, true) val calculatedTimestamp = comboPlugin.generatePumpBolusId(bolus) Assert.assertEquals(calculatedTimestamp, calculatedTimestamp - calculatedTimestamp % 1000) } }
agpl-3.0
sjnyag/stamp
app/src/main/java/com/sjn/stamp/media/playback/CastPlayback.kt
1
7799
/* * Copyright (C) 2014 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.sjn.stamp.media.playback import android.content.Context import android.net.Uri import android.support.v4.media.session.MediaSessionCompat.QueueItem import android.support.v4.media.session.PlaybackStateCompat import android.text.TextUtils import com.google.android.gms.cast.MediaStatus import com.google.android.gms.cast.framework.CastContext import com.google.android.gms.cast.framework.media.RemoteMediaClient import com.sjn.stamp.utils.LogHelper import com.sjn.stamp.utils.MediaIDHelper import com.sjn.stamp.utils.MediaItemHelper import org.json.JSONException import org.json.JSONObject /** * An implementation of Playback that talks to Cast. */ open class CastPlayback(internal val context: Context, private val callback: Playback.Callback, initialStreamPosition: Int, override var currentMediaId: String?) : Playback { internal val remoteMediaClient: RemoteMediaClient = CastContext.getSharedInstance(this.context).sessionManager.currentCastSession.remoteMediaClient private val remoteMediaClientListener: RemoteMediaClient.Listener = CastMediaClientListener() private var currentPosition: Int = initialStreamPosition override var state: Int = 0 override val isConnected: Boolean get() = CastContext.getSharedInstance(context).sessionManager.currentCastSession?.isConnected ?: false override val isPlaying: Boolean get() = isConnected && remoteMediaClient.isPlaying override val currentStreamPosition: Int get() = if (!isConnected) currentPosition else remoteMediaClient.approximateStreamPosition.toInt() override fun start() = remoteMediaClient.addListener(remoteMediaClientListener) override fun stop(notifyListeners: Boolean) { remoteMediaClient.removeListener(remoteMediaClientListener) state = PlaybackStateCompat.STATE_STOPPED if (notifyListeners) callback.onPlaybackStatusChanged(state) } override fun updateLastKnownStreamPosition() { currentPosition = currentStreamPosition } override fun play(item: QueueItem) { playItem(item) state = PlaybackStateCompat.STATE_BUFFERING callback.onPlaybackStatusChanged(state) } override fun pause() { if (remoteMediaClient.hasMediaSession()) { remoteMediaClient.pause() currentPosition = remoteMediaClient.approximateStreamPosition.toInt() } } override fun seekTo(position: Int) { if (currentMediaId == null) { callback.onError("seekTo cannot be calling in the absence of mediaId.") return } if (remoteMediaClient.hasMediaSession()) { remoteMediaClient.seek(position.toLong()) currentPosition = position } } open fun playItem(item: QueueItem) { send(item, true, item.description.mediaUri.toString(), Uri.Builder().encodedPath(item.description.iconUri.toString()).build()) } @Throws(JSONException::class) protected fun send(item: QueueItem, autoPlay: Boolean, mediaUri: String, iconUri: Uri) { val mediaId = item.description.mediaId if (mediaId == null || mediaId.isEmpty()) { throw IllegalArgumentException("Invalid mediaId") } val musicId = MediaIDHelper.extractMusicIDFromMediaID(mediaId) if (musicId == null || musicId.isEmpty()) { throw IllegalArgumentException("Invalid mediaId") } if (!TextUtils.equals(mediaId, currentMediaId) || state != PlaybackStateCompat.STATE_PAUSED) { currentMediaId = mediaId currentPosition = 0 } val customData = JSONObject() try { customData.put(ITEM_ID, mediaId) } catch (e: JSONException) { LogHelper.e(TAG, "Exception loading media ", e, null) e.message?.let { callback.onError(it) } } remoteMediaClient.load(MediaItemHelper.convertToMediaInfo( item, customData, mediaUri, iconUri), autoPlay, currentPosition.toLong(), customData) } private fun setMetadataFromRemote() { // Sync: We get the customData from the remote media information and update the local // metadata if it happens to be different from the one we are currently using. // This can happen when the app was either restarted/disconnected + connected, or if the // app joins an existing session while the Chromecast was playing a queue. try { val mediaInfo = remoteMediaClient.mediaInfo ?: return val customData = mediaInfo.customData if (customData != null && customData.has(ITEM_ID)) { val remoteMediaId = customData.getString(ITEM_ID) if (!TextUtils.equals(currentMediaId, remoteMediaId)) { currentMediaId = remoteMediaId callback.setCurrentMediaId(remoteMediaId) updateLastKnownStreamPosition() } } } catch (e: JSONException) { LogHelper.e(TAG, e, "Exception processing update metadata") } } private fun updatePlaybackState() { val status = remoteMediaClient.playerState LogHelper.d(TAG, "onRemoteMediaPlayerStatusUpdated ", status) // Convert the remote playback states to media playback states. when (status) { MediaStatus.PLAYER_STATE_IDLE -> if (remoteMediaClient.idleReason == MediaStatus.IDLE_REASON_FINISHED) { callback.onCompletion() } MediaStatus.PLAYER_STATE_BUFFERING -> { state = PlaybackStateCompat.STATE_BUFFERING callback.onPlaybackStatusChanged(state) } MediaStatus.PLAYER_STATE_PLAYING -> { state = PlaybackStateCompat.STATE_PLAYING setMetadataFromRemote() callback.onPlaybackStatusChanged(state) } MediaStatus.PLAYER_STATE_PAUSED -> { state = PlaybackStateCompat.STATE_PAUSED setMetadataFromRemote() callback.onPlaybackStatusChanged(state) } else // case unknown -> LogHelper.d(TAG, "State default : ", status) } } private inner class CastMediaClientListener : RemoteMediaClient.Listener { private var lastStatus = -1 override fun onMetadataUpdated() { LogHelper.d(TAG, "RemoteMediaClient.onMetadataUpdated") setMetadataFromRemote() } override fun onStatusUpdated() { LogHelper.d(TAG, "RemoteMediaClient.onStatusUpdated") if (lastStatus != remoteMediaClient.playerState) { updatePlaybackState() } lastStatus = remoteMediaClient.playerState } override fun onSendingRemoteMediaRequest() {} override fun onAdBreakStatusUpdated() {} override fun onQueueStatusUpdated() {} override fun onPreloadStatusUpdated() {} } companion object { private val TAG = LogHelper.makeLogTag(CastPlayback::class.java) const val ITEM_ID = "itemId" } }
apache-2.0
pocmo/focus-android
app/src/test/java/org/mozilla/focus/settings/SearchEngineValidationTest.kt
1
2353
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.settings import okhttp3.mockwebserver.MockResponse import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import okhttp3.mockwebserver.MockWebServer import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.mozilla.focus.settings.ManualAddSearchEngineSettingsFragment.isValidSearchQueryURL @RunWith(RobolectricTestRunner::class) // This unit test is not running on an Android device. Allow me to use spaces in function names. @Suppress("IllegalIdentifier") class SearchEngineValidationTest { @Test fun `URL returning 200 OK is valid`() = withMockWebServer(responseWithStatus(200)) { assertTrue(isValidSearchQueryURL(it.rootUrl())) } @Test fun `URL using HTTP redirect is invalid`() = withMockWebServer(responseWithStatus(301)) { // We now follow redirects(Issue #1976). This test now asserts false. assertFalse(isValidSearchQueryURL(it.rootUrl())) } @Test fun `URL returning 404 NOT FOUND is not valid`() = withMockWebServer(responseWithStatus(404)) { assertFalse(isValidSearchQueryURL(it.rootUrl())) } @Test fun `URL returning server error is not valid`() = withMockWebServer(responseWithStatus(500)) { assertFalse(isValidSearchQueryURL(it.rootUrl())) } @Test fun `URL timing out is not valid`() = withMockWebServer { // Without queuing a response MockWebServer will not return anything and keep the connection open assertFalse(isValidSearchQueryURL(it.rootUrl())) } } /** * Helper for creating a test that uses a mock webserver instance. */ private fun withMockWebServer(vararg responses: MockResponse, block: (MockWebServer) -> Unit) { val server = MockWebServer() responses.forEach { server.enqueue(it) } server.start() try { block(server) } finally { server.shutdown() } } private fun MockWebServer.rootUrl(): String = url("/").toString() private fun responseWithStatus(status: Int) = MockResponse() .setResponseCode(status) .setBody("")
mpl-2.0
luojilab/DDComponentForAndroid
sharecomponentkotlin/src/main/java/com/luojilab/share/kotlin/applike/KotlinAppLike.kt
1
460
package com.luojilab.share.kotlin.applike import com.luojilab.component.componentlib.applicationlike.IApplicationLike import com.luojilab.component.componentlib.router.ui.UIRouter /** * Created by mrzhang on 2018/1/3. */ class KotlinApplike : IApplicationLike { val uiRouter = UIRouter.getInstance() override fun onCreate() { uiRouter.registerUI("kotlin") } override fun onStop() { uiRouter.unregisterUI("kotlin") } }
apache-2.0
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemovePartsFromPropertyFix.kt
2
3986
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.compilerPreferences.KotlinBaseCompilerConfigurationUiBundle import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtProperty open class RemovePartsFromPropertyFix( element: KtProperty, private val removeInitializer: Boolean, private val removeGetter: Boolean, private val removeSetter: Boolean ) : KotlinQuickFixAction<KtProperty>(element) { override fun getText(): String { val chunks = ArrayList<String>(3).apply { if (removeGetter) add(KotlinBundle.message("text.getter")) if (removeSetter) add(KotlinBundle.message("text.setter")) if (removeInitializer) add(KotlinBundle.message("text.initializer")) } fun concat(head: String, tail: String): String { return head + " " + KotlinBaseCompilerConfigurationUiBundle.message("configuration.text.and") + " " + tail } val partsText = when (chunks.size) { 0 -> "" 1 -> chunks.single() 2 -> concat(chunks[0], chunks[1]) else -> concat(chunks.dropLast(1).joinToString(", "), chunks.last()) } return KotlinBundle.message("remove.0.from.property", partsText) } override fun getFamilyName(): String = KotlinBundle.message("remove.parts.from.property") public override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = this.element ?: return if (removeInitializer) { val initializer = element.initializer if (initializer != null) { if (element.typeReference == null) { val type = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(element) SpecifyTypeExplicitlyIntention.addTypeAnnotation(null, element, type) } element.deleteChildRange(element.equalsToken ?: initializer, initializer) } } if (removeGetter) { element.getter?.delete() } if (removeSetter) { element.setter?.delete() } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtProperty>? { val element = diagnostic.psiElement val property = PsiTreeUtil.getParentOfType(element, KtProperty::class.java) ?: return null return RemovePartsFromPropertyFix( property, removeInitializer = property.hasInitializer(), removeGetter = property.getter?.bodyExpression != null, removeSetter = property.setter?.bodyExpression != null ) } } object LateInitFactory : KotlinSingleIntentionActionFactory() { public override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtProperty>? { val property = Errors.INAPPLICABLE_LATEINIT_MODIFIER.cast(diagnostic).psiElement as? KtProperty ?: return null val hasInitializer = property.hasInitializer() val hasGetter = property.getter?.bodyExpression != null val hasSetter = property.setter?.bodyExpression != null if (!hasInitializer && !hasGetter && !hasSetter) { return null } return RemovePartsFromPropertyFix(property, hasInitializer, hasGetter, hasSetter) } } }
apache-2.0
onoderis/failchat
src/test/kotlin/failchat/experiment/JsonParsing.kt
2
4594
package failchat.experiment import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import failchat.twitch.TwitchEmoticon import failchat.twitch.TwitchEmoticonUrlFactory import failchat.util.nextNonNullToken import failchat.util.validate import org.junit.Test import java.io.PipedInputStream import java.io.PipedOutputStream import java.nio.file.Files import java.nio.file.Paths class JsonParsing { @Test fun streamParsingTest() { val jsonFile = Paths.get("""docs/integration/twitch/twitch-emoticons-slice.json""") // val json = """{"name":"Tom","age":25,"address":["Poland","5th avenue"]}""" val jsonFactory = JsonFactory() val parser = jsonFactory.createParser(Files.newInputStream(jsonFile)) val emoticons: MutableList<TwitchEmoticon> = ArrayList() parser.nextNonNullToken() // root object parser.nextNonNullToken() // 'emoticons' field var token = parser.nextNonNullToken() //START_ARRAY while (token != JsonToken.END_ARRAY) { token = parser.nextNonNullToken() //START_OBJECT var id: Long? = null var code: String? = null while (token != JsonToken.END_OBJECT) { parser.nextNonNullToken() // FIELD_NAME val fieldName = parser.currentName parser.nextNonNullToken() when (fieldName) { "id" -> { id = parser.longValue } "code" -> { code = parser.text } } token = parser.nextNonNullToken() // END_OBJECT } emoticons.add(TwitchEmoticon( requireNotNull(id) { "'id' not found" }, requireNotNull(code) { "'code' not found" }, TwitchEmoticonUrlFactory("pr", "sf") )) token = parser.nextNonNullToken() } parser.close() emoticons.forEach { println("${it.code}: ${it.twitchId}") } /* var parsedName: String? = null var parsedAge: Int? = null val addresses = LinkedList<String>() while (parser.nextToken() != JsonToken.END_OBJECT) { val fieldname = parser.currentName if ("name" == fieldname) { parser.nextToken() parsedName = parser.text } if ("age" == fieldname) { parser.nextToken() parsedAge = parser.intValue } if ("address" == fieldname) { parser.nextToken() while (parser.nextToken() !== JsonToken.END_ARRAY) { addresses.add(parser.getText()) } } } parser.close() */ } @Test fun streamParsingTestV2() { val jsonFile = Paths.get("""docs/integration/twitch/twitch-emoticons-slice.json""") val jsonFactory = JsonFactory() jsonFactory.codec = ObjectMapper() val parser = jsonFactory.createParser(Files.newInputStream(jsonFile)) val emoticons: MutableList<TwitchEmoticon> = ArrayList() parser.nextNonNullToken().validate(JsonToken.START_OBJECT) // root object parser.nextNonNullToken().validate(JsonToken.FIELD_NAME) // 'emoticons' field parser.nextNonNullToken().validate(JsonToken.START_ARRAY) // 'emoticons' array var token = parser.nextNonNullToken().validate(JsonToken.START_OBJECT) // emoticon object while (token != JsonToken.END_ARRAY) { val node: ObjectNode = parser.readValueAsTree() emoticons.add(TwitchEmoticon( node.get("id").longValue(), node.get("code").textValue(), TwitchEmoticonUrlFactory("pr", "sf") )) token = parser.nextNonNullToken() } parser.close() emoticons.forEach { println("${it.code}: ${it.twitchId}") } } @Test fun noDataAvailableTest() { val inStream = PipedInputStream() val outStream = PipedOutputStream(inStream) outStream.write("""{"name":"value ...""".toByteArray()) val jsonFactory = JsonFactory() val parser = jsonFactory.createParser(inStream) while (true) { println(parser.nextToken()) //thread will block here } } }
gpl-3.0
k9mail/k-9
app/core/src/main/java/com/fsck/k9/notification/NotificationGroupKeys.kt
2
297
package com.fsck.k9.notification import com.fsck.k9.Account object NotificationGroupKeys { private const val NOTIFICATION_GROUP_KEY_PREFIX = "newMailNotifications-" fun getGroupKey(account: Account): String { return NOTIFICATION_GROUP_KEY_PREFIX + account.accountNumber } }
apache-2.0
simone201/easy-auth0-java
src/main/kotlin/it/simonerenzo/easyauth0/models/User.kt
1
837
/* * Easy Auth0 Java Library * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>. */ package it.simonerenzo.easyauth0.models data class User(val username: String, val fullName: String, val email: String)
lgpl-3.0
filpgame/kotlinx-examples
app/src/main/java/com/filpgame/kotlinx/ui/list/UserAdapter.kt
1
1243
package com.filpgame.kotlinx.ui.list import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.filpgame.kotlinx.R import kotlinx.android.synthetic.main.list_row_user.view.* /** * @author Felipe Rodrigues * @since 13/02/2017 */ class UserAdapter(users: MutableList<User>? = null) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() { val users = users ?: mutableListOf<User>() override fun onBindViewHolder(holder: UserViewHolder, position: Int) { holder.view.userNameTextView.text = users[position].name holder.view.userOccupationTextView.text = users[position].occupation holder.view.userPictureImageView.setImageDrawable(ContextCompat.getDrawable(holder.view.context, users[position].picture)) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): UserViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.list_row_user, parent, false) return UserViewHolder(view) } override fun getItemCount(): Int = users.count() class UserViewHolder(val view: View) : RecyclerView.ViewHolder(view) }
mit