content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.piticlistudio.playednext.data.entity.mapper.datasources.image import com.piticlistudio.playednext.data.entity.igdb.IGDBImage import com.piticlistudio.playednext.data.entity.mapper.DataLayerMapper import com.piticlistudio.playednext.domain.model.GameImage import com.piticlistudio.playednext.domain.model.Image import javax.inject.Inject /** * Mapper for [IGDBImage] and [GameImage] models. * This mapper implements only [DataLayerMapper], since we don't need to map domain entities into IGDB models */ class IGDBImageMapper @Inject constructor() : DataLayerMapper<IGDBImage, Image> { override fun mapFromDataLayer(model: IGDBImage): Image = Image(model.mediumSizeUrl, model.width, model.height) }
app/src/main/java/com/piticlistudio/playednext/data/entity/mapper/datasources/image/IGDBImageMapper.kt
4037739440
package com.sakebook.android.library.multilinedevider.divider /** * Created by sakemotoshinya on 2017/05/21. */ interface PositionDivider: Divider { val positions: List<Int> val inverted: Boolean }
multilinedivider/src/main/kotlin/com/sakebook/android/library/multilinedevider/divider/PositionDivider.kt
2904707573
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package promotion import common.VersionedSettingsBranch import vcsroots.gradlePromotionBranches class PublishNightlySnapshotFromQuickFeedback(branch: VersionedSettingsBranch) : PublishGradleDistributionFullBuild( promotedBranch = branch.branchName, prepTask = branch.prepNightlyTaskName(), promoteTask = branch.promoteNightlyTaskName(), triggerName = "QuickFeedback", vcsRootId = gradlePromotionBranches ) { init { id("Promotion_SnapshotFromQuickFeedback") name = "Nightly Snapshot (from QuickFeedback)" description = "Promotes the latest successful changes on '${branch.branchName}' from Quick Feedback as a new nightly snapshot" } }
.teamcity/src/main/kotlin/promotion/PublishNightlySnapshotFromQuickFeedback.kt
2851801397
/* * Copyright 2022 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.pcc.chronicle.codegen.backend.api import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.PropertySpec /** * Defines an object capable of building a [PropertySpec] and injecting it into kotlinpoet builders * like [FileSpec.Builder]. */ abstract class PropertyProvider : FileSpecContentsProvider { /** Returns a [PropertySpec] that can be added to a kotlinpoet builder. */ abstract fun provideProperty(): PropertySpec override fun provideContentsInto(builder: FileSpec.Builder) { builder.addProperty(provideProperty()) } }
java/com/google/android/libraries/pcc/chronicle/codegen/backend/api/PropertyProvider.kt
529529044
/* * Copyright 2022 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.pcc.chronicle.testutil import com.google.android.libraries.pcc.chronicle.analysis.ChronicleContext import com.google.android.libraries.pcc.chronicle.analysis.DefaultChronicleContext import com.google.android.libraries.pcc.chronicle.analysis.PolicyEngine import com.google.android.libraries.pcc.chronicle.analysis.PolicySet import com.google.android.libraries.pcc.chronicle.api.Chronicle import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.flags.FlagsReader import com.google.android.libraries.pcc.chronicle.api.integration.DefaultChronicle import com.google.android.libraries.pcc.chronicle.api.integration.DefaultDataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.integration.NoOpChronicle import com.google.android.libraries.pcc.chronicle.api.policy.DefaultPolicyConformanceCheck import com.google.android.libraries.pcc.chronicle.api.policy.Policy import com.google.android.libraries.pcc.chronicle.util.Logcat import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dagger.multibindings.Multibinds import javax.inject.Singleton import kotlin.system.exitProcess import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @Module @InstallIn(SingletonComponent::class) abstract class ChronicleModule { @Multibinds abstract fun providesPolicies(): Set<Policy> @Multibinds abstract fun providesConnectionProviders(): Set<ConnectionProvider> @Multibinds abstract fun bindDtds(): Set<DataTypeDescriptor> companion object { val log = Logcat.default @Provides @Singleton fun bindDtdSetImpl(dtds: Set<@JvmSuppressWildcards DataTypeDescriptor>): DataTypeDescriptorSet = DefaultDataTypeDescriptorSet(dtds) @Provides @Singleton fun bindChronicleContextImpl( providers: Set<@JvmSuppressWildcards ConnectionProvider>, policySet: PolicySet, dtdSet: DataTypeDescriptorSet ): ChronicleContext = DefaultChronicleContext(providers, emptySet(), policySet, dtdSet) @OptIn(DelicateCoroutinesApi::class) @Provides @Singleton fun bindsChronicle( context: ChronicleContext, engine: PolicyEngine, flags: FlagsReader, ): Chronicle { // Because some policy checks happen in `ChronicleImpl` init(), when `failNewConnections` // goes from true -> false have to wait for an app restart to get the real impl back. val current = flags.config.value if (current.failNewConnections || current.emergencyDisable) { log.d("Starting Chronicle in no-op mode.") return NoOpChronicle(disabledFromStartupFlags = true) } // This listener is here rather than in ChronicleImpl to make the decision on whether to use // a NoOpImpl atomic with emergencyDisable and only enable this force-exit logic when the real // impl is active. flags.config .onEach { value -> if (value.emergencyDisable) { // Force exit the app. It will be restarted by SystemServer and when it comes back up // we will be using the no-op impl. log.i("Emergency disable engaged, restarting APK.") exitProcess(0) } } .launchIn(GlobalScope) log.d("Starting Chronicle in enabled mode.") return DefaultChronicle( context, engine, DefaultChronicle.Config( policyMode = DefaultChronicle.Config.PolicyMode.STRICT, policyConformanceCheck = DefaultPolicyConformanceCheck() ), flags ) } } }
java/com/google/android/libraries/pcc/chronicle/testutil/ChronicleModule.kt
3592092319
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache import org.gradle.api.internal.BuildScopeListenerRegistrationListener import org.gradle.api.internal.FeaturePreviews import org.gradle.api.internal.TaskInternal import org.gradle.api.internal.tasks.execution.TaskExecutionAccessListener import org.gradle.internal.buildoption.FeatureFlags import org.gradle.internal.deprecation.DeprecationLogger import org.gradle.internal.event.ListenerManager import org.gradle.internal.service.scopes.BuildScopeListenerManagerAction internal class DeprecatedFeaturesListenerManagerAction( private val featureFlags: FeatureFlags ) : BuildScopeListenerManagerAction { override fun execute(manager: ListenerManager) { manager.addListener(DeprecatedFeaturesListener(featureFlags)) } private class DeprecatedFeaturesListener( private val featureFlags: FeatureFlags ) : BuildScopeListenerRegistrationListener, TaskExecutionAccessListener { override fun onBuildScopeListenerRegistration(listener: Any, invocationDescription: String, invocationSource: Any) { if (featureFlags.isEnabled(FeaturePreviews.Feature.STABLE_CONFIGURATION_CACHE)) { DeprecationLogger.deprecateAction("Listener registration using $invocationDescription()") .willBecomeAnErrorInGradle8() .withUpgradeGuideSection(7, "task_execution_events") .nagUser() } } override fun onProjectAccess(invocationDescription: String, task: TaskInternal) { if (featureFlags.isEnabled(FeaturePreviews.Feature.STABLE_CONFIGURATION_CACHE)) { DeprecationLogger.deprecateAction("Invocation of $invocationDescription at execution time") .willBecomeAnErrorInGradle8() .withUpgradeGuideSection(7, "task_project") .nagUser() } } override fun onTaskDependenciesAccess(invocationDescription: String, task: TaskInternal) { if (featureFlags.isEnabled(FeaturePreviews.Feature.STABLE_CONFIGURATION_CACHE)) { DeprecationLogger.deprecateAction("Invocation of $invocationDescription at execution time") .willBecomeAnErrorInGradle8() .withUpgradeGuideSection(7, "task_dependencies") .nagUser() } } } }
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/DeprecatedFeaturesListenerManagerAction.kt
4210232478
package com.rpkit.chat.bukkit.chatchannel fun interface RPKChatChannelMessageCallback { operator fun invoke() }
bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/RPKChatChannelMessageCallback.kt
1463854673
package com.github.timrs2998.pdfbuilder import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature import java.io.ByteArrayOutputStream object RowElementSpec: Spek({ Feature("row") { Scenario("document with empty row in table") { val pdDocument = document { table { row {} } } Then("should save pdf") { ByteArrayOutputStream().use { os -> pdDocument.save(os) } } } } })
src/test/kotlin/com/github/timrs2998/pdfbuilder/RowElementSpec.kt
4189570591
/* * Copyright 2021 Ren Binden * 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.rpkit.players.bukkit.profile import java.security.SecureRandom import java.util.Arrays import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec class RPKProfileImpl : RPKProfile { override var id: RPKProfileId? = null override var name: RPKProfileName override var discriminator: RPKProfileDiscriminator override var passwordHash: ByteArray? override var passwordSalt: ByteArray? constructor(id: RPKProfileId, name: RPKProfileName, discriminator: RPKProfileDiscriminator, passwordHash: ByteArray? = null, passwordSalt: ByteArray? = null) { this.id = id this.name = name this.discriminator = discriminator this.passwordHash = passwordHash this.passwordSalt = passwordSalt } constructor(name: RPKProfileName, discriminator: RPKProfileDiscriminator, password: String?) { this.id = null this.name = name this.discriminator = discriminator if (password != null) { val random = SecureRandom() passwordSalt = ByteArray(16) random.nextBytes(passwordSalt) val spec = PBEKeySpec(password.toCharArray(), passwordSalt, 65536, 128) val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") passwordHash = factory.generateSecret(spec).encoded } else { passwordSalt = null passwordHash = null } } override fun setPassword(password: CharArray) { val random = SecureRandom() passwordSalt = ByteArray(16) random.nextBytes(passwordSalt) val spec = PBEKeySpec(password, passwordSalt, 65536, 128) val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") passwordHash = factory.generateSecret(spec).encoded } override fun checkPassword(password: CharArray): Boolean { if (passwordHash == null || passwordSalt == null) return false val spec = PBEKeySpec(password, passwordSalt, 65536, 128) val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") return Arrays.equals(passwordHash, factory.generateSecret(spec).encoded) } }
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKProfileImpl.kt
1576755055
package com.fwdekker.randomness.template import com.fwdekker.randomness.Bundle import com.fwdekker.randomness.CapitalizationMode.Companion.getMode import com.fwdekker.randomness.SettingsState import com.fwdekker.randomness.StateEditor import com.fwdekker.randomness.array.ArrayDecoratorEditor import com.fwdekker.randomness.template.TemplateReference.Companion.DEFAULT_CAPITALIZATION import com.fwdekker.randomness.template.TemplateReference.Companion.DEFAULT_QUOTATION import com.fwdekker.randomness.ui.MaxLengthDocumentFilter import com.fwdekker.randomness.ui.UIConstants import com.fwdekker.randomness.ui.VariableLabelRadioButton import com.fwdekker.randomness.ui.addChangeListenerTo import com.fwdekker.randomness.ui.getValue import com.fwdekker.randomness.ui.setLabel import com.fwdekker.randomness.ui.setValue import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SeparatorFactory import com.intellij.ui.TitledSeparator import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane import java.awt.BorderLayout import javax.swing.ButtonGroup import javax.swing.DefaultListModel import javax.swing.JLabel import javax.swing.JList import javax.swing.JPanel import javax.swing.ListSelectionModel /** * Component for editing [TemplateReference]s. * * @param reference the reference to edit */ @Suppress("LateinitUsage") // Initialized by scene builder class TemplateReferenceEditor(reference: TemplateReference) : StateEditor<TemplateReference>(reference) { override lateinit var rootComponent: JPanel private set override val preferredFocusedComponent get() = templateList private lateinit var templateListSeparator: TitledSeparator private lateinit var templateListPanel: JPanel private lateinit var templateListModel: DefaultListModel<Template> private lateinit var templateList: JBList<Template> private lateinit var appearanceSeparator: TitledSeparator private lateinit var capitalizationLabel: JLabel private lateinit var capitalizationGroup: ButtonGroup private lateinit var customQuotation: VariableLabelRadioButton private lateinit var quotationLabel: JLabel private lateinit var quotationGroup: ButtonGroup private lateinit var arrayDecoratorEditor: ArrayDecoratorEditor private lateinit var arrayDecoratorEditorPanel: JPanel init { nop() // Cannot use `lateinit` property as first statement in init capitalizationGroup.setLabel(capitalizationLabel) customQuotation.addToButtonGroup(quotationGroup) quotationGroup.setLabel(quotationLabel) loadState() } /** * Initializes custom UI components. * * This method is called by the scene builder at the start of the constructor. */ @Suppress("UnusedPrivateMember") // Used by scene builder private fun createUIComponents() { templateListSeparator = SeparatorFactory.createSeparator(Bundle("reference.ui.template_list"), null) templateListModel = DefaultListModel<Template>() templateList = JBList(templateListModel) templateList.cellRenderer = object : ColoredListCellRenderer<Template>() { override fun customizeCellRenderer( list: JList<out Template>, value: Template?, index: Int, selected: Boolean, hasFocus: Boolean ) { icon = value?.icon ?: Template.DEFAULT_ICON append(value?.name ?: Bundle("template.name.unknown")) } } templateList.selectionMode = ListSelectionModel.SINGLE_SELECTION templateList.setEmptyText(Bundle("reference.ui.empty")) templateListPanel = JPanel(BorderLayout()) templateListPanel.add(JBScrollPane(templateList), BorderLayout.WEST) appearanceSeparator = SeparatorFactory.createSeparator(Bundle("reference.ui.appearance"), null) customQuotation = VariableLabelRadioButton(UIConstants.WIDTH_TINY, MaxLengthDocumentFilter(2)) arrayDecoratorEditor = ArrayDecoratorEditor(originalState.arrayDecorator) arrayDecoratorEditorPanel = arrayDecoratorEditor.rootComponent } override fun loadState(state: TemplateReference) { super.loadState(state) // Find templates that would not cause recursion if selected val listCopy = (+state.templateList).deepCopy(retainUuid = true) .also { it.applySettingsState(SettingsState(it)) } val referenceCopy = listCopy.templates.flatMap { it.schemes }.single { it.uuid == originalState.uuid } as TemplateReference val validTemplates = (+state.templateList).templates .filter { template -> referenceCopy.template = template listCopy.findRecursionFrom(referenceCopy) == null } templateListModel.removeAllElements() templateListModel.addAll(validTemplates) templateList.setSelectedValue(state.template, true) customQuotation.label = state.customQuotation quotationGroup.setValue(state.quotation) capitalizationGroup.setValue(state.capitalization) arrayDecoratorEditor.loadState(state.arrayDecorator) } override fun readState() = TemplateReference( templateUuid = templateList.selectedValue?.uuid, quotation = quotationGroup.getValue() ?: DEFAULT_QUOTATION, customQuotation = customQuotation.label, capitalization = capitalizationGroup.getValue()?.let { getMode(it) } ?: DEFAULT_CAPITALIZATION, arrayDecorator = arrayDecoratorEditor.readState() ).also { it.uuid = originalState.uuid it.templateList = originalState.templateList.copy() } override fun addChangeListener(listener: () -> Unit) { templateList.addListSelectionListener { listener() } addChangeListenerTo( capitalizationGroup, quotationGroup, customQuotation, arrayDecoratorEditor, listener = listener ) } } /** * Null operation, does nothing. */ private fun nop() { // Does nothing }
src/main/kotlin/com/fwdekker/randomness/template/TemplateReferenceEditor.kt
2211343895
package fr.free.nrw.commons.category import android.content.Context import android.view.Menu import android.view.MenuItem import fr.free.nrw.commons.TestAppAdapter import fr.free.nrw.commons.TestCommonsApplication import fr.free.nrw.commons.explore.categories.media.CategoriesMediaFragment import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.MockitoAnnotations import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.robolectric.fakes.RoboMenu import org.robolectric.fakes.RoboMenuItem import org.wikipedia.AppAdapter import java.lang.reflect.Field @RunWith(RobolectricTestRunner::class) @Config(sdk = [21], application = TestCommonsApplication::class) class CategoryDetailsActivityUnitTests { private lateinit var activity: CategoryDetailsActivity private lateinit var context: Context private lateinit var menuItem: MenuItem private lateinit var menu: Menu @Mock private lateinit var categoriesMediaFragment: CategoriesMediaFragment @Before fun setUp() { MockitoAnnotations.initMocks(this) AppAdapter.set(TestAppAdapter()) context = RuntimeEnvironment.application.applicationContext activity = Robolectric.buildActivity(CategoryDetailsActivity::class.java).create().get() val fieldCategoriesMediaFragment: Field = CategoryDetailsActivity::class.java.getDeclaredField("categoriesMediaFragment") fieldCategoriesMediaFragment.isAccessible = true fieldCategoriesMediaFragment.set(activity, categoriesMediaFragment) menuItem = RoboMenuItem(null) menu = RoboMenu(context) } @Test @Throws(Exception::class) fun checkActivityNotNull() { Assert.assertNotNull(activity) } @Test @Throws(Exception::class) fun testOnMediaClicked() { activity.onMediaClicked(0) } @Test @Throws(Exception::class) fun testGetMediaAtPosition() { activity.getMediaAtPosition(0) } @Test @Throws(Exception::class) fun testGetTotalMediaCount() { activity.totalMediaCount } @Test @Throws(Exception::class) fun testGetContributionStateAt() { activity.getContributionStateAt(0) } @Test @Throws(Exception::class) fun testOnCreateOptionsMenu() { activity.onCreateOptionsMenu(menu) } @Test @Throws(Exception::class) fun testOnOptionsItemSelected() { activity.onOptionsItemSelected(menuItem) } @Test @Throws(Exception::class) fun testOnBackPressed() { activity.onBackPressed() } @Test @Throws(Exception::class) fun testViewPagerNotifyDataSetChanged() { activity.viewPagerNotifyDataSetChanged() } }
app/src/test/kotlin/fr/free/nrw/commons/category/CategoryDetailsActivityUnitTests.kt
2798459726
package fr.geobert.efficio.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import android.widget.RemoteViews import fr.geobert.efficio.R import fr.geobert.efficio.db.TaskTable import fr.geobert.efficio.db.WidgetTable import fr.geobert.efficio.misc.OnRefreshReceiver import kotlin.properties.Delegates /** * Implementation of App Widget functionality. */ class TaskListWidget : AppWidgetProvider() { val TAG = "TaskListWidget" var opacity: Float by Delegates.notNull<Float>() var storeName by Delegates.notNull<String>() var storeId by Delegates.notNull<Long>() companion object { val ACTION_CHECKBOX_CHANGED = "fr.geobert.efficio.action_checkbox_changed" } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { // There may be multiple widgets active, so update all of them Log.d(TAG, "onUpdate: ${appWidgetIds.size}") for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } super.onUpdate(context, appWidgetManager, appWidgetIds) } override fun onReceive(context: Context, intent: Intent) { val extras = intent.extras Log.d(TAG, "onReceive: ${intent.action}") val appWidgetManager = AppWidgetManager.getInstance(context) when (intent.action) { ACTION_CHECKBOX_CHANGED -> { val widgetId = extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID TaskTable.updateDoneState(context, extras.getLong("taskId"), true) appWidgetManager.notifyAppWidgetViewDataChanged( widgetId, R.id.tasks_list_widget) if (!fetchWidgetInfo(context, widgetId)) { Log.e(TAG, "onReceive ACTION_CHECKBOX_CHANGED fetchWidgetInfo FAILED") return } val i = Intent(OnRefreshReceiver.REFRESH_ACTION) i.putExtra("storeId", storeId) context.sendBroadcast(i) } "android.appwidget.action.APPWIDGET_DELETED" -> { val widgetId = extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID Log.d(TAG, "widgetId: $widgetId") WidgetTable.delete(context, widgetId) } "android.appwidget.action.APPWIDGET_UPDATE" -> { val widgetIds = extras?.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS) if (widgetIds != null) for (widgetId in widgetIds) appWidgetManager.notifyAppWidgetViewDataChanged(widgetId, R.id.tasks_list_widget) } } super.onReceive(context, intent) } override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created } override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled } private fun fetchWidgetInfo(ctx: Context, widgetId: Int): Boolean { val cursor = WidgetTable.getWidgetInfo(ctx, widgetId) if (cursor != null) { if (cursor.count > 0 && cursor.moveToFirst()) { storeId = cursor.getLong(0) opacity = cursor.getFloat(1) storeName = cursor.getString(2) return true } cursor.close() } return false } fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) { Log.d(TAG, "updateAppWidget $appWidgetId") val intent = Intent(context, TaskListWidgetService::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) if (!fetchWidgetInfo(context, appWidgetId)) { Log.e(TAG, "updateAppWidget fetchWidgetInfo FAILED") return } // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.task_list_widget) views.setInt(R.id.widget_background, "setAlpha", (opacity * 255).toInt()) views.setTextViewText(R.id.widget_store_chooser_btn, storeName) views.setRemoteAdapter(R.id.tasks_list_widget, intent) views.setEmptyView(R.id.tasks_list_widget, R.id.empty_text_widget) val onClickIntent = Intent(context, TaskListWidget::class.java) onClickIntent.action = ACTION_CHECKBOX_CHANGED onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) val pIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT) views.setPendingIntentTemplate(R.id.tasks_list_widget, pIntent) val launchIntent = Intent("android.intent.action.MAIN") launchIntent.addCategory("android.intent.category.LAUNCHER") launchIntent.component = ComponentName("fr.geobert.efficio", "fr.geobert.efficio.MainActivity") val lpIntent = PendingIntent.getActivity(context, 0, launchIntent, 0) views.setOnClickPendingIntent(R.id.widget_store_chooser_btn, lpIntent) val launchConfigIntent = Intent(context, WidgetSettingsActivity::class.java) launchConfigIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) launchConfigIntent.putExtra(WidgetSettingsActivity.FIRST_CONFIG, false) val cpIntent = PendingIntent.getActivity(context, 0, launchConfigIntent, PendingIntent.FLAG_UPDATE_CURRENT) views.setOnClickPendingIntent(R.id.widget_settings_btn, cpIntent) // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views) } }
app/src/main/kotlin/fr/geobert/efficio/widget/TaskListWidget.kt
771994816
package de.maibornwolff.codecharta.importer.sourcecodeparser import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptConfirm import com.github.kinquirer.components.promptInput import com.github.kinquirer.components.promptListObject import com.github.kinquirer.core.Choice import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface class ParserDialog { companion object : ParserDialogInterface { override fun collectParserArgs(): List<String> { val inputFileName = KInquirer.promptInput( message = "Which project folder or code file should be parsed?", hint = "file.java" ) val outputFormat = KInquirer.promptListObject( message = "Which output format should be generated?", choices = listOf(Choice("CodeCharta JSON", OutputFormat.JSON), Choice("CSV", OutputFormat.TABLE)), ) val defaultOutputFilename = if (outputFormat == OutputFormat.JSON) "output.cc.json" else "output.csv" val outputFileName: String = KInquirer.promptInput( message = "What is the name of the output file?", hint = defaultOutputFilename, default = defaultOutputFilename, ) val findIssues = KInquirer.promptConfirm( message = "Should we search for sonar issues?", default = true ) val defaultExcludes = KInquirer.promptConfirm( message = "Should we apply default excludes (build, target, dist and out folders, hidden files/folders)?", default = false ) val exclude = mutableListOf<String>() while (true) { val additionalExclude = KInquirer.promptInput( message = "Exclude file/folder according to regex pattern? Leave empty to skip.", ) if (additionalExclude.isNotBlank()) { exclude.add("--exclude=" + additionalExclude) } else { break } } val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm( message = "Do you want to compress the output file?", default = true ) val isVerbose: Boolean = KInquirer.promptConfirm(message = "Display info messages from sonar plugins?", default = false) return listOfNotNull( inputFileName, "--format=$outputFormat", "--output-file=$outputFileName", if (isCompressed) null else "--not-compressed", if (findIssues) null else "--no-issues", if (defaultExcludes) "--default-excludes" else null, if (isVerbose) "--verbose" else null, ) + exclude } } }
analysis/import/SourceCodeParser/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcecodeparser/ParserDialog.kt
2270400117
package net.perfectdreams.loritta.common.utils import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.common.emotes.Emote import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.i18n.I18nKeysData enum class TransactionType( val title: StringI18nData, val description: StringI18nData, val emote: Emote ) { PAYMENT( I18nKeysData.Commands.Command.Transactions.Types.Payment.Title, I18nKeysData.Commands.Command.Transactions.Types.Payment.Description, Emotes.Star ), COINFLIP_BET( I18nKeysData.Commands.Command.Transactions.Types.CoinFlipBet.Title, I18nKeysData.Commands.Command.Transactions.Types.CoinFlipBet.Description, Emotes.CoinHeads ), COINFLIP_BET_GLOBAL( I18nKeysData.Commands.Command.Transactions.Types.CoinFlipBetGlobal.Title, I18nKeysData.Commands.Command.Transactions.Types.CoinFlipBetGlobal.Description, Emotes.CoinTails ), EMOJI_FIGHT_BET( I18nKeysData.Commands.Command.Transactions.Types.EmojiFightBet.Title, I18nKeysData.Commands.Command.Transactions.Types.EmojiFightBet.Description, Emotes.Rooster ), HOME_BROKER( I18nKeysData.Commands.Command.Transactions.Types.HomeBroker.Title, I18nKeysData.Commands.Command.Transactions.Types.HomeBroker.Description, Emotes.LoriStonks, ), SHIP_EFFECT( I18nKeysData.Commands.Command.Transactions.Types.ShipEffect.Title, I18nKeysData.Commands.Command.Transactions.Types.ShipEffect.Description, Emotes.LoriHeart, ), SPARKLYPOWER_LSX( I18nKeysData.Commands.Command.Transactions.Types.SparklyPowerLsx.Title, I18nKeysData.Commands.Command.Transactions.Types.SparklyPowerLsx.Description, Emotes.PantufaGaming, ), SONHOS_BUNDLE_PURCHASE( I18nKeysData.Commands.Command.Transactions.Types.SonhosBundlePurchase.Title, I18nKeysData.Commands.Command.Transactions.Types.SonhosBundlePurchase.Description, Emotes.LoriRich, ), INACTIVE_DAILY_TAX( I18nKeysData.Commands.Command.Transactions.Types.InactiveDailyTax.Title, I18nKeysData.Commands.Command.Transactions.Types.InactiveDailyTax.Description, Emotes.LoriSob, ), DIVINE_INTERVENTION( I18nKeysData.Commands.Command.Transactions.Types.DivineIntervention.Title, I18nKeysData.Commands.Command.Transactions.Types.DivineIntervention.Description, Emotes.Jesus, ), BOT_VOTE( I18nKeysData.Commands.Command.Transactions.Types.BotVote.Title, I18nKeysData.Commands.Command.Transactions.Types.BotVote.Description, Emotes.LoriShining, ) }
common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/TransactionType.kt
953793259
package net.perfectdreams.loritta.cinnamon.showtime.backend.utils import kotlinx.html.DIV import kotlinx.html.FlowOrInteractiveOrPhrasingContent import kotlinx.html.IMG import kotlinx.html.div import kotlinx.html.fieldSet import kotlinx.html.id import kotlinx.html.img import kotlinx.html.legend import kotlinx.html.style import net.perfectdreams.etherealgambi.data.DefaultImageVariantPreset import net.perfectdreams.etherealgambi.data.ScaleDownToWidthImageVariantPreset import net.perfectdreams.etherealgambi.data.api.responses.ImageVariantsResponse import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend fun FlowOrInteractiveOrPhrasingContent.imgSrcSetFromResources(path: String, sizes: String, block: IMG.() -> Unit = {}) { val imageInfo = ImageUtils.optimizedImagesInfoWithVariants.firstOrNull { it.path.removePrefix("static") == path } if (imageInfo != null) { imgSrcSet( imageInfo.path.removePrefix("static"), sizes, ( imageInfo.variations!!.map { "${it.path.removePrefix("static")} ${it.width}w" } + "${imageInfo.path.removePrefix("static")} ${imageInfo.width}w" ).joinToString(", "), block ) } else error("Missing ImageInfo for \"$path\"!") } fun FlowOrInteractiveOrPhrasingContent.imgSrcSetFromEtherealGambi(m: ShowtimeBackend, variantInfo: ImageVariantsResponse, extension: String, sizes: String, block: IMG.() -> Unit = {}) { val defaultVariant = variantInfo.variants.first { it.preset is DefaultImageVariantPreset } val scaleDownVariants = variantInfo.variants.filter { it.preset is ScaleDownToWidthImageVariantPreset } val imageUrls = ( scaleDownVariants.map { "${m.etherealGambiClient.baseUrl}/${it.urlWithoutExtension}.$extension ${(it.preset as ScaleDownToWidthImageVariantPreset).width}w" } + "${m.etherealGambiClient.baseUrl}/${defaultVariant.urlWithoutExtension}.$extension ${variantInfo.imageInfo.width}w" ).joinToString(", ") imgSrcSet( "${m.etherealGambiClient.baseUrl}/${defaultVariant.urlWithoutExtension}.$extension", sizes, imageUrls ) { block() style += "aspect-ratio: ${variantInfo.imageInfo.width}/${variantInfo.imageInfo.height}" } } fun FlowOrInteractiveOrPhrasingContent.imgSrcSetFromResourcesOrFallbackToImgIfNotPresent(path: String, sizes: String, block: IMG.() -> Unit = {}) { try { imgSrcSetFromResources(path, sizes, block) } catch (e: Exception) { img(src = path, block = block) } } // Generates Image Sets fun DIV.imgSrcSet(path: String, fileName: String, sizes: String, max: Int, min: Int, stepInt: Int, block : IMG.() -> Unit = {}) { val srcsets = mutableListOf<String>() val split = fileName.split(".") val ext = split.last() for (i in (max - stepInt) downTo min step stepInt) { // "${websiteUrl}$versionPrefix/assets/img/home/lori_gabi.png 1178w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_1078w.png 1078w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_978w.png 978w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_878w.png 878w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_778w.png 778w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_678w.png 678w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_578w.png 578w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_478w.png 478w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_378w.png 378w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_278w.png 278w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_178w.png 178w" srcsets.add("$path${split.first()}_${i}w.$ext ${i}w") } srcsets.add("$path$fileName ${max}w") imgSrcSet( "$path$fileName", sizes, srcsets.joinToString(", "), block ) } fun FlowOrInteractiveOrPhrasingContent.imgSrcSet(filePath: String, sizes: String, srcset: String, block : IMG.() -> Unit = {}) { img(src = filePath) { style = "width: auto;" attributes["sizes"] = sizes attributes["srcset"] = srcset this.apply(block) } } fun DIV.adWrapper(svgIconManager: SVGIconManager, callback: DIV.() -> Unit) { // Wraps the div in a nice wrapper div { style = "text-align: center;" fieldSet { style = "display: inline;\n" + "border: 2px solid rgba(0,0,0,.05);\n" + "border-radius: 7px;\n" + "color: rgba(0,0,0,.3);" legend { style = "margin-left: auto;" svgIconManager.ad.apply(this) } div { callback.invoke(this) } } } } fun DIV.mediaWithContentWrapper( mediaOnTheRightSide: Boolean, mediaFigure: DIV.() -> (Unit), mediaBody: DIV.() -> (Unit), ) { div(classes = "media") { if (mediaOnTheRightSide) { div(classes = "media-body") { mediaBody.invoke(this) } div(classes = "media-figure") { mediaFigure.invoke(this) } } else { div(classes = "media-figure") { mediaFigure.invoke(this) } div(classes = "media-body") { mediaBody.invoke(this) } } } } fun DIV.innerContent(block: DIV.() -> (Unit)) = div { id = "inner-content" div(classes = "background-overlay") {} block.invoke(this) } /* fun DIV.generateNitroPayAdOrSponsor(sponsorId: Int, adSlot: String, adName: String? = null, callback: (NitroPayAdDisplay) -> (Boolean)) { // TODO: Fix val sponsors = listOf<Sponsor>() // loritta.sponsors val sponsor = sponsors.getOrNull(sponsorId) if (sponsor != null) { generateSponsor(sponsor) } else { generateNitroPayAdOrSponsor(sponsorId, "$adSlot-desktop", NitroPayAdDisplay.DESKTOP, "Loritta Daily Reward", callback.invoke( NitroPayAdDisplay.DESKTOP)) generateNitroPayAdOrSponsor(sponsorId, "$adSlot-phone", NitroPayAdDisplay.PHONE, "Loritta Daily Reward", callback.invoke( NitroPayAdDisplay.PHONE)) generateNitroPayAdOrSponsor(sponsorId, "$adSlot-tablet", NitroPayAdDisplay.TABLET, "Loritta Daily Reward", callback.invoke( NitroPayAdDisplay.TABLET)) } } fun DIV.generateNitroPayAd(adSlot: String, adName: String? = null) { generateNitroPayAd("$adSlot-desktop", NitroPayAdDisplay.DESKTOP, "Loritta Daily Reward") generateNitroPayAd("$adSlot-phone", NitroPayAdDisplay.PHONE, "Loritta Daily Reward") generateNitroPayAd("$adSlot-tablet", NitroPayAdDisplay.TABLET, "Loritta Daily Reward") } // TODO: Fix fun DIV.generateNitroPayAdOrSponsor(sponsorId: Int, adSlot: String, displayType: NitroPayAdDisplay, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) = generateNitroPayAdOrSponsor(listOf<Sponsor>(), sponsorId, adSlot, displayType, adName, showIfSponsorIsMissing) fun DIV.generateNitroPayAdOrSponsor(sponsors: List<Sponsor>, sponsorId: Int, adSlot: String, displayType: NitroPayAdDisplay, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) { val sponsor = sponsors.getOrNull(sponsorId) if (sponsor != null) { generateSponsor(sponsor) } else if (showIfSponsorIsMissing) { generateNitroPayAd(adSlot, displayType, adName) } } // TODO: Fix fun DIV.generateNitroPayVideoAdOrSponsor(sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) = generateNitroPayVideoAdOrSponsor(listOf(), sponsorId, adSlot, adName, showIfSponsorIsMissing) fun DIV.generateNitroPayVideoAdOrSponsor(sponsors: List<Sponsor>, sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) { val sponsor = sponsors.getOrNull(sponsorId) if (sponsor != null) { generateSponsor(sponsor) } else if (showIfSponsorIsMissing) { generateNitroPayVideoAd(adSlot, adName) } } fun DIV.generateAdOrSponsor(sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) = generateAdOrSponsor(listOf(), sponsorId, adSlot, adName, showIfSponsorIsMissing) fun DIV.generateAdOrSponsor(sponsors: List<Sponsor>, sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) { val sponsor = sponsors.getOrNull(sponsorId) if (sponsor != null) { generateSponsor(sponsor) } else if (showIfSponsorIsMissing) { generateAd(adSlot, adName, showOnMobile) } } fun DIV.generateSponsor(sponsor: Sponsor) { div(classes = "media") { generateSponsorNoWrap(sponsor) } } fun DIV.generateSponsorNoWrap(sponsor: Sponsor) { a(href = "/sponsor/${sponsor.slug}", classes = "sponsor-wrapper", target = "_blank") { div(classes = "sponsor-pc-image") { img(src = sponsor.getRectangularBannerUrl(), classes = "sponsor-banner") } div(classes = "sponsor-mobile-image") { img(src = sponsor.getSquareBannerUrl(), classes = "sponsor-banner") } } } fun DIV.generateHowToSponsorButton(locale: BaseLocale) { div(classes = "media") { style = "justify-content: end;" div { style = "font-size: 0.8em; margin: 8px;" + (locale["website.sponsors.wantYourServerHere"] + " ") a(href = "/sponsors") { span(classes = "sponsor-button") { + "Premium Slots" } } } } } fun DIV.generateAd(adSlot: String, adName: String? = null, showOnMobile: Boolean = true) { // O "adName" não é utilizado para nada, só está aí para que fique mais fácil de analisar aonde está cada ad (caso seja necessário) // TODO: Random ID val adGen = "ad-$adSlot-" div(classes = "centralized-ad") { ins(classes = "adsbygoogle") { style = "display: block;" if (!showOnMobile) attributes["id"] = adGen attributes["data-ad-client"] = "ca-pub-9989170954243288" attributes["data-ad-slot"] = adSlot attributes["data-ad-format"] = "auto" attributes["data-full-width-responsive"] = "true" } } if (!showOnMobile) { script(type = ScriptType.textJavaScript) { unsafe { raw("if (document.body.clientWidth >= 1366) { (adsbygoogle = window.adsbygoogle || []).push({}); } else { console.log(\"Not displaying ad: Browser width is too smol!\"); document.querySelector(\"#$adGen\").remove(); }") } } } else { script(type = ScriptType.textJavaScript) { unsafe { raw("(adsbygoogle = window.adsbygoogle || []).push({});") } } } } fun DIV.generateNitroPayAd(adId: String, displayType: NitroPayAdDisplay, adName: String? = null) { // O "adName" não é utilizado para nada, só está aí para que fique mais fácil de analisar aonde está cada ad (caso seja necessário) div(classes = "centralized-ad") { div(classes = "nitropay-ad") { id = adId attributes["data-nitropay-ad-type"] = NitroPayAdType.STANDARD_BANNER.name.toLowerCase() attributes["data-nitropay-ad-display"] = displayType.name.toLowerCase() } } } fun DIV.generateNitroPayVideoAd(adId: String, adName: String? = null) { // O "adName" não é utilizado para nada, só está aí para que fique mais fácil de analisar aonde está cada ad (caso seja necessário) div(classes = "centralized-ad") { div(classes = "nitropay-ad") { id = adId attributes["data-nitropay-ad-type"] = NitroPayAdType.VIDEO_PLAYER.name.toLowerCase() attributes["data-nitropay-ad-display"] = NitroPayAdDisplay.RESPONSIVE.name.toLowerCase() } } } */
web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/utils/WebUtils.kt
928055517
/* * Copyright 2016, 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 org.owntracks.android.support import androidx.test.espresso.IdlingResource import androidx.test.espresso.IdlingResource.ResourceCallback import org.jetbrains.annotations.NotNull import java.util.concurrent.atomic.AtomicBoolean /** * A very simple implementation of [IdlingResource]. * * * Consider using CountingIdlingResource from espresso-contrib package if you use this class from * multiple threads or need to keep a count of pending operations. */ class SimpleIdlingResource(private val resourceName: @NotNull String, initialIdlingState: Boolean) : IdlingResource { @Volatile private var mCallback: ResourceCallback? = null // Idleness is controlled with this boolean. private val mIsIdleNow = AtomicBoolean(initialIdlingState) override fun getName(): String { return this.resourceName } override fun isIdleNow(): Boolean { return mIsIdleNow.get() } override fun registerIdleTransitionCallback(callback: ResourceCallback) { mCallback = callback } /** * Sets the new idle state, if isIdleNow is true, it pings the [ResourceCallback]. * @param isIdleNow false if there are pending operations, true if idle. */ fun setIdleState(isIdleNow: Boolean) { mIsIdleNow.set(isIdleNow) if (isIdleNow && mCallback != null) { mCallback!!.onTransitionToIdle() } } }
project/app/src/main/java/org/owntracks/android/support/SimpleIdlingResource.kt
570926850
package kratos.card.utils /** * Created by sanvi on 11/16/15. */ interface OnCardRenderListener { open fun onRender(json: String): String }
kratos/src/main/java/kratos/card/utils/OnCardRenderListener.kt
158960886
fun main(args: Array<String>) { println("Hello, World.") }
src/main/kotlin/HelloWorld.kt
2046213956
import com.mongodb.BasicDBObject import io.vertx.kotlin.core.json.get import io.vertx.kotlin.core.json.json import io.vertx.kotlin.core.json.obj import org.junit.Test import org.springframework.data.mongodb.core.query.Criteria class CriteriaTest { @Test fun testCriteria() { // val criteria = Criteria.where("x").`is`("dfdf").andOperator( // Criteria.where("y").ne("dddd"), // Criteria.where("m.z").lt("mm") // ).orOperator( // Criteria.where("q").ne("1qq"), // Criteria.where("m.1").gt("11") // ) // // criteria.criteriaObject.keySet().forEach { // println("criteria key:$it") // } // // println("criteria:${criteria.criteriaObject}") // // println(criteria.criteriaObject.containsField("\$and")) // criteria.criteriaObject } }
src/test/kotlin/CriteriaTest.kt
1426706887
package non_test.kotlin_playground //fun `func is fun`() { // val btn1: JButton = JButton().apply { // text = "hihi" // true // } // val btn2: JButton = with(JButton()) { // text = "hihi" // this // } // val panel = JPanel() // panel.add(JButton().let { btn -> // btn.text = "hihi" // btn // }) //} fun main(args: Array<String>) { myRecursion(10) } fun myRecursion(max: Int) { _myRecursion(1, max) } fun _myRecursion(current: Int, max: Int) { when { current <= max -> { println(current); _myRecursion(current + 1, max) } else -> return } }
src/test/kotlin/non_test/kotlin_playground/misc.kt
1931789280
package at.cpickl.gadsu.mail import at.cpickl.gadsu.isNotValidMail data class Mail( val recipients: List<String>, val subject: String, val body: String, val recipientsAsBcc: Boolean = true ) { constructor(recipient: String, subject: String, body: String, recipientsAsBcc: Boolean = true): this(listOf(recipient), subject, body, recipientsAsBcc) init { if (recipients.isEmpty()) { throw IllegalArgumentException("Recipients must not be empty! ($this)") } if (recipients.any(String::isNotValidMail)) { throw IllegalArgumentException("There was an invalid address in the list of recipients! ($this)") } } } data class MailPreferencesData( val subject: String, val body: String )
src/main/kotlin/at/cpickl/gadsu/mail/model.kt
1715945058
package ee.asm import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodNode internal interface ClassTreeUtils { val classTree: ClassTree fun isExcluded(node: ClassNode): Boolean fun isExcluded(node: MethodNodeWithClass): Boolean fun findAvailableClasses(): List<ClassNode> = classTree.filter { !isExcluded(it) } fun findAvailableMethods(availableClasses: List<ClassNode>): List<MethodNodeWithClass> { return availableClasses.flatMap { classNode -> classNode.methods?.map { MethodNodeWithClass(classNode, it as MethodNode) }?.filter { !isExcluded(it) } ?: listOf() } } val ClassNode.isView: Boolean get() { val isSuccessor = classTree.isSuccessorOf(this, "android/view/View") || this.name == "android/view/View" return isSuccessor && !isInner } val ClassNode.isLayoutParams: Boolean get() { return isInner && (classTree.isSuccessorOf(this, "android/view/ViewGroup\$LayoutParams") || this.name == "android/view/ViewGroup\$LayoutParams") } val ClassNode.isViewGroup: Boolean get() { return !isInner && (classTree.isSuccessorOf(this, "android/view/ViewGroup") || this.name == "android/view/ViewGroup") } fun ClassNode.resolveAllMethods(): List<MethodNode> { val node = classTree.findNode(this) fun allMethodsTo(node: ClassTreeNode?, list: MutableList<MethodNode>) { if (node == null) return list.addAll(node.data.methods as List<MethodNode>) allMethodsTo(node.parent, list) } val list = arrayListOf<MethodNode>() allMethodsTo(node, list) return list } }
ee-asm/src/main/kotlin/ee/asm/ClassTreeUtils.kt
3424546803
package uk.co.appsbystudio.geoshare.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo private fun getNetworkInfo(context: Context): NetworkInfo? { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return connectivityManager.activeNetworkInfo } fun isConnected(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnected } fun isConnectedWifi(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_WIFI } fun isConnectedMobile(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE }
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/Connectivity.kt
1134329042
package uk.co.appsbystudio.geoshare.friends.profile.friends.pages.all import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import uk.co.appsbystudio.geoshare.utils.firebase.FirebaseHelper class ProfileFriendsAllInteractorImpl: ProfileFriendsAllInteractor { private lateinit var friendsListener: ChildEventListener private var friendsRef: DatabaseReference? = null override fun getFriends(uid: String?, listener: ProfileFriendsAllInteractor.OnFirebaseListener) { val user = FirebaseAuth.getInstance().currentUser friendsRef = FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.FRIENDS}/$uid") friendsListener = object : ChildEventListener { override fun onChildAdded(dataSnapshot: DataSnapshot, string: String?) { if (dataSnapshot.key != user?.uid) listener.add(dataSnapshot.key) } override fun onChildChanged(dataSnapshot: DataSnapshot, string: String?) { } override fun onChildRemoved(dataSnapshot: DataSnapshot) { listener.remove(dataSnapshot.key) } override fun onChildMoved(dataSnapshot: DataSnapshot, string: String?) { } override fun onCancelled(databaseError: DatabaseError) { listener.error(databaseError.message) } } friendsRef?.addChildEventListener(friendsListener) } override fun sendFriendRequest(uid: String?, listener: ProfileFriendsAllInteractor.OnFirebaseListener) { val user = FirebaseAuth.getInstance().currentUser FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid/outgoing").setValue(true) .addOnSuccessListener { listener.success("Friend request sent") }.addOnFailureListener { listener.error(it.message.toString()) } FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}/outgoing").setValue(false) } override fun removeListener() { friendsRef?.removeEventListener(friendsListener) } }
mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/profile/friends/pages/all/ProfileFriendsAllInteractorImpl.kt
1191308483
/** * Copyright 2021 Carl-Philipp Harmant * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.cph.chicago.core.model import android.os.Parcel import android.os.Parcelable import fr.cph.chicago.core.model.enumeration.TrainLine import java.io.Serializable import java.util.Date import java.util.Locale import java.util.concurrent.TimeUnit import org.apache.commons.lang3.StringUtils /** * TrainEta entity * * @author Carl-Philipp Harmant * @version 1 */ data class TrainEta( val trainStation: TrainStation, val stop: Stop, val routeName: TrainLine, val destName: String, private val predictionDate: Date, private val arrivalDepartureDate: Date, private val isApp: Boolean, private var isDly: Boolean) : Comparable<TrainEta>, Parcelable, Serializable { companion object { private const val serialVersionUID = 0L fun buildFakeEtaWith(trainStation: TrainStation, arrivalDepartureDate: Date, predictionDate: Date, app: Boolean, delay: Boolean): TrainEta { return TrainEta(trainStation, Stop.buildEmptyStop(), TrainLine.NA, StringUtils.EMPTY, predictionDate, arrivalDepartureDate, app, delay) } @JvmField val CREATOR: Parcelable.Creator<TrainEta> = object : Parcelable.Creator<TrainEta> { override fun createFromParcel(source: Parcel): TrainEta { return TrainEta(source) } override fun newArray(size: Int): Array<TrainEta?> { return arrayOfNulls(size) } } } constructor(source: Parcel) : this( trainStation = source.readParcelable<TrainStation>(TrainStation::class.java.classLoader) ?: TrainStation.buildEmptyStation(), stop = source.readParcelable<Stop>(Stop::class.java.classLoader) ?: Stop.buildEmptyStop(), routeName = TrainLine.fromXmlString(source.readString() ?: StringUtils.EMPTY), destName = source.readString() ?: StringUtils.EMPTY, predictionDate = Date(source.readLong()), arrivalDepartureDate = Date(source.readLong()), isApp = source.readString()?.toBoolean() ?: false, isDly = source.readString()?.toBoolean() ?: false ) private val timeLeft: String get() { val time = arrivalDepartureDate.time - predictionDate.time return String.format(Locale.ENGLISH, "%d min", TimeUnit.MILLISECONDS.toMinutes(time)) } val timeLeftDueDelay: String get() { return if (isDly) { "Delay" } else { if (isApp) "Due" else timeLeft } } override fun compareTo(other: TrainEta): Int { val time1 = arrivalDepartureDate.time - predictionDate.time val time2 = other.arrivalDepartureDate.time - other.predictionDate.time return time1.compareTo(time2) } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { with(dest) { writeParcelable(trainStation, flags) writeParcelable(stop, flags) writeString(routeName.toTextString()) writeString(destName) writeLong(predictionDate.time) writeLong(arrivalDepartureDate.time) writeString(isApp.toString()) writeString(isDly.toString()) } } }
android-app/src/main/kotlin/fr/cph/chicago/core/model/TrainEta.kt
903141749
package com.lasthopesoftware.bluewater.shared.resilience.GivenTwoSecondOneTriggersTimedCountdownLatch import com.lasthopesoftware.bluewater.shared.resilience.TimedCountdownLatch import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test class WhenTriggeringTheLatch { companion object { private var isClosed = false @JvmStatic @BeforeClass fun setup() { val timedLatch = TimedCountdownLatch(1, Duration.standardSeconds(2)) isClosed = timedLatch.trigger() } } @Test fun thenTheLatchIsClosed() { assertThat(isClosed).isTrue } }
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/shared/resilience/GivenTwoSecondOneTriggersTimedCountdownLatch/WhenTriggeringTheLatch.kt
2232990239
package com.sksamuel.kotest.throwablehandling import io.kotest.assertions.throwables.shouldNotThrowAny import io.kotest.assertions.throwables.shouldNotThrowAnyUnit import io.kotest.assertions.throwables.shouldThrowAny import io.kotest.assertions.throwables.shouldThrowAnyUnit import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import io.kotest.matchers.types.shouldBeSameInstanceAs class AnyThrowableHandlingTest : FreeSpec() { init { onShouldThrowAnyMatcher { shouldThrowAnyMatcher -> "Should throw any ($shouldThrowAnyMatcher)" - { "Should throw an exception" - { "When no exception is thrown in the code" { verifyThrowsNoExceptionError { shouldThrowAnyMatcher { /* No exception being thrown */ } } } } "Should return the thrown instance" - { "When an exception is thrown in the code" { val instanceToThrow = FooRuntimeException() verifyReturnsExactly(instanceToThrow) { shouldThrowAnyMatcher { throw instanceToThrow } } } } } } onShouldNotThrowAnyMatcher { shouldNotThrowAnyMatcher -> "Should not throw any($shouldNotThrowAnyMatcher)" - { "Should throw an exception" - { "When any exception is thrown in the code" { val exception = FooRuntimeException() verifyThrowsAssertionWrapping(exception) { shouldNotThrowAnyMatcher { throw exception } } } } "Should not throw an exception" - { "When no exception is thrown in the code" { verifyNoErrorIsThrown { shouldNotThrowAnyMatcher { /* Nothing thrown */ } } } } } } } private inline fun onShouldThrowAnyMatcher(func: (ShouldThrowAnyMatcher) -> Unit) { func(::shouldThrowAny) func(::shouldThrowAnyUnit) } private fun verifyThrowsNoExceptionError(block: () -> Unit) { val thrown = catchThrowable(block) thrown.shouldBeInstanceOf<AssertionError>() thrown!!.message shouldBe "Expected a throwable, but nothing was thrown." } private fun verifyReturnsExactly(thrownInstance: Throwable, block: () -> Any?) { val actualReturn = block() (actualReturn === thrownInstance).shouldBeTrue() } private inline fun onShouldNotThrowAnyMatcher(func: (ShouldNotThrowAnyMatcher) -> Unit) { func(::shouldNotThrowAny) func(::shouldNotThrowAnyUnit) } private fun verifyThrowsAssertionWrapping(throwable: Throwable, block: () -> Any?) { val thrownException = catchThrowable(block) thrownException.shouldBeInstanceOf<AssertionError>() thrownException!!.message shouldBe "No exception expected, but a ${throwable::class.simpleName} was thrown." thrownException.cause shouldBeSameInstanceAs throwable } private fun verifyNoErrorIsThrown(block: () -> Unit) { catchThrowable(block) shouldBe null } } private typealias ShouldThrowAnyMatcher = (() -> Unit) -> Throwable private typealias ShouldNotThrowAnyMatcher = (() -> Unit) -> Unit
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/throwablehandling/AnyThrowableHandlingTest.kt
2802378258
package io.kotest.core.spec import java.nio.file.Paths import kotlin.reflect.KClass /** * An implementation of [SpecExecutionOrder] which will run specs that * contained a failed test on a previous run first, before specs where * all the tests passed. */ object FailureFirstSpecExecutionOrder : SpecExecutionOrder { override fun sort(classes: List<KClass<out Spec>>): List<KClass<out Spec>> { // try to locate a folder called .kotest which should contain a file called spec_failures // each line in this file is a failed spec and they should run first // if the file doesn't exist then we just execute in Lexico order val path = Paths.get(".kotest").resolve("spec_failures") return if (path.toFile().exists()) { val classnames = path.toFile().readLines() val (failed, passed) = classes.partition { classnames.contains(it.qualifiedName) } LexicographicSpecExecutionOrder.sort(failed) + LexicographicSpecExecutionOrder.sort( passed) } else { LexicographicSpecExecutionOrder.sort(classes) } } }
kotest-core/src/jvmMain/kotlin/io/kotest/core/spec/FailureFirstSpecExecutionOrder.kt
121030245
package pokur.calculate import pokur.Card /** * Created by jiaweizhang on 6/12/2017. */ class HandProcessor { private fun getSevenCards(communityCards: List<Card>, holeCards: PlayerHand): List<Card> { return communityCards.plus(holeCards.holeCards.first).plus(holeCards.holeCards.second) } fun rank(communityCards: List<Card>, holeCards: List<PlayerHand>): List<List<RankingUnit>> { val handRanking = mutableListOf<List<RankingUnit>>() val temporaryRanking = mutableListOf<RankingUnit>() holeCards.forEach { val rank = findHandValue7Complex(getSevenCards(communityCards, it)) temporaryRanking.add(RankingUnit(it, rank)) } val rankingGroups = temporaryRanking.groupBy { it.rank } rankingGroups.keys.toSortedSet().reversed().mapTo(handRanking) { rankingGroups.getValue(it) } return handRanking } fun findHandValue7Using5(sevenCards: List<Card>): Int { val fiveCardsList = listOf(sevenCards.subList(0, 5), listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[5]), listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[6]), listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[4], sevenCards[5]), listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[4], sevenCards[6]), listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[5], sevenCards[6]), listOf(sevenCards[0], sevenCards[1], sevenCards[3], sevenCards[4], sevenCards[5]), listOf(sevenCards[0], sevenCards[1], sevenCards[3], sevenCards[4], sevenCards[6]), listOf(sevenCards[0], sevenCards[1], sevenCards[3], sevenCards[5], sevenCards[6]), listOf(sevenCards[0], sevenCards[1], sevenCards[4], sevenCards[5], sevenCards[6]), listOf(sevenCards[0], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[5]), listOf(sevenCards[0], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[6]), listOf(sevenCards[0], sevenCards[2], sevenCards[3], sevenCards[5], sevenCards[6]), listOf(sevenCards[0], sevenCards[2], sevenCards[4], sevenCards[5], sevenCards[6]), listOf(sevenCards[0], sevenCards[3], sevenCards[4], sevenCards[5], sevenCards[6]), listOf(sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[5]), listOf(sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[6]), listOf(sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[5], sevenCards[6]), listOf(sevenCards[1], sevenCards[2], sevenCards[4], sevenCards[5], sevenCards[6]), listOf(sevenCards[1], sevenCards[3], sevenCards[4], sevenCards[5], sevenCards[6]), listOf(sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[5], sevenCards[6])) return fiveCardsList.map { findHandValue5(it) }.max()!!.toInt() } fun findHandValue6Using5(sixCards: List<Card>): Int { val fiveCardsList = listOf(sixCards.subList(0, 5), listOf(sixCards[0], sixCards[2], sixCards[3], sixCards[4], sixCards[5]), listOf(sixCards[0], sixCards[1], sixCards[3], sixCards[4], sixCards[5]), listOf(sixCards[0], sixCards[1], sixCards[2], sixCards[4], sixCards[5]), listOf(sixCards[0], sixCards[1], sixCards[2], sixCards[3], sixCards[5]), listOf(sixCards[1], sixCards[2], sixCards[3], sixCards[4], sixCards[5])) return fiveCardsList.map { findHandValue5(it) }.max()!!.toInt() } fun findHandValue5(fiveCards: List<Card>): Int { // find handValue using grouping var pair1 = -1 var pair2 = -1 var set = -1 var high2 = -1 var high3 = -1 var high4 = -1 val one = fiveCards[0] val two = fiveCards[1] val three = fiveCards[2] val four = fiveCards[3] val five = fiveCards[4] // process first card var high1 = one.face // process second card if (two.face == high1) { // 2 pair1 = high1 high1 = -1 } else { // 1 1 high2 = two.face } // process third card if (three.face == pair1) { // 3 set = pair1 pair1 = -1 } else if (pair1 != -1) { // 2 1 high1 = three.face } else { if (three.face == high1) { // 2 1 pair1 = high1 high1 = high2 high2 = -1 } else if (three.face == high2) { // 2 1 pair1 = high2 high2 = -1 } else { // 1 1 1 high3 = three.face } } // process fourth card if (four.face == set) { // 4 - can return quad return (8 shl 20) + (set shl 16) + (five.face shl 12) } else if (set != -1) { // 3 1 high1 = four.face } else { if (four.face == pair1) { // 3 1 set = pair1 pair1 = -1 } else if ((pair1 != -1) and (four.face == high1)) { // 2 2 pair2 = high1 high1 = -1 } else if ((pair1 != -1)) { high2 = four.face } else if (four.face == high1) { // 2 1 1 pair1 = high1 high1 = high2 high2 = high3 high3 = -1 } else if (four.face == high2) { // 2 1 1 pair1 = high2 high2 = high3 high3 = -1 } else if (four.face == high3) { // 2 1 1 pair1 = high3 high3 = -1 } else { // 1 1 1 1 high4 = four.face } } // process fifth card if (five.face == set) { // 4 - return quad return (8 shl 20) + (set shl 16) + (high1 shl 12) } else { if ((set != -1) and (five.face == high1)) { // 3 2 - return FH return (7 shl 20) + (set shl 16) + (high1 shl 12) } else if (set != -1) { // 3 1 1 - return set return (4 shl 20) + (set shl 16) + ((if (high1 > five.face) high1 else five.face) shl 12) + ((if (high1 > five.face) five.face else high1) shl 8) } else if (five.face == pair2) { // 3 2 - return FH return (7 shl 20) + (pair2 shl 16) + (pair1 shl 12) } else if ((five.face == pair1) and (pair2 != -1)) { // 3 2 - return FH return (7 shl 20) + (pair1 shl 16) + (pair2 shl 12) } else if ((pair1 != -1) and (pair2 != -1)) { // 2 2 1 return (3 shl 20) + ((if (pair1 > pair2) pair1 else pair2) shl 16) + ((if (pair1 > pair2) pair2 else pair1) shl 12) + (five.face shl 8) } else if (five.face == pair1) { // 3 1 1 return (4 shl 20) + (pair1 shl 16) + ((if (high1 > high2) high1 else high2) shl 12) + ((if (high1 > high2) high2 else high1) shl 8) } else if ((pair1 != -1) and (five.face == high1)) { // 2 2 1 return (3 shl 20) + ((if (pair1 > high1) pair1 else high1) shl 16) + ((if (pair1 > high1) high1 else pair1) shl 12) + (high2 shl 8) } else if ((pair1 != -1) and (five.face == high2)) { // 2 2 1 return (3 shl 20) + ((if (pair1 > high2) pair1 else high2) shl 16) + ((if (pair1 > high2) high2 else pair1) shl 12) + (high1 shl 8) } else if ((pair1 != -1)) { // 2 1 1 1 return (2 shl 20) + (pair1 shl 16) + (order3(high1, high2, five.face) shl 4) } else if (five.face == high1) { // 2 1 1 1 return (2 shl 20) + (high1 shl 16) + (order3(high2, high3, high4) shl 4) } else if (five.face == high2) { // 2 1 1 1 return (2 shl 20) + (high2 shl 16) + (order3(high1, high3, high4) shl 4) } else if (five.face == high3) { // 2 1 1 1 return (2 shl 20) + (high3 shl 16) + (order3(high1, high2, high4) shl 4) } else if (five.face == high4) { // 2 1 1 1 return (2 shl 20) + (high4 shl 16) + (order3(high1, high2, high3) shl 4) } else { // 1 1 1 1 1 val flush = ((one.suit == two.suit) and (one.suit == three.suit) and (one.suit == four.suit) and (one.suit == five.suit)) val order5 = order5(one.face, two.face, three.face, four.face, five.face) val straight = order5 and 0b1111 if (flush and (straight != 0)) { return (9 shl 20) + (straight shl 16) } if (flush) { return (6 shl 20) + (order5 shr 4) } if (straight != 0) { return (5 shl 20) + (straight shl 16) } return (1 shl 20) + (order5 shr 4) } } } fun order3(one: Int, two: Int, three: Int): Int { var tmp: Int var a = one var b = two var c = three if (b < c) { tmp = b b = c c = tmp } if (a < c) { tmp = a a = c c = tmp } if (a < b) { tmp = a a = b b = tmp } return (a shl 8) + (b shl 4) + c } fun order5(one: Int, two: Int, three: Int, four: Int, five: Int): Int { var tmp: Int var a = one var b = two var c = three var d = four var e = five if (a < b) { tmp = a a = b b = tmp } if (d < e) { tmp = d d = e e = tmp } if (c < e) { tmp = c c = e e = tmp } if (c < d) { tmp = c c = d d = tmp } if (b < e) { tmp = b b = e e = tmp } if (a < d) { tmp = a a = d d = tmp } if (a < c) { tmp = a a = c c = tmp } if (b < d) { tmp = b b = d d = tmp } if (b < c) { tmp = b b = c c = tmp } val straight = if ((a == b + 1) and (a == c + 2) and (a == d + 3) and (a == e + 4)) { a } else if ((a == 12) and (b == 3) and (c == 2) and (d == 1) and (e == 0)) { 3 } else { 0 } return (a shl 20) + (b shl 16) + (c shl 12) + (d shl 8) + (e shl 4) + straight } fun findHandValue7Complex(sevenCards: List<Card>): Int { var type: Int val sortedCards = sevenCards.sortedByDescending { it.face } val groupedCards = sevenCards.groupBy { it.face } val first = sortedCards.get(0).face val second = sortedCards.get(1).face val third = sortedCards.get(2).face val fourth = sortedCards.get(3).face val fifth = sortedCards.get(4).face val sixth = sortedCards.get(5).face val seventh = sortedCards.get(6).face var twoPairTopPair = -1 var twoPairBottomPair = -1 var twoPairKicker = -1 var triple = -1 var tripleKicker = -1 var tripleKicker2 = -1 var pair = -1 var pairKicker = -1 var pairKicker2 = -1 var pairKicker3 = -1 var straightHigh = -1 var spadesCount = 0 var heartsCount = 0 var clubsCount = 0 var diamondsCount = 0 when (groupedCards.size) { 2 -> { // 4 3 - Q // if count quad, cannot possibly be SF if (first == fourth) { return (8 shl 20) + (first shl 16) + (fifth shl 12) } else { return (8 shl 20) + (fourth shl 16) + (first shl 12) } } 3 -> { // 4 2 1 - Q if (groupedCards.any { it.value.size == 4 }) { if (first == second) { if (second == third) { // quad is top return (8 shl 20) + (first shl 16) + (fifth shl 12) } else { // pair is top if (third == fourth) { // quad is after top return (8 shl 20) + (third shl 16) + (first shl 12) } else { // quad is last return (8 shl 20) + (fourth shl 16) + (first shl 12) } } } else { if (second == fourth) { // 1 4 2 return (8 shl 20) + (second shl 16) + (first shl 12) } else { // 1 2 4 return (8 shl 20) + (fourth shl 16) + (first shl 12) } } } // 3 3 1 - FH else if (groupedCards.any { it.value.size == 1 }) { if (first == second) { // 3 3 1 or 3 1 3 if (fourth == fifth) { // 3 3 1 return (7 shl 20) + (first shl 16) + (fourth shl 12) } else { // 3 1 3 return (7 shl 20) + (first shl 16) + (fifth shl 12) } } else { // 1 3 3 return (7 shl 20) + (second shl 16) + (fifth shl 12) } } // 3 2 2 - FH else { if (second == third) { // 3 2 2 return (7 shl 20) + (first shl 16) + (fourth shl 12) } else if (fourth == fifth) { // 2 3 2 return (7 shl 20) + (third shl 16) + (first shl 12) } else { // 2 2 3 return (7 shl 20) + (fifth shl 16) + (first shl 12) } } } 4 -> { // 4 1 1 1 if (groupedCards.any { it.value.size == 4 }) { if (first == second) { // 4 1 1 1 return (8 shl 20) + (first shl 16) + (fifth shl 12) } else if (second == third) { // 1 4 1 1 return (8 shl 20) + (second shl 16) + (first shl 12) } else if (third == fourth) { // 1 1 4 1 return (8 shl 20) + (third shl 16) + (first shl 12) } else { // 1 1 1 4 return (8 shl 20) + (fourth shl 16) + (first shl 12) } } // 3 2 1 1 else if (groupedCards.any { it.value.size == 3 }) { val advancedGroupedCards = sevenCards.groupingBy({ it.face }).eachCount() // triple and pair var fhTriple = -1 var fhPair = -1 advancedGroupedCards.forEach { if (it.value == 3) { fhTriple = it.key } else if (it.value == 2) { fhPair = it.key } } return (7 shl 20) + (fhTriple shl 16) + (fhPair shl 12) } // 2 2 2 1 else { type = 3 if (first != second) { // 1 2 2 2 twoPairTopPair = second twoPairBottomPair = fourth twoPairKicker = first } else if (sixth != seventh) { // 2 2 2 1 twoPairTopPair = first twoPairBottomPair = third twoPairKicker = fifth } else if (fourth != fifth) { // 2 2 1 2 twoPairTopPair = first twoPairBottomPair = third twoPairKicker = fifth } else { // 2 1 2 2 twoPairTopPair = first twoPairBottomPair = fourth twoPairKicker = third } } } 5 -> { // 3 1 1 1 1 if (groupedCards.any { it.value.size == 3 }) { type = 4 if (first == second) { // 3 1 1 1 1 triple = first tripleKicker = fourth tripleKicker2 = fifth } else if (second == third) { // 1 3 1 1 1 triple = second tripleKicker = first tripleKicker2 = fifth } else if (third == fourth) { // 1 1 3 1 1 triple = third tripleKicker = first tripleKicker2 = second } else if (fourth == fifth) { // 1 1 1 3 1 triple = fourth tripleKicker = first tripleKicker2 = second } else { // 1 1 1 1 3 triple = fifth tripleKicker = first tripleKicker2 = second } } // 2 2 1 1 1 else { type = 3 if (first == second) { twoPairTopPair = first if (third == fourth) { // 2 2 1 1 1 twoPairBottomPair = third twoPairKicker = fifth } else if (fourth == fifth) { // 2 1 2 1 1 twoPairBottomPair = fourth twoPairKicker = third } else if (fifth == sixth) { // 2 1 1 2 1 twoPairBottomPair = fifth twoPairKicker = third } else { // 2 1 1 1 2 twoPairBottomPair = sixth twoPairKicker = third } } else { twoPairKicker = first if (second == third) { twoPairTopPair = second if (fourth == fifth) { // 1 2 2 1 1 twoPairBottomPair = fourth } else if (fifth == sixth) { // 1 2 1 2 1 twoPairBottomPair = fifth } else { // 1 2 1 1 2 twoPairBottomPair = sixth } } else if (third == fourth) { twoPairTopPair = third if (fifth == sixth) { // 1 1 2 2 1 twoPairBottomPair = fifth } else { // 1 1 2 1 2 twoPairBottomPair = sixth } } else { // 1 1 1 2 2 twoPairTopPair = fourth twoPairBottomPair = sixth } } } } 6 -> { type = 2 if (first == second) { // 2 1 1 1 1 1 pair = first pairKicker = third pairKicker2 = fourth pairKicker3 = fifth } else if (second == third) { // 1 2 1 1 1 1 pair = second pairKicker = first pairKicker2 = fourth pairKicker3 = fifth } else if (third == fourth) { // 1 1 2 1 1 1 pair = third pairKicker = first pairKicker2 = second pairKicker3 = fifth } else if (fourth == fifth) { // 1 1 1 2 1 1 pair = fourth pairKicker = first pairKicker2 = second pairKicker3 = third } else if (fifth == sixth) { // 1 1 1 1 2 1 pair = fifth pairKicker = first pairKicker2 = second pairKicker3 = third } else { // 1 1 1 1 1 2 pair = sixth pairKicker = first pairKicker2 = second pairKicker3 = third } } else -> { type = 1 } } sevenCards.forEach { // fill suits - technically don't need to iterate all 7 val suit = it.suit if (suit == 'S') { spadesCount++ } else if (suit == 'H') { heartsCount++ } else if (suit == 'C') { clubsCount++ } else if (suit == 'D') { diamondsCount++ } } // is flush val flushSuit = when { spadesCount >= 5 -> 'S' heartsCount >= 5 -> 'H' clubsCount >= 5 -> 'C' diamondsCount >= 5 -> 'D' else -> 'N' } // look for straight val distinctCards = sortedCards.distinctBy { it.face } if (distinctCards.size == 5) { if (distinctCards.get(0).face == distinctCards.get(4).face + 4) { // straight type = 5 straightHigh = distinctCards.get(0).face if (findStraightFlush(flushSuit, straightHigh, groupedCards)) { return (9 shl 20) + (straightHigh shl 16) } } if ((distinctCards.get(1).face == 3) and (distinctCards.get(4).face == 0) and (distinctCards.get(0).face == 12)) { // 5-high straight type = 5 if (straightHigh < 3) { straightHigh = 3 } if (findFiveHighStraightFlush(flushSuit, groupedCards)) { return (9 shl 20) + (3 shl 16) } } } else if (distinctCards.size == 6) { if (distinctCards.get(0).face == distinctCards.get(4).face + 4) { // straight type = 5 straightHigh = distinctCards.get(0).face if (findStraightFlush(flushSuit, straightHigh, groupedCards)) { return (9 shl 20) + (straightHigh shl 16) } } if (distinctCards.get(1).face == distinctCards.get(5).face + 4) { type = 5 if (straightHigh < distinctCards.get(1).face) { straightHigh = distinctCards.get(1).face } if (findStraightFlush(flushSuit, distinctCards.get(1).face, groupedCards)) { return (9 shl 20) + (distinctCards.get(1).face shl 16) } } if ((distinctCards.get(2).face == 3) and (distinctCards.get(5).face == 0) and (distinctCards.get(0).face == 12)) { // 5-high straight type = 5 if (straightHigh < 3) { straightHigh = 3 } if (findFiveHighStraightFlush(flushSuit, groupedCards)) { return (9 shl 20) + (3 shl 16) } } } else if (distinctCards.size == 7) { // size 7 - all different digits if (distinctCards.get(0).face == distinctCards.get(4).face + 4) { type = 5 straightHigh = distinctCards.get(0).face if (findStraightFlush(flushSuit, straightHigh, groupedCards)) { return (9 shl 20) + (straightHigh shl 16) } } if (distinctCards.get(1).face == distinctCards.get(5).face + 4) { type = 5 if (straightHigh < distinctCards.get(1).face) { straightHigh = distinctCards.get(1).face } if (findStraightFlush(flushSuit, distinctCards.get(1).face, groupedCards)) { return (9 shl 20) + (distinctCards.get(1).face shl 16) } } if (distinctCards.get(2).face == distinctCards.get(6).face + 4) { type = 5 if (straightHigh < distinctCards.get(2).face) { straightHigh = distinctCards.get(2).face } if (findStraightFlush(flushSuit, distinctCards.get(2).face, groupedCards)) { return (9 shl 20) + (distinctCards.get(2).face shl 16) } } if ((distinctCards.get(3).face == 3) and (distinctCards.get(6).face == 0) and (distinctCards.get(0).face == 12)) { // 5-high straight type = 5 if (straightHigh < 3) { straightHigh = 3 } if (findFiveHighStraightFlush(flushSuit, groupedCards)) { return (9 shl 20) + (3 shl 16) } } } // SF, Q, and FH have returned // return flush if (flushSuit != 'N') { // get five highest of suit val sortedFlush = sortedCards.filter { it.suit == flushSuit } return (6 shl 20) + (sortedFlush.get(0).face shl 16) + (sortedFlush.get(1).face shl 12) + (sortedFlush.get(2).face shl 8) + (sortedFlush.get(3).face shl 4) + (sortedFlush.get(4).face) } // return straight if (type == 5) { return (5 shl 20) + (straightHigh shl 16) } // return triple if (type == 4) { return (4 shl 20) + (triple shl 16) + (tripleKicker shl 12) + (tripleKicker2 shl 8) } // two pair if (type == 3) { return (3 shl 20) + (twoPairTopPair shl 16) + (twoPairBottomPair shl 12) + (twoPairKicker shl 8) } // pair if (type == 2) { return (2 shl 20) + (pair shl 16) + (pairKicker shl 12) + (pairKicker2 shl 8) + (pairKicker3 shl 4) } if (type == 1) { return (1 shl 20) + (first shl 16) + (second shl 12) + (third shl 8) + (fourth shl 4) + fifth } throw Exception("Impossible type") } fun findStraightFlush(flushSuit: Char, straightHigh: Int, groupedCards: Map<Int, List<Card>>): Boolean { if (flushSuit != 'N') { // check series of 5 for flush var isStraightFlush = true for (i in straightHigh.downTo(straightHigh - 4)) { var suitFoundInCurrent = false for (j in groupedCards.getValue(i)) { if (j.suit == flushSuit) { suitFoundInCurrent = true break } } if (!suitFoundInCurrent) { isStraightFlush = false } } if (isStraightFlush) { return true } } return false } fun findFiveHighStraightFlush(flushSuit: Char, groupedCards: Map<Int, List<Card>>): Boolean { if (flushSuit != 'N') { var isStraightFlush = true for (i in 0..3) { var suitFoundInCurrent = false for (j in groupedCards.getValue(i)) { if (j.suit == flushSuit) { suitFoundInCurrent = true break } } if (!suitFoundInCurrent) { isStraightFlush = false } } var aceSuitCorrect = false for (i in groupedCards.getValue(12)) { if (i.suit == flushSuit) { aceSuitCorrect = true } } if (isStraightFlush and aceSuitCorrect) { return true } } return false } }
src/main/kotlin/pokur/calculate/HandProcessor.kt
1021494283
package com.epimorphics.android.myrivers.models import android.util.JsonReader import com.epimorphics.android.myrivers.data.CDEPoint import com.epimorphics.android.myrivers.data.Classification import com.epimorphics.android.myrivers.helpers.InputStreamHelper import java.io.IOException import java.io.InputStream import java.io.InputStreamReader /** * Consumes an InputStream and converts it to Classification * * @see Classification */ class InputStreamToCDEClassification : InputStreamHelper() { /** * Converts InputStream to JsonReader and consumes it. * * @param cdePoint CDEPoint to which parsed Classification belongs * @param inputStream InputStream to be consumed * @param group a name of the group of the Classifications * * @throws IOException */ @Throws(IOException::class) fun readJsonStream(cdePoint: CDEPoint, inputStream: InputStream, group: String) { val reader = JsonReader(InputStreamReader(inputStream, "UTF-8")) reader.isLenient = true reader.use { readMessagesArray(cdePoint, reader, group) } } /** * Focuses on the array of objects that are to be converted to Classifications and parses * them one by one. * * @param cdePoint CDEPoint to which parsed Classification belongs * @param reader JsonReader to be consumed * @param group a name of the group of the Classifications * * @throws IOException */ @Throws(IOException::class) fun readMessagesArray(cdePoint: CDEPoint, reader: JsonReader, group: String) { reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "items") { reader.beginArray() while (reader.hasNext()) { readMessage(cdePoint, reader, group) } reader.endArray() } else { reader.skipValue() } } reader.endObject() } /** * Converts single JsonObject to Classification and adds it to the given CDEPoint's * classificationHashMap for a given group. * * @param cdePoint CDEPoint to which parsed Classification belongs * @param reader JsonReader to be consumed * @param group a name of the group of the Classifications * * @throws IOException */ @Throws(IOException::class) fun readMessage(cdePoint: CDEPoint, reader: JsonReader, group: String) { var item = "" var certainty = "" var value = "" var year = "" reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() when (name) { "classificationCertainty" -> certainty = readItemToString(reader) "classificationItem" -> item = readItemToString(reader) "classificationValue" -> value = readItemToString(reader) "classificationYear" -> year = reader.nextString() else -> reader.skipValue() } } reader.endObject() if (certainty == "No Information") { certainty = "No Info" } if (!cdePoint.getClassificationHashMap(group).containsKey(item)) { cdePoint.getClassificationHashMap(group).put(item, Classification(value, certainty, year)) } } }
android/app/src/main/java/com/epimorphics/android/myrivers/models/InputStreamToCDEClassification.kt
3293045449
package mil.nga.giat.mage.network.gson import android.util.Log import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import mil.nga.giat.mage.sdk.datastore.location.Location import mil.nga.giat.mage.sdk.datastore.location.LocationProperty import mil.nga.giat.mage.sdk.utils.ISO8601DateFormatFactory import java.io.IOException import java.io.Serializable import java.text.ParseException class LocationsTypeAdapter: TypeAdapter<List<Location>>() { private val geometryDeserializer = GeometryTypeAdapter() override fun write(out: JsonWriter, value: List<Location>) { throw UnsupportedOperationException() } override fun read(reader: JsonReader): List<Location> { val locations = mutableListOf<Location>() if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue() return locations } reader.beginArray() while (reader.hasNext()) { locations.addAll(readUserLocations(reader)) } reader.endArray() return locations } @Throws(IOException::class) private fun readUserLocations(reader: JsonReader): List<Location> { val locations = mutableListOf<Location>() if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return locations } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "locations" -> locations.addAll(readLocations(reader)) else -> reader.skipValue() } } reader.endObject() return locations } @Throws(IOException::class) private fun readLocations(reader: JsonReader): List<Location> { val locations = mutableListOf<Location>() if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue() return locations } reader.beginArray() while(reader.hasNext()) { locations.add(readLocation(reader)) } reader.endArray() return locations } @Throws(IOException::class) private fun readLocation(reader: JsonReader): Location { val location = Location() if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return location } reader.beginObject() var userId: String? = null var properties = mutableListOf<LocationProperty>() while(reader.hasNext()) { when(reader.nextName()) { "_id" -> location.remoteId = reader.nextString() "type" -> location.type = reader.nextString() "geometry" -> location.geometry = geometryDeserializer.read(reader) "properties" -> properties = readProperties(reader, location) "userId" -> userId = reader.nextString() else -> reader.skipValue() } } // don't set the user at this time, only the id. Set it later. properties.add(LocationProperty("userId", userId)) location.properties = properties val propertiesMap = location.propertiesMap // timestamp is special pull it out of properties and set it at the top level propertiesMap["timestamp"]?.value?.toString()?.let { try { location.timestamp = ISO8601DateFormatFactory.ISO8601().parse(it) } catch (e: ParseException) { Log.w(LOG_NAME, "Unable to parse date: " + it + " for location: " + location.remoteId, e) } } reader.endObject() return location } @Throws(IOException::class) private fun readProperties(reader: JsonReader, location: Location): MutableList<LocationProperty> { val properties = mutableListOf<LocationProperty>() if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return properties } reader.beginObject() while(reader.hasNext()) { val key = reader.nextName() if (reader.peek() == JsonToken.BEGIN_OBJECT || reader.peek() == JsonToken.BEGIN_ARRAY) { reader.skipValue() } else { val value: Serializable? = when(reader.peek()) { JsonToken.NUMBER -> reader.nextNumberOrNull() JsonToken.BOOLEAN -> reader.nextBooleanOrNull() else -> reader.nextStringOrNull() } if (value != null) { val property = LocationProperty(key, value) property.location = location properties.add(property) } } } reader.endObject() return properties } companion object { private val LOG_NAME = LocationsTypeAdapter::class.java.name } }
mage/src/main/java/mil/nga/giat/mage/network/gson/LocationsTypeAdapter.kt
3946422255
package com.ruuvi.station.network.data data class NetworkTokenInfo ( val email: String, val token: String )
app/src/main/java/com/ruuvi/station/network/data/NetworkTokenInfo.kt
1480755046
package org.fdroid.database import androidx.core.os.LocaleListCompat import androidx.test.ext.junit.runners.AndroidJUnit4 import org.fdroid.database.TestUtils.getOrFail import org.fdroid.database.TestUtils.toMetadataV2 import org.fdroid.test.TestRepoUtils.getRandomRepo import org.fdroid.test.TestUtils.sort import org.fdroid.test.TestVersionUtils.getRandomPackageVersionV2 import org.junit.Test import org.junit.runner.RunWith import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlin.test.fail @RunWith(AndroidJUnit4::class) internal class AppDaoTest : AppTest() { @Test fun insertGetDeleteSingleApp() { val repoId = repoDao.insertOrReplace(getRandomRepo()) appDao.insert(repoId, packageName, app1) assertEquals(app1, appDao.getApp(repoId, packageName)?.toMetadataV2()?.sort()) assertEquals(app1, appDao.getApp(packageName).getOrFail()?.toMetadataV2()?.sort()) appDao.deleteAppMetadata(repoId, packageName) assertEquals(0, appDao.countApps()) assertEquals(0, appDao.countLocalizedFiles()) assertEquals(0, appDao.countLocalizedFileLists()) } @Test fun testGetSameAppFromTwoRepos() { // insert same app into three repos (repoId1 has highest weight) val repoId2 = repoDao.insertOrReplace(getRandomRepo()) val repoId3 = repoDao.insertOrReplace(getRandomRepo()) val repoId1 = repoDao.insertOrReplace(getRandomRepo()) appDao.insert(repoId1, packageName, app1, locales) appDao.insert(repoId2, packageName, app2, locales) appDao.insert(repoId3, packageName, app3, locales) // ensure expected repo weights val repoPrefs1 = repoDao.getRepositoryPreferences(repoId1) ?: fail() val repoPrefs2 = repoDao.getRepositoryPreferences(repoId2) ?: fail() val repoPrefs3 = repoDao.getRepositoryPreferences(repoId3) ?: fail() assertTrue(repoPrefs2.weight < repoPrefs3.weight) assertTrue(repoPrefs3.weight < repoPrefs1.weight) // each app gets returned as stored from each repo assertEquals(app1, appDao.getApp(repoId1, packageName)?.toMetadataV2()?.sort()) assertEquals(app2, appDao.getApp(repoId2, packageName)?.toMetadataV2()?.sort()) assertEquals(app3, appDao.getApp(repoId3, packageName)?.toMetadataV2()?.sort()) // if repo is not given, app from repo with highest weight is returned assertEquals(app1, appDao.getApp(packageName).getOrFail()?.toMetadataV2()?.sort()) } @Test fun testUpdateCompatibility() { // insert two apps with one version each val repoId = repoDao.insertOrReplace(getRandomRepo()) appDao.insert(repoId, packageName, app1, locales) // without versions, app isn't compatible assertEquals(false, appDao.getApp(repoId, packageName)?.metadata?.isCompatible) appDao.updateCompatibility(repoId) assertEquals(false, appDao.getApp(repoId, packageName)?.metadata?.isCompatible) // still incompatible with incompatible version versionDao.insert(repoId, packageName, "1", getRandomPackageVersionV2(), false) appDao.updateCompatibility(repoId) assertEquals(false, appDao.getApp(repoId, packageName)?.metadata?.isCompatible) // only with at least one compatible version, the app becomes compatible versionDao.insert(repoId, packageName, "2", getRandomPackageVersionV2(), true) appDao.updateCompatibility(repoId) assertEquals(true, appDao.getApp(repoId, packageName)?.metadata?.isCompatible) } @Test fun testAfterLocalesChanged() { // insert app with German and French locales val localesBefore = LocaleListCompat.forLanguageTags("de-DE") val app = app1.copy( name = mapOf("de-DE" to "de-DE", "fr-FR" to "fr-FR"), summary = mapOf("de-DE" to "de-DE", "fr-FR" to "fr-FR"), ) val repoId = repoDao.insertOrReplace(getRandomRepo()) appDao.insert(repoId, packageName, app, localesBefore) // device is set to German, so name and summary come out German val appBefore = appDao.getApp(repoId, packageName) assertEquals("de-DE", appBefore?.name) assertEquals("de-DE", appBefore?.summary) // device gets switched to French val localesAfter = LocaleListCompat.forLanguageTags("fr-FR") db.afterLocalesChanged(localesAfter) // device is set to French now, so name and summary come out French val appAfter = appDao.getApp(repoId, packageName) assertEquals("fr-FR", appAfter?.name) assertEquals("fr-FR", appAfter?.summary) } @Test fun testGetNumberOfAppsInCategory() { val repoId = repoDao.insertOrReplace(getRandomRepo()) // app1 is in A and B appDao.insert(repoId, packageName1, app1, locales) assertEquals(1, appDao.getNumberOfAppsInCategory("A")) assertEquals(1, appDao.getNumberOfAppsInCategory("B")) assertEquals(0, appDao.getNumberOfAppsInCategory("C")) // app2 is in A appDao.insert(repoId, packageName2, app2, locales) assertEquals(2, appDao.getNumberOfAppsInCategory("A")) assertEquals(1, appDao.getNumberOfAppsInCategory("B")) assertEquals(0, appDao.getNumberOfAppsInCategory("C")) // app3 is in A and B appDao.insert(repoId, packageName3, app3, locales) assertEquals(3, appDao.getNumberOfAppsInCategory("A")) assertEquals(2, appDao.getNumberOfAppsInCategory("B")) assertEquals(0, appDao.getNumberOfAppsInCategory("C")) } @Test fun testGetNumberOfAppsInRepository() { val repoId = repoDao.insertOrReplace(getRandomRepo()) assertEquals(0, appDao.getNumberOfAppsInRepository(repoId)) appDao.insert(repoId, packageName1, app1, locales) assertEquals(1, appDao.getNumberOfAppsInRepository(repoId)) appDao.insert(repoId, packageName2, app2, locales) assertEquals(2, appDao.getNumberOfAppsInRepository(repoId)) appDao.insert(repoId, packageName3, app3, locales) assertEquals(3, appDao.getNumberOfAppsInRepository(repoId)) } }
libs/database/src/dbTest/java/org/fdroid/database/AppDaoTest.kt
3796997410
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.Closeable import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.nio.charset.Charset import okhttp3.internal.charset import okhttp3.internal.chooseCharset import okhttp3.internal.commonAsResponseBody import okhttp3.internal.commonByteString import okhttp3.internal.commonBytes import okhttp3.internal.commonClose import okhttp3.internal.commonToResponseBody import okhttp3.internal.readBomAsCharset import okio.Buffer import okio.BufferedSource import okio.ByteString actual abstract class ResponseBody : Closeable { /** Multiple calls to [charStream] must return the same instance. */ private var reader: Reader? = null actual abstract fun contentType(): MediaType? actual abstract fun contentLength(): Long fun byteStream(): InputStream = source().inputStream() actual abstract fun source(): BufferedSource @Throws(IOException::class) actual fun bytes() = commonBytes() @Throws(IOException::class) actual fun byteString() = commonByteString() /** * Returns the response as a character stream. * * If the response starts with a * [Byte Order Mark (BOM)](https://en.wikipedia.org/wiki/Byte_order_mark), it is consumed and * used to determine the charset of the response bytes. * * Otherwise if the response has a `Content-Type` header that specifies a charset, that is used * to determine the charset of the response bytes. * * Otherwise the response bytes are decoded as UTF-8. */ fun charStream(): Reader = reader ?: BomAwareReader(source(), charset()).also { reader = it } @Throws(IOException::class) actual fun string(): String = source().use { source -> source.readString(charset = source.readBomAsCharset(charset())) } private fun charset() = contentType().charset() actual override fun close() = commonClose() internal class BomAwareReader( private val source: BufferedSource, private val charset: Charset ) : Reader() { private var closed: Boolean = false private var delegate: Reader? = null @Throws(IOException::class) override fun read(cbuf: CharArray, off: Int, len: Int): Int { if (closed) throw IOException("Stream closed") val finalDelegate = delegate ?: InputStreamReader( source.inputStream(), source.readBomAsCharset(charset)).also { delegate = it } return finalDelegate.read(cbuf, off, len) } @Throws(IOException::class) override fun close() { closed = true delegate?.close() ?: run { source.close() } } } actual companion object { @JvmStatic @JvmName("create") actual fun String.toResponseBody(contentType: MediaType?): ResponseBody { val (charset, finalContentType) = contentType.chooseCharset() val buffer = Buffer().writeString(this, charset) return buffer.asResponseBody(finalContentType, buffer.size) } @JvmStatic @JvmName("create") actual fun ByteArray.toResponseBody(contentType: MediaType?): ResponseBody = commonToResponseBody(contentType) @JvmStatic @JvmName("create") actual fun ByteString.toResponseBody(contentType: MediaType?): ResponseBody = commonToResponseBody(contentType) @JvmStatic @JvmName("create") actual fun BufferedSource.asResponseBody( contentType: MediaType?, contentLength: Long ): ResponseBody = commonAsResponseBody(contentType, contentLength) @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.toResponseBody(contentType)", imports = ["okhttp3.ResponseBody.Companion.toResponseBody"] ), level = DeprecationLevel.WARNING) fun create(contentType: MediaType?, content: String): ResponseBody = content.toResponseBody(contentType) @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.toResponseBody(contentType)", imports = ["okhttp3.ResponseBody.Companion.toResponseBody"] ), level = DeprecationLevel.WARNING) fun create(contentType: MediaType?, content: ByteArray): ResponseBody = content.toResponseBody(contentType) @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.toResponseBody(contentType)", imports = ["okhttp3.ResponseBody.Companion.toResponseBody"] ), level = DeprecationLevel.WARNING) fun create(contentType: MediaType?, content: ByteString): ResponseBody = content.toResponseBody(contentType) @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.asResponseBody(contentType, contentLength)", imports = ["okhttp3.ResponseBody.Companion.asResponseBody"] ), level = DeprecationLevel.WARNING) fun create( contentType: MediaType?, contentLength: Long, content: BufferedSource ): ResponseBody = content.asResponseBody(contentType, contentLength) } }
okhttp/src/jvmMain/kotlin/okhttp3/ResponseBody.kt
3019068501
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.settings import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import jp.toastkid.lib.preference.PreferenceApplier /** * @author toastkidjp */ data class Theme( @ColorInt val backgroundColor: Int, @ColorInt val fontColor: Int, @ColorInt val editorBackgroundColor: Int, @ColorInt val editorFontColor: Int, @ColorInt val editorCursorColor: Int, @ColorInt val editorHighlightColor: Int, val useDarkMode: Boolean ) { fun apply(preferenceApplier: PreferenceApplier) { preferenceApplier.color = backgroundColor preferenceApplier.fontColor = fontColor preferenceApplier.setEditorBackgroundColor(editorBackgroundColor) preferenceApplier.setEditorFontColor(editorFontColor) preferenceApplier.setEditorCursorColor(editorCursorColor) preferenceApplier.setEditorHighlightColor(editorHighlightColor) preferenceApplier.setUseDarkMode(useDarkMode) } companion object { fun extract(preferenceApplier: PreferenceApplier, substituteCursorColor: Int, substituteHilightColor: Int): Theme { return Theme( preferenceApplier.color, preferenceApplier.fontColor, preferenceApplier.editorBackgroundColor(), preferenceApplier.editorFontColor(), preferenceApplier.editorCursorColor(substituteCursorColor), preferenceApplier.editorHighlightColor(substituteHilightColor), preferenceApplier.useDarkMode() ) } } }
app/src/main/java/jp/toastkid/yobidashi/settings/Theme.kt
3573477963
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.flexbox import com.facebook.litho.Border import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Dimen import com.facebook.litho.Style import com.facebook.litho.StyleItem import com.facebook.litho.StyleItemField import com.facebook.litho.exhaustive import com.facebook.litho.getCommonPropsHolder import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaDirection import com.facebook.yoga.YogaEdge import com.facebook.yoga.YogaPositionType /** Enums for [FlexboxDimenStyleItem]. */ @PublishedApi internal enum class FlexboxDimenField : StyleItemField { FLEX_BASIS, POSITION_ALL, POSITION_START, POSITION_TOP, POSITION_END, POSITION_BOTTOM, POSITION_LEFT, POSITION_RIGHT, POSITION_HORIZONTAL, POSITION_VERTICAL, } /** Enums for [FlexboxFloatStyleItem]. */ @PublishedApi internal enum class FlexboxFloatField : StyleItemField { FLEX, FLEX_GROW, FLEX_SHRINK, FLEX_BASIS_PERCENT, ASPECT_RATIO, } /** Enums for [FlexboxObjectStyleItem]. */ @PublishedApi internal enum class FlexboxObjectField : StyleItemField { ALIGN_SELF, BORDER, LAYOUT_DIRECTION, MARGIN_AUTO, POSITION_TYPE, IS_REFERENCE_BASELINE, USE_HEIGHT_AS_BASELINE, } /** Common style item for all dimen styles. See note on [FlexboxDimenField] about this pattern. */ @PublishedApi internal data class FlexboxDimenStyleItem( override val field: FlexboxDimenField, override val value: Dimen ) : StyleItem<Dimen> { override fun applyToComponent(context: ComponentContext, component: Component) { val commonProps = component.getCommonPropsHolder() val pixelValue = value.toPixels(context.resourceResolver) when (field) { FlexboxDimenField.FLEX_BASIS -> commonProps.flexBasisPx(pixelValue) FlexboxDimenField.POSITION_ALL -> commonProps.positionPx(YogaEdge.ALL, pixelValue) FlexboxDimenField.POSITION_START -> commonProps.positionPx(YogaEdge.START, pixelValue) FlexboxDimenField.POSITION_END -> commonProps.positionPx(YogaEdge.END, pixelValue) FlexboxDimenField.POSITION_TOP -> commonProps.positionPx(YogaEdge.TOP, pixelValue) FlexboxDimenField.POSITION_BOTTOM -> commonProps.positionPx(YogaEdge.BOTTOM, pixelValue) FlexboxDimenField.POSITION_LEFT -> commonProps.positionPx(YogaEdge.LEFT, pixelValue) FlexboxDimenField.POSITION_RIGHT -> commonProps.positionPx(YogaEdge.RIGHT, pixelValue) FlexboxDimenField.POSITION_HORIZONTAL -> commonProps.positionPx(YogaEdge.HORIZONTAL, pixelValue) FlexboxDimenField.POSITION_VERTICAL -> commonProps.positionPx(YogaEdge.VERTICAL, pixelValue) }.exhaustive } } /** Common style item for all float styles. See note on [FlexboxDimenField] about this pattern. */ @PublishedApi internal class FloatStyleItem(override val field: FlexboxFloatField, override val value: Float) : StyleItem<Float> { override fun applyToComponent(context: ComponentContext, component: Component) { val commonProps = component.getCommonPropsHolder() when (field) { FlexboxFloatField.FLEX -> commonProps.flex(value) FlexboxFloatField.FLEX_GROW -> commonProps.flexGrow(value) FlexboxFloatField.FLEX_SHRINK -> commonProps.flexShrink(value) FlexboxFloatField.FLEX_BASIS_PERCENT -> commonProps.flexBasisPercent(value) FlexboxFloatField.ASPECT_RATIO -> commonProps.aspectRatio(value) }.exhaustive } } /** Common style item for all object styles. See note on [FlexboxDimenField] about this pattern. */ @PublishedApi internal class FlexboxObjectStyleItem( override val field: FlexboxObjectField, override val value: Any? ) : StyleItem<Any?> { override fun applyToComponent(context: ComponentContext, component: Component) { val commonProps = component.getCommonPropsHolder() when (field) { FlexboxObjectField.ALIGN_SELF -> value?.let { commonProps.alignSelf(it as YogaAlign) } FlexboxObjectField.BORDER -> commonProps.border(value as Border?) FlexboxObjectField.LAYOUT_DIRECTION -> commonProps.layoutDirection(value as YogaDirection) FlexboxObjectField.POSITION_TYPE -> value?.let { commonProps.positionType(it as YogaPositionType) } FlexboxObjectField.MARGIN_AUTO -> value?.let { commonProps.marginAuto(it as YogaEdge) } FlexboxObjectField.IS_REFERENCE_BASELINE -> value?.let { commonProps.isReferenceBaseline(it as Boolean) } FlexboxObjectField.USE_HEIGHT_AS_BASELINE -> value?.let { commonProps.useHeightAsBaseline(it as Boolean) } }.exhaustive } } /** * Flex allows you to define how this component should take up space within its parent. It's * comprised of the following properties: * * **flex-grow**: This component should take up remaining space in its parent. If multiple children * of the parent have a flex-grow set, the extra space is divided up based on proportions of * flex-grow values, i.e. a child with flex-grow of 2 will get twice as much of the space as its * sibling with flex-grow of 1. * * **flex-shrink**: This component should shrink if necessary. Similar to flex-grow, the value * determines the proportion of space *taken* from each child. Setting a flex-shink of 0 means the * child won't shrink. * * **flex-basis**: Defines the default size of the component before extra space is distributed. If * omitted, the measured size of the content (or the width/height styles) will be used instead. * * **flex-basis-percent**: see **flex-basis**. Defines the default size as a percentage of its * parent's size. Values should be from 0 to 100. * * - See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more documentation on flexbox * properties. * - See https://yogalayout.com/ for a web-based playground for trying out flexbox layouts. * * Defaults: flex-grow = 0, flex-shrink = 1, flex-basis = null, flex-basis-percent = null */ inline fun Style.flex( grow: Float? = null, shrink: Float? = null, basis: Dimen? = null, basisPercent: Float? = null ): Style = this + grow?.let { FloatStyleItem(FlexboxFloatField.FLEX_GROW, it) } + shrink?.let { FloatStyleItem(FlexboxFloatField.FLEX_SHRINK, it) } + basis?.let { FlexboxDimenStyleItem(FlexboxDimenField.FLEX_BASIS, it) } + basisPercent?.let { FloatStyleItem(FlexboxFloatField.FLEX_BASIS_PERCENT, it) } /** * Defines how a child should be aligned with a Row or Column, overriding the parent's align-items * property for this child. * * - See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more documentation on flexbox * properties. * - See https://yogalayout.com/ for a web-based playground for trying out flexbox layouts. */ inline fun Style.alignSelf(align: YogaAlign): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.ALIGN_SELF, align) /** * Defines an aspect ratio for this component, meaning the ratio of width to height. This means if * aspectRatio is set to 2 and width is calculated to be 50px, then height will be 100px. * * Note: This property is not part of the flexbox standard. */ inline fun Style.aspectRatio(aspectRatio: Float): Style = this + FloatStyleItem(FlexboxFloatField.ASPECT_RATIO, aspectRatio) /** * Used in conjunction with [positionType] to define how a component should be positioned in its * parent. * * For positionType of ABSOLUTE: the values specified here will define how inset the child is from * the same edge on its parent. E.g. for `position(0.px, 0.px, 0.px, 0.px)`, it will be the full * size of the parent (no insets). For `position(0.px, 10.px, 0.px, 10.px)`, the child will be the * full width of the parent, but inset by 10px on the top and bottom. * * For positionType of RELATIVE: the values specified here will define how the child is positioned * relative to where that edge would have normally been positioned. * * See https://yogalayout.com/ for a web-based playground for trying out flexbox layouts. */ inline fun Style.position( all: Dimen? = null, start: Dimen? = null, top: Dimen? = null, end: Dimen? = null, bottom: Dimen? = null, left: Dimen? = null, right: Dimen? = null, vertical: Dimen? = null, horizontal: Dimen? = null ): Style = this + all?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_ALL, it) } + start?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_START, it) } + top?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_TOP, it) } + end?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_END, it) } + bottom?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_BOTTOM, it) } + left?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_LEFT, it) } + right?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_RIGHT, it) } + vertical?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_VERTICAL, it) } + horizontal?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_HORIZONTAL, it) } /** See docs in [position]. */ inline fun Style.positionType(positionType: YogaPositionType): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.POSITION_TYPE, positionType) /** * Describes how a [Border] should be drawn around this component. Setting this property will cause * the Component to be represented as a View at mount time if it wasn't going to already. */ inline fun Style.border(border: Border): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.BORDER, border) /** * Describes the RTL/LTR direction of component. Determines whether {@link YogaEdge#START} and * {@link YogaEdge#END} will resolve to the left or right side, among other things. INHERIT * indicates this setting will be inherited from this component's parent. Setting this property will * cause the Component to be represented as a View at mount time if it wasn't going to already. * * <p>Default: {@link YogaDirection#INHERIT} */ inline fun Style.layoutDirection(layoutDirection: YogaDirection): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.LAYOUT_DIRECTION, layoutDirection) /** * Sets margin value for specified edge to auto. The item will extend the margin for this edge to * occupy the extra space in the parent, depending on the direction (Row or Column). */ inline fun Style.marginAuto(edge: YogaEdge): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.MARGIN_AUTO, edge) inline fun Style.isReferenceBaseline(isReferenceBaseline: Boolean): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.IS_REFERENCE_BASELINE, isReferenceBaseline) inline fun Style.useHeightAsBaseline(useHeightAsBaseline: Boolean): Style = this + FlexboxObjectStyleItem(FlexboxObjectField.USE_HEIGHT_AS_BASELINE, useHeightAsBaseline)
litho-core-kotlin/src/main/kotlin/com/facebook/litho/flexbox/FlexboxStyle.kt
2212507392
/* * Copyright 2017 vinayagasundar * Copyright 2017 randhirgupta * * 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 you.devknights.minimalweather.database.entity import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import you.devknights.minimalweather.database.WeatherDatabase /** * @author Randhir * @since 6/6/2017. */ @Entity(tableName = WeatherDatabase.TABLE_WEATHER) class WeatherEntity { @PrimaryKey(autoGenerate = true) var _id: Long = 0 /////////////////////////////////////////////////////////////////////////// // Place information /////////////////////////////////////////////////////////////////////////// var placeId: Int = 0 var placeName: String? = null var placeLat: Double = 0.toDouble() var placeLon: Double = 0.toDouble() /////////////////////////////////////////////////////////////////////////// // Weather Information /////////////////////////////////////////////////////////////////////////// var weatherId: Int = 0 var weatherMain: String? = null var weatherDescription: String? = null var weatherIcon: String? = null /////////////////////////////////////////////////////////////////////////// // Temperature, wind , pressure information /////////////////////////////////////////////////////////////////////////// var temperature: Float = 0.toFloat() var pressure: Float = 0.toFloat() var humidity: Float = 0.toFloat() var windSpeed: Float = 0.toFloat() /////////////////////////////////////////////////////////////////////////// // Sunrise and sunset timing information /////////////////////////////////////////////////////////////////////////// var sunriseTime: Long = 0 var sunsetTime: Long = 0 var startTime: Long = 0 var endTime: Long = 0 }
app/src/main/java/you/devknights/minimalweather/database/entity/WeatherEntity.kt
1332384565
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.java.lifecycle import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.Button import android.widget.LinearLayout import androidx.fragment.app.Fragment import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.LithoLifecycleProvider import com.facebook.litho.LithoLifecycleProviderDelegate import com.facebook.litho.LithoView import com.facebook.samples.litho.R import java.util.concurrent.atomic.AtomicInteger class LifecycleFragment : Fragment(), View.OnClickListener { private var lithoView: LithoView? = null private var consoleView: ConsoleView? = null private val consoleDelegateListener = ConsoleDelegateListener() private val delegateListener: DelegateListener = object : DelegateListener { override fun onDelegateMethodCalled( type: Int, thread: Thread, timestamp: Long, id: String ) { val prefix = LifecycleDelegateLog.prefix(thread, timestamp, id) val logRunnable = ConsoleView.LogRunnable(consoleView, prefix, LifecycleDelegateLog.log(type)) consoleView?.post(logRunnable) } override fun setRootComponent(isSync: Boolean) = Unit } // start_example_lifecycleprovider private val delegate: LithoLifecycleProviderDelegate = LithoLifecycleProviderDelegate() override fun onClick(view: View) { // Replaces the current fragment with a new fragment replaceFragment() // inform the LithoView delegate.moveToLifecycle(LithoLifecycleProvider.LithoLifecycle.HINT_VISIBLE) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val parent = inflater.inflate(R.layout.activity_fragment_transactions_lifecycle, container, false) as ViewGroup val c = ComponentContext(requireContext()) lithoView = LithoView.create( c, getComponent(c), delegate /* The LithoLifecycleProvider delegate for this LithoView */) // end_example_lifecycleprovider val layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT) layoutParams.weight = 1f lithoView?.layoutParams = layoutParams consoleView = ConsoleView(requireContext()) consoleView?.layoutParams = layoutParams parent.addView(consoleView) return parent } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val fragmentButton = view.findViewById<Button>(R.id.new_fragment_button) fragmentButton.text = "New Fragment" fragmentButton.setOnClickListener(this) val fragmentLithoView = view.findViewById<ViewGroup>(R.id.fragment_litho_view) fragmentLithoView.addView(lithoView) } private fun getComponent(c: ComponentContext): Component = Column.create(c) .child( LifecycleDelegateComponent.create(c) .id(atomicId.getAndIncrement().toString()) .delegateListener(delegateListener) .consoleDelegateListener(consoleDelegateListener) .build()) .build() private fun replaceFragment() { parentFragmentManager .beginTransaction() .replace(R.id.fragment_view, LifecycleFragment(), null) .addToBackStack(null) .commit() } companion object { private val atomicId = AtomicInteger(0) } }
sample/src/main/java/com/facebook/samples/litho/java/lifecycle/LifecycleFragment.kt
2011732518
package web import integration.BackgroundTasks import integration.OAuth import photos.AlbumPart import photos.Cache import photos.Picasa import java.util.* import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY import javax.servlet.http.HttpServletResponse.SC_NOT_FOUND class RequestRouter( val req: HttpServletRequest, val res: HttpServletResponse, val chain: FilterChain, val render: Renderer, var requestedUser: String? = req["by"], val auth: OAuth = requestedUser?.let { OAuth.auths[it] } ?: OAuth.default, val picasa: Picasa = Picasa.of(auth) ) { val userAgent: String = req.getHeader("User-Agent") ?: "" val path = req.servletPath val pathParts = path.substring(1).split("/") val random = req["random"] val bot = isBot(userAgent) || req["bot"] != null val reqProps = RequestProps(picasa.urlPrefix, picasa.urlSuffix, req.getHeader("host"), bot, detectMobile()) fun invoke() { try { if (req["clear"] != null) Cache.clear() if (req["reload"] != null) Cache.reload() when { "/poll" == path || "/_ah/start" == path -> BackgroundTasks.run().also { res.writer.use { it.write("OK") } } "/oauth" == path -> handleOAuth() auth.refreshToken == null -> throw Redirect("/oauth") random != null -> renderRandom() (path == null || "/" == path) && requestedUser == null -> throw Redirect(picasa.urlPrefix) picasa.urlPrefix == path || "/" == path -> renderGallery() pathParts.size == 1 && path.endsWith(".jpg") -> renderAlbumThumb(pathParts.last().substringBefore(".jpg")) path.isResource() -> chain.doFilter(req, res) // pathParts.size == 1 -> throw Redirect(picasa.urlPrefix + path) pathParts.size == 2 -> renderPhotoPage(pathParts[0], pathParts[1]) else -> renderAlbum(pathParts.last()) } } catch (e: Redirect) { res.status = SC_MOVED_PERMANENTLY res.setHeader("Location", e.path) } catch (e: MissingResourceException) { res.sendError(SC_NOT_FOUND, e.message) } } private fun String.isResource() = lastIndexOf('.') >= length - 5 private fun renderGallery() { render(res, picasa.gallery.loadedAt.time) { views.gallery(reqProps, picasa.gallery, auth.profile!!) } } private fun renderPhotoPage(albumName: String, photoIdxOrId: String) { val album = picasa.gallery[albumName] ?: throw Redirect("/") val photo = picasa.findAlbumPhoto(album, photoIdxOrId) ?: throw Redirect(album.url) val redirectUrl = "/$albumName${picasa.urlSuffix}#$photoIdxOrId" render(res) { views.photo(photo, album, auth.profile!!, if (bot) null else redirectUrl) } } private fun renderAlbum(name: String) { val album = picasa.gallery[name] ?: throw Redirect("/") if (album.id == name && album.id != album.name) throw Redirect("${album.url}${picasa.urlSuffix}") val pageToken = req["pageToken"] val part = if (bot) AlbumPart(picasa.getAlbumPhotos(album), null) else picasa.getAlbumPhotos(album, pageToken) if (pageToken == null) render(res, album.timestamp) { views.album(album, part, auth.profile!!, reqProps) } else render(res) { views.albumPart(part, album, reqProps) } } private fun renderAlbumThumb(name: String) { val album = picasa.gallery[name] ?: throw MissingResourceException(path, "", "") val x2 = req["x2"] != null val thumbContent = if (x2) album.thumbContent2x else album.thumbContent if (thumbContent == null) res.sendRedirect(album.baseUrl?.crop(album.thumbSize * (if (x2) 2 else 1))) else { res.contentType = "image/jpeg" res.addIntHeader("Content-Length", thumbContent.size) res.addDateHeader("Last-Modified", album.timestamp!!) res.addHeader("Cache-Control", "public, max-age=" + (14 * 24 * 3600)) res.outputStream.write(thumbContent) } } private fun handleOAuth() { val code = req["code"] ?: throw Redirect(OAuth.startUrl(reqProps.host)) val auth = if (OAuth.default.refreshToken == null) OAuth.default else OAuth(null) val token = auth.token(code) auth.profile?.slug?.let { OAuth.auths[it] = auth if (!auth.isDefault) throw Redirect("/?by=$it") } render(res) { views.oauth(token.refreshToken) } } private fun renderRandom() { if (req.remoteAddr == "82.131.59.12" && isNight()) return render(res) { "<h1>Night mode</h1>" } val numRandom = if (random.isNotEmpty()) random.toInt() else 1 val randomPhotos = picasa.getRandomPhotos(numRandom) render(res) { views.random(randomPhotos, req["delay"], req["refresh"] != null) } } private fun isNight(): Boolean { val utcHours = Date().let { it.hours + it.timezoneOffset / 60 } return utcHours >= 18 || utcHours < 5 } private fun detectMobile() = userAgent.contains("Mobile") && !userAgent.contains("iPad") && !userAgent.contains("Tab") internal fun isBot(userAgent: String) = userAgent.contains("bot/", true) || userAgent.contains("spider/", true) } class Redirect(val path: String): Exception() class RequestProps(val urlPrefix: String, val urlSuffix: String, val host: String, val bot: Boolean, val mobile: Boolean) operator fun HttpServletRequest.get(param: String) = getParameter(param)
src/web/RequestRouter.kt
1307568105
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui.state import com.example.jetnews.data.Result /** * Immutable data class that allows for loading, data, and exception to be managed independently. * * This is useful for screens that want to show the last successful result while loading or a later * refresh has caused an error. */ data class UiState<T>( val loading: Boolean = false, val exception: Exception? = null, val data: T? = null ) { /** * True if this contains an error */ val hasError: Boolean get() = exception != null /** * True if this represents a first load */ val initialLoad: Boolean get() = data == null && loading && !hasError } /** * Copy a UiState<T> based on a Result<T>. * * Result.Success will set all fields * Result.Error will reset loading and exception only */ fun <T> UiState<T>.copyWithResult(value: Result<T>): UiState<T> { return when (value) { is Result.Success -> copy(loading = false, exception = null, data = value.data) is Result.Error -> copy(loading = false, exception = value.exception) } }
koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/state/UiState.kt
650500919
package com.eden.orchid.plugindocs.components import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.Descriptive import com.eden.orchid.api.options.OptionsHolder import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.components.OrchidComponent import io.github.classgraph.ClassGraph import javax.inject.Inject @Description("Show all options for your plugin's classes.", name = "Plugin Documentation") class PluginDocsComponent @Inject constructor( context: OrchidContext ) : OrchidComponent(context, "pluginDocs", 25) { @Option @Description("A list of fully-qualified class names to render options for.") var classNames = emptyArray<String>() @Option @Description("A list of fully-qualified package names. All OptionsHolder classes in these packages will have their " + "options displayed." ) var packageNames = emptyArray<String>() @Option @Description("A fully-qualified class name to render options for.") lateinit var tableClass: String @Option @Description("A fully-qualified class name to render options for.") lateinit var tableHeaderClass: String @Option @Description("A fully-qualified class name to render options for.") lateinit var tableLeaderClass: String @Option @Description("A custom template to use the for tabs tag used internally.") lateinit var tabsTemplate: String fun getClassList(): Set<String> { val classList = emptyList<String>().toMutableSet() if (!EdenUtils.isEmpty(classNames)) { addClassNames(classList) } if (!EdenUtils.isEmpty(packageNames)) { addPackageClasses(classList) } return classList } private fun addClassNames(classList: MutableSet<String>) { classNames.forEach { if (isOptionsHolderClass(it)) { classList.add(it) } } } private fun addPackageClasses(classList: MutableSet<String>) { ClassGraph() .enableClassInfo() .whitelistPackages(*packageNames) .scan() .allStandardClasses .loadClasses() .forEach { matchingClass -> if (isOptionsHolderClass(matchingClass)) { classList.add(matchingClass.name) } } } private fun isOptionsHolderClass(clazz: Class<*>): Boolean { return OptionsHolder::class.java.isAssignableFrom(clazz) } private fun isOptionsHolderClass(clazz: String): Boolean { try { return OptionsHolder::class.java.isAssignableFrom(Class.forName(clazz)) } catch (e: Exception) { e.printStackTrace() } return false } fun getDescriptiveName(o: Any): String { if(o is Class<*>) { return Descriptive.getDescriptiveName(o) } else if(o is String) { try { return Descriptive.getDescriptiveName(Class.forName(o)) } catch (e: Exception) { return o.toString() } } else { return Descriptive.getDescriptiveName(o.javaClass) } } fun getDescription(o: Any): String { if(o is Class<*>) { return Descriptive.getDescription(o) } else if(o is String) { try { return Descriptive.getDescription(Class.forName(o)) } catch (e: Exception) { return o.toString() } } else { return Descriptive.getDescription(o.javaClass) } } fun getDescriptionSummary(o: Any): String { if(o is Class<*>) { return Descriptive.getDescriptionSummary(o) } else if(o is String) { try { return Descriptive.getDescriptionSummary(Class.forName(o)) } catch (e: Exception) { return o.toString() } } else { return Descriptive.getDescriptionSummary(o.javaClass) } } }
plugins/OrchidPluginDocs/src/main/kotlin/com/eden/orchid/plugindocs/components/PluginDocsComponent.kt
1558794836
/* * Copyright 2019 Andrey Tolpeev * * 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.github.vase4kin.teamcityapp.navigation.data import com.github.vase4kin.teamcityapp.navigation.api.NavigationItem import com.github.vase4kin.teamcityapp.navigation.api.Project import org.hamcrest.core.Is.`is` import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.runners.MockitoJUnitRunner import java.util.* @RunWith(MockitoJUnitRunner::class) class NavigationDataModelImplTest { @Mock private lateinit var navigationItem: NavigationItem private lateinit var dataModel: NavigationDataModel @Before fun setUp() { val items = mutableListOf(navigationItem) dataModel = NavigationDataModelImpl(items) } @Test fun testGetName() { `when`(navigationItem.name).thenReturn("name") assertThat(dataModel.getName(0), `is`("name")) } @Test fun testGetDescription() { `when`(navigationItem.description).thenReturn("desc") assertThat(dataModel.getDescription(0), `is`("desc")) } @Test fun testIsProject() { val items = ArrayList<NavigationItem>() items.add(Project()) dataModel = NavigationDataModelImpl(items) assertThat(dataModel.isProject(0), `is`(true)) } @Test fun testGetNavigationItem() { assertThat(dataModel.getNavigationItem(0), `is`(navigationItem)) } @Test fun testGetItemCount() { assertThat(dataModel.itemCount, `is`(1)) } }
app/src/test/java/com/github/vase4kin/teamcityapp/navigation/data/NavigationDataModelImplTest.kt
3644260724
package io.piano.android.showhelper import android.os.Build import android.view.View import android.webkit.WebView import androidx.annotation.UiThread import androidx.fragment.app.FragmentActivity import io.piano.android.composer.model.DisplayMode import io.piano.android.composer.model.events.BaseShowType import timber.log.Timber abstract class BaseShowController<T : BaseShowType, V : BaseJsInterface> constructor( protected val eventData: T, protected val jsInterface: V ) { abstract val url: String abstract val fragmentTag: String abstract val fragmentProvider: () -> BaseShowDialogFragment protected abstract fun WebView.configure() protected open fun processDelay(activity: FragmentActivity, showFunction: () -> Unit) = showFunction() protected open fun checkPrerequisites(callback: (Boolean) -> Unit) = callback(true) @JvmOverloads @Suppress("unused") // Public API. @UiThread fun show( activity: FragmentActivity, inlineWebViewProvider: (FragmentActivity, String) -> WebView? = defaultWebViewProvider ) { checkPrerequisites { canShow -> if (canShow) { when (eventData.displayMode) { DisplayMode.MODAL -> showModal(activity) DisplayMode.INLINE -> showInline(activity, inlineWebViewProvider) else -> Timber.w("Unknown display mode %s", eventData.displayMode) } } else { Timber.w("Showing forbidden due to prerequisites ") } } } @Suppress("unused") // Public API. @UiThread abstract fun close(data: String? = null) private fun showInline( activity: FragmentActivity, webViewProvider: (FragmentActivity, String) -> WebView? ) = eventData.containerSelector .takeUnless { it.isNullOrEmpty() } ?.let { id -> runCatching { val webView = requireNotNull(webViewProvider(activity, id)) { "Can't find WebView with id $id" } webView.configure() processDelay(activity) { webView.loadUrl(url) webView.visibility = View.VISIBLE } }.onFailure { Timber.e(it) }.getOrNull() } private fun showModal( activity: FragmentActivity ) = fragmentProvider().apply { isCancelable = eventData.showCloseButton javascriptInterface = jsInterface processDelay(activity) { show(activity.supportFragmentManager, fragmentTag) } } companion object { fun WebView.executeJavascriptCode(code: String) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) evaluateJavascript(code, null) else loadUrl("javascript:$code") @JvmStatic private val defaultWebViewProvider: (FragmentActivity, String) -> WebView? = { activity, webViewId -> activity.resources .getIdentifier(webViewId, "id", activity.packageName) .takeUnless { it == 0 } ?.let { id -> runCatching { activity.findViewById<WebView>(id) }.onFailure { Timber.e(it) }.getOrNull() } } } }
show-helper/src/main/java/io/piano/android/showhelper/BaseShowController.kt
3525110215
/* * Copyright 2019 Andrey Tolpeev * * 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 teamcityapp.features.manage_accounts.router interface ManageAccountsRouter { fun openHome() fun openCreateNewAccount() fun openLogin() }
features/manage-accounts/src/main/java/teamcityapp/features/manage_accounts/router/ManageAccountsRouter.kt
4005030479
package com.ilaps.androidtest.signin import com.ilaps.androidtest.common.BasePresenter import com.ilaps.androidtest.common.auth.BaseAuthView /** * Created by ricar on 4/7/17. */ interface SignInContract { interface View: BaseAuthView { fun userLoginIncorrect() } interface Presenter: BasePresenter { fun signIn(email:String, pass:String) } }
app/src/main/java/com/ilaps/androidtest/signin/SignInContract.kt
1362335321
package uk.co.ourfriendirony.medianotifier.general import android.database.Cursor import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* object Helper { private val PREFIXES = arrayOf("A ", "The ") private val dateFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.UK) @JvmStatic fun cleanUrl(url: String): String { return try { URLEncoder.encode(url, "UTF-8") } catch (e: UnsupportedEncodingException) { url } } @JvmStatic fun cleanTitle(string: String): String { for (prefix in PREFIXES) { if (string.startsWith(prefix)) { return string.substring(prefix.length) + ", " + prefix.substring( 0, prefix.length - 1 ) } } return string } @JvmStatic fun dateToString(date: Date?): String? { return if (date != null) dateFormat.format(date) else null } @JvmStatic fun stringToDate(date: String?): Date? { return if (date == null) { null } else try { dateFormat.parse(date) } catch (e: Exception) { null } } @JvmStatic fun replaceTokens(original: String, token: String, value: String): String { return replaceTokens(original, arrayOf(token), arrayOf(value)) } @JvmStatic fun replaceTokens(s: String, tokens: Array<String>, values: Array<String>): String { var string = s if (tokens.size == values.size) { for (i in tokens.indices) { string = string.replace(tokens[i], values[i]) } } return string } @JvmStatic fun getNotificationNumber(num: Int): String { return if (num <= 9) num.toString() else "9+" } @JvmStatic fun getColumnValue(cursor: Cursor, field: String?): String { // Log.d("[FIELD]", "$field") val colIndex = cursor.getColumnIndex(field) val value = cursor.getString(colIndex) return value ?: "" } }
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/general/Helper.kt
2949628071
/* * Copyright (c) 2017 Fabio Berta * * 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 ch.berta.fabio.popularmovies.data.dtos import com.google.gson.annotations.SerializedName import java.util.* /** * Represents a movie, queried from TheMovieDB. */ data class Movie( val id: Int, @SerializedName("backdrop_path") val backdrop: String, val overview: String, @SerializedName("release_date") val releaseDate: Date, @SerializedName("poster_path") val poster: String, val title: String, @SerializedName("vote_average") val voteAverage: Double )
app/src/main/java/ch/berta/fabio/popularmovies/data/dtos/Movie.kt
3548315967
package com.neva.javarel.gradle.internal object Behaviors { fun waitFor(duration: Int) { waitFor(duration.toLong()) } fun waitFor(duration: Long) { Thread.sleep(duration) } fun waitUntil(interval: Int, condition: (Timer) -> Boolean) { waitUntil(interval.toLong(), condition) } fun waitUntil(interval: Long, condition: (Timer) -> Boolean) { val timer = Timer() while (condition(timer)) { waitFor(interval) timer.tick() } } class Timer { private var _started = time() private var _ticks = 0L private fun time(): Long { return System.currentTimeMillis() } fun reset() { this._ticks = 0 } fun tick() { this._ticks++ } val started: Long get() = _started val elapsed: Long get() = time() - _started val ticks: Long get() = _ticks } }
tooling/gradle-plugin/src/main/kotlin/com/neva/javarel/gradle/internal/Behaviors.kt
1250595492
package ca.six.tomato.data.entity /** * Created by songzhw on 2016-06-06. */ data class ClockItem(var work : Int, var longBreak : Int, var shortBreak : Int)
app/src/main/java/ca/six/tomato/data/entity/ClockItem.kt
2417966083
package com.openlattice.authorization.aggregators import com.hazelcast.aggregation.Aggregator import com.openlattice.authorization.* import com.openlattice.organizations.PrincipalSet import java.util.Map class PrincipalAggregator(private val principalsMap: MutableMap<AclKey, PrincipalSet> ) : Aggregator<MutableMap.MutableEntry<AceKey, AceValue>, PrincipalAggregator> { override fun accumulate(input: MutableMap.MutableEntry<AceKey, AceValue>) { val key = input.key.aclKey val principal = input.key.principal if (principalsMap.containsKey(key)) { principalsMap[key]!!.add(principal) } else { principalsMap[key] = PrincipalSet(mutableSetOf(principal)) } } override fun combine(aggregator: Aggregator<*, *>) { if (aggregator is PrincipalAggregator) { aggregator.principalsMap.forEach { if (principalsMap.containsKey(it.key)) { principalsMap[it.key]!!.addAll(it.value) } else { principalsMap[it.key] = it.value } } } } override fun aggregate(): PrincipalAggregator { return this } fun getResult(): MutableMap<AclKey, PrincipalSet> { return principalsMap } override fun equals(other: Any?): Boolean { if (other == null) return false if (other !is PrincipalAggregator) return false return principalsMap == other.principalsMap } override fun hashCode(): Int { return principalsMap.hashCode() } override fun toString(): String { return "PrincipalAggregator{principalsMap=$principalsMap}" } }
src/main/kotlin/com/openlattice/authorization/aggregators/PrincipalAggregator.kt
644955042
/* * 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 com.sdibt.korm.core.callbacks import com.sdibt.korm.core.db.DataSourceType import com.sdibt.korm.core.db.KormSqlSession class CallBackExecute(db: KormSqlSession) { val defaultCallBack = DefaultCallBack.instance.getCallBack(db) fun init() { defaultCallBack.execute().reg("sqlProcess") { CallBackCommon().sqlProcess(it) } defaultCallBack.execute().reg("setDataSource") { CallBackCommon().setDataSoure(it) } defaultCallBack.execute().reg("exec") { execCallback(it) } } fun execCallback(scope: Scope): Scope { if (scope.db.Error == null) { val (rowsAffected, generatedKeys) = scope.db.executeUpdate( scope.sqlString, scope.sqlParam, dsName = scope.dsName, dsType = DataSourceType.WRITE ) scope.rowsAffected = rowsAffected scope.generatedKeys = generatedKeys scope.result = rowsAffected } return scope } }
src/main/kotlin/com/sdibt/korm/core/callbacks/CallBackExecute.kt
3247238073
package fr.jcgay.gradle.notifier.extension import java.util.Properties class Pushbullet: NotifierConfiguration { var apikey: String? = null var device: String? = null override fun asProperties(): Properties { val prefix = "notifier.pushbullet" val result = Properties() apikey?.let { result["${prefix}.apikey"] = it } device?.let { result["${prefix}.device"] = it } return result } }
src/main/kotlin/fr/jcgay/gradle/notifier/extension/Pushbullet.kt
461907394
package org.chapper.chapper.presentation.screen.chat interface ChatView { var isForeground: Boolean fun initToolbar() fun showMessages() fun changeMessageList() fun sendMessage() fun showRefresher() fun hideRefresher() fun startRefreshing() fun statusTyping() fun statusConnected() fun statusNearby() fun statusOffline() fun isCoarseLocationPermissionDenied(): Boolean fun requestCoarseLocationPermission() }
app/src/main/java/org/chapper/chapper/presentation/screen/chat/ChatView.kt
2166148791
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.state.training.model /** * 練習結果. */ data class TrainingResult( val score: String, val averageAnswerSecText: String, val canRestart: Boolean )
state/src/main/java/me/rei_m/hyakuninisshu/state/training/model/TrainingResult.kt
2414538015
package com.loloof64.android.basicchessendgamestrainer.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
app/src/main/java/com/loloof64/android/basicchessendgamestrainer/ui/theme/Type.kt
1886399529
package pw.janyo.whatanime.ui.activity.contract import android.content.Context import android.content.Intent import android.os.Build import android.provider.MediaStore import androidx.activity.result.contract.ActivityResultContract class ImagePickResultContract : ActivityResultContract<String, Intent?>() { override fun createIntent(context: Context, input: String): Intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Intent(MediaStore.ACTION_PICK_IMAGES).apply { type = input } } else { Intent(Intent.ACTION_PICK).apply { setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, input) } } override fun parseResult(resultCode: Int, intent: Intent?): Intent? = intent }
app/src/main/java/pw/janyo/whatanime/ui/activity/contract/ImagePickResultContract.kt
221088153
package pw.janyo.whatanime import android.annotation.SuppressLint import android.app.Application import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.Uri import android.provider.Settings import android.util.Log import androidx.browser.customtabs.CustomTabsIntent import com.microsoft.appcenter.AppCenter import com.microsoft.appcenter.analytics.Analytics import com.microsoft.appcenter.crashes.Crashes import org.koin.java.KoinJavaComponent import pw.janyo.whatanime.base.BaseComposeActivity import pw.janyo.whatanime.config.Configure @SuppressLint("StaticFieldLeak") internal lateinit var context: Context //设备id val publicDeviceId: String @SuppressLint("HardwareIds") get() = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) //应用名称 val appName: String get() = context.getString(R.string.app_name) //应用包名 const val packageName: String = BuildConfig.APPLICATION_ID //版本名称 const val appVersionName: String = BuildConfig.VERSION_NAME //版本号 const val appVersionCode: String = BuildConfig.VERSION_CODE.toString() const val appVersionCodeNumber: Long = BuildConfig.VERSION_CODE.toLong() fun BaseComposeActivity.toCustomTabs(url: String) { if (url.isBlank()) { throw IllegalArgumentException("url is blank") } try { val builder = CustomTabsIntent.Builder() val intent = builder.build() intent.launchUrl(this, Uri.parse(url)) } catch (e: Exception) { loadInBrowser(url) } } fun BaseComposeActivity.loadInBrowser(url: String) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } catch (e: ActivityNotFoundException) { R.string.hint_no_browser.toast(true) } } @Suppress("DEPRECATION") fun isOnline(): Boolean { val connectivityManager = KoinJavaComponent.get<ConnectivityManager>(ConnectivityManager::class.java) val networkInfo = connectivityManager.activeNetworkInfo return networkInfo?.isConnected == true } fun registerAppCenter(application: Application) { if (Configure.allowSendCrashReport) { if (BuildConfig.DEBUG) { AppCenter.setLogLevel(Log.VERBOSE) } AppCenter.setUserId(publicDeviceId) AppCenter.start( application, "0d392422-670e-488b-b62b-b33cb2c15c3c", Analytics::class.java, Crashes::class.java ) } } fun trackEvent(event: String, properties: Map<String, String>? = null) { if (AppCenter.isConfigured() && Configure.allowSendCrashReport) { Analytics.trackEvent(event, properties) } } fun trackError(error: Throwable) { if (AppCenter.isConfigured() && Configure.allowSendCrashReport) { Crashes.trackError(error) } }
app/src/main/java/pw/janyo/whatanime/ApplicationExt.kt
3883510777
package test import org.apache.logging.log4j.Level import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.core.LoggerContext import org.apache.logging.log4j.core.appender.FileAppender import org.apache.logging.log4j.core.config.AppenderRef import org.apache.logging.log4j.core.config.LoggerConfig import org.apache.logging.log4j.core.layout.PatternLayout /** * yggdrasil * * Created by Erik Håkansson on 2017-03-26. * Copyright 2017 * */ class TestDelegatedMainClass { companion object { class KBuilder : FileAppender.Builder<KBuilder>() @JvmStatic fun main(args: Array<String>) { val ctx = LogManager.getContext(false) as LoggerContext val config = ctx.configuration val layout = PatternLayout.newBuilder().withConfiguration(config).withPattern( PatternLayout.SIMPLE_CONVERSION_PATTERN) val builder = KBuilder().withFileName(args[0]).withLayout(layout.build()).setConfiguration(config).withName( "TEST") val appender = builder.build() appender.start() config.addAppender(appender) val ref = AppenderRef.createAppenderRef("File", null, null) val refs = arrayOf(ref) val loggerConfig = LoggerConfig.createLogger(false, Level.INFO, TestDelegatedMainClass::class.java.name, "true", refs, null, config, null) loggerConfig.addAppender(appender, null, null) config.addLogger(TestDelegatedMainClass::class.java.name, loggerConfig) ctx.updateLoggers() LogManager.getLogger(TestDelegatedMainClass::class.java.name).info( "${TestDelegatedMainClass::class.java.name} loaded") } } }
yggdrasil-maven-plugin/yggdrasil-maven-plugin-test/src/main/kotlin/test/TestDelegatedMainClass.kt
2517442784
/* * Tinc App, an Android binding and user interface for the tinc mesh VPN daemon * Copyright (C) 2017-2018 Pacien TRAN-GIRARD * * 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 <https://www.gnu.org/licenses/>. */ package org.pacien.tincapp.activities.configure.tools import android.os.Bundle import kotlinx.android.synthetic.main.configure_tools_dialog_encrypt_decrypt_keys.view.* import org.pacien.tincapp.R import org.pacien.tincapp.commands.TincApp /** * @author pacien */ class EncryptDecryptPrivateKeysToolDialogFragment : ConfigurationToolDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?) = makeDialog( R.layout.configure_tools_dialog_encrypt_decrypt_keys, R.string.configure_tools_private_keys_encryption_title, R.string.configure_tools_private_keys_encryption_action ) { dialog -> encryptDecryptPrivateKeys( dialog.enc_dec_net_name.text.toString(), dialog.enc_dec_current_passphrase.text.toString(), dialog.enc_dec_new_passphrase.text.toString() ) } private fun encryptDecryptPrivateKeys(netName: String, currentPassphrase: String, newPassphrase: String) = execAction( R.string.configure_tools_private_keys_encryption_encrypting, validateNetName(netName) .thenCompose { TincApp.setPassphrase(netName, currentPassphrase, newPassphrase) } ) }
app/src/main/java/org/pacien/tincapp/activities/configure/tools/EncryptDecryptPrivateKeysToolDialogFragment.kt
558727156
package io.github.rfonzi.rxaware.bus.events /** * Created by ryan on 9/21/17. */ enum class EventID { TOAST, NAVIGATE_UP, FRAGMENT_TRANSACTION, START_ACTIVITY, POST_TO_CURRENT_ACTIVITY }
rxaware-lib/src/main/java/io/github/rfonzi/rxaware/bus/events/EventID.kt
1376199988
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.ui.widget import android.content.Context import android.util.AttributeSet import android.view.View import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.ui.StyledPlayerView import com.google.android.exoplayer2.video.VideoSize class AutoHeightPlayerView constructor(context: Context, attrs: AttributeSet) : StyledPlayerView(context, attrs), Player.Listener { private var currentPlayer: ExoPlayer? = null override fun setPlayer(player: Player?) { currentPlayer?.removeListener(this) super.setPlayer(player) currentPlayer = player as ExoPlayer? currentPlayer?.addListener(this) } override fun onVideoSizeChanged(size: VideoSize) { requestLayout() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val size = currentPlayer?.videoFormat ?: return super.onMeasure(widthMeasureSpec, heightMeasureSpec) val measuredWidth = View.resolveSize(0, widthMeasureSpec) val measuredHeight = (measuredWidth.toDouble() * size.height / size.width).toInt() val newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.getMode(widthMeasureSpec)) super.onMeasure(widthMeasureSpec, newHeightMeasureSpec) } }
mobile/src/main/java/org/openhab/habdroid/ui/widget/AutoHeightPlayerView.kt
2931029409
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.ui.exposure import org.koin.core.qualifier.named import org.koin.dsl.module import tv.dotstart.beacon.ui.preload.Loader /** * Exposes all components within this module to the injection framework. * * @author [Johannes Donath](mailto:[email protected]) * @date 08/12/2020 */ val exposureModule = module { single { PortExposureProvider() } single<Loader>(named("portExposureLoader")) { PortExposureProvider.Preloader(get()) } }
ui/src/main/kotlin/tv/dotstart/beacon/ui/exposure/ExposureModule.kt
2015603854
package mixit.integration import mixit.talk.model.Talk import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType.APPLICATION_JSON import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBodyList @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class TalkIntegrationTests(@Autowired val client: WebTestClient) { @Test fun `Find Dan North talk`() { client.get().uri("/api/talk/2421").accept(APPLICATION_JSON) .exchange() .expectStatus().is2xxSuccessful .expectBody() .jsonPath("\$.title").isEqualTo("Selling BDD to the Business") .jsonPath("\$.speakerIds").isEqualTo("tastapod") } @Test fun `Find MiXiT 2012 talks`() { client.get().uri("/api/2012/talk").accept(APPLICATION_JSON) .exchange() .expectStatus().is2xxSuccessful .expectBodyList<Talk>() .hasSize(27) } }
src/test/kotlin/mixit/integration/TalkIntegrationTests.kt
306236199
/**************************************************************************************** * Copyright (c) 2021 Akshay Jadhav <[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.dialogs import android.annotation.SuppressLint import android.content.Context import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.setActionButtonEnabled import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.ichi2.anki.CollectionHelper import com.ichi2.anki.CollectionManager.withCol import com.ichi2.anki.R import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.anki.servicelayer.DeckService.deckExists import com.ichi2.annotations.NeedsTest import com.ichi2.libanki.DeckId import com.ichi2.libanki.Decks import com.ichi2.libanki.backend.exception.DeckRenameException import com.ichi2.libanki.getOrCreateFilteredDeck import com.ichi2.utils.displayKeyboard import net.ankiweb.rsdroid.BackendFactory import timber.log.Timber import java.util.function.Consumer // TODO: Use snackbars instead of toasts: https://github.com/ankidroid/Anki-Android/pull/12139#issuecomment-1224963182 @NeedsTest("Ensure a toast is shown on a successful action") class CreateDeckDialog(private val context: Context, private val title: Int, private val deckDialogType: DeckDialogType, private val parentId: Long?) { private var mPreviousDeckName: String? = null private var mOnNewDeckCreated: Consumer<Long>? = null private var mInitialDeckName = "" private var mShownDialog: MaterialDialog? = null enum class DeckDialogType { FILTERED_DECK, DECK, SUB_DECK, RENAME_DECK } private val col get() = CollectionHelper.instance.getCol(context)!! suspend fun showFilteredDeckDialog() { Timber.i("CreateDeckDialog::showFilteredDeckDialog") mInitialDeckName = withCol { if (!BackendFactory.defaultLegacySchema) { newBackend.getOrCreateFilteredDeck(did = 0).name } else { val names = decks.allNames() var n = 1 val namePrefix = context.resources.getString(R.string.filtered_deck_name) + " " while (names.contains(namePrefix + n)) { n++ } namePrefix + n } } showDialog() } /** Used for rename */ var deckName: String get() = mShownDialog!!.getInputField().text.toString() set(deckName) { mPreviousDeckName = deckName mInitialDeckName = deckName } fun showDialog(): MaterialDialog { @SuppressLint("CheckResult") val dialog = MaterialDialog(context).show { title(title) positiveButton(R.string.dialog_ok) { onPositiveButtonClicked() } negativeButton(R.string.dialog_cancel) input(prefill = mInitialDeckName, waitForPositiveButton = false) { dialog, text -> // we need the fully-qualified name for subdecks val fullyQualifiedDeckName = fullyQualifyDeckName(dialogText = text) // if the name is empty, it seems distracting to show an error if (!Decks.isValidDeckName(fullyQualifiedDeckName)) { dialog.setActionButtonEnabled(WhichButton.POSITIVE, false) return@input } if (deckExists(col, fullyQualifiedDeckName!!)) { dialog.setActionButtonEnabled(WhichButton.POSITIVE, false) dialog.getInputField().error = context.getString(R.string.validation_deck_already_exists) return@input } dialog.setActionButtonEnabled(WhichButton.POSITIVE, true) } displayKeyboard(getInputField()) } mShownDialog = dialog return dialog } /** * Returns the fully qualified deck name for the provided input * @param dialogText The user supplied text in the dialog * @return [dialogText], or the deck name containing `::` in case of [DeckDialogType.SUB_DECK] */ private fun fullyQualifyDeckName(dialogText: CharSequence) = when (deckDialogType) { DeckDialogType.DECK, DeckDialogType.FILTERED_DECK, DeckDialogType.RENAME_DECK -> dialogText.toString() DeckDialogType.SUB_DECK -> col.decks.getSubdeckName(parentId!!, dialogText.toString()) } fun closeDialog() { mShownDialog?.dismiss() } fun createSubDeck(did: DeckId, deckName: String?) { val deckNameWithParentName = col.decks.getSubdeckName(did, deckName) createDeck(deckNameWithParentName!!) } fun createDeck(deckName: String) { if (Decks.isValidDeckName(deckName)) { createNewDeck(deckName) // 11668: Display feedback if a deck is created showThemedToast(context, R.string.deck_created, true) } else { Timber.d("CreateDeckDialog::createDeck - Not creating invalid deck name '%s'", deckName) showThemedToast(context, context.getString(R.string.invalid_deck_name), false) } closeDialog() } fun createFilteredDeck(deckName: String): Boolean { try { // create filtered deck Timber.i("CreateDeckDialog::createFilteredDeck...") val newDeckId = col.decks.newDyn(deckName) mOnNewDeckCreated!!.accept(newDeckId) } catch (ex: DeckRenameException) { showThemedToast(context, ex.getLocalizedMessage(context.resources), false) return false } return true } private fun createNewDeck(deckName: String): Boolean { try { // create normal deck or sub deck Timber.i("CreateDeckDialog::createNewDeck") val newDeckId = col.decks.id(deckName) mOnNewDeckCreated!!.accept(newDeckId) } catch (filteredAncestor: DeckRenameException) { Timber.w(filteredAncestor) return false } return true } private fun onPositiveButtonClicked() { if (deckName.isNotEmpty()) { when (deckDialogType) { DeckDialogType.DECK -> { // create deck createDeck(deckName) } DeckDialogType.RENAME_DECK -> { renameDeck(deckName) } DeckDialogType.SUB_DECK -> { // create sub deck createSubDeck(parentId!!, deckName) } DeckDialogType.FILTERED_DECK -> { // create filtered deck createFilteredDeck(deckName) } } } } fun renameDeck(newDeckName: String) { val newName = newDeckName.replace("\"".toRegex(), "") if (!Decks.isValidDeckName(newName)) { Timber.i("CreateDeckDialog::renameDeck not renaming deck to invalid name '%s'", newName) showThemedToast(context, context.getString(R.string.invalid_deck_name), false) } else if (newName != mPreviousDeckName) { try { val decks = col.decks val deckId = decks.id(mPreviousDeckName!!) decks.rename(decks.get(deckId), newName) mOnNewDeckCreated!!.accept(deckId) // 11668: Display feedback if a deck is renamed showThemedToast(context, R.string.deck_renamed, true) } catch (e: DeckRenameException) { Timber.w(e) // We get a localized string from libanki to explain the error showThemedToast(context, e.getLocalizedMessage(context.resources), false) } } } fun setOnNewDeckCreated(c: Consumer<Long>?) { mOnNewDeckCreated = c } }
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/CreateDeckDialog.kt
4197471357
package pl.loziuu.ivms.presentation import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers import org.springframework.test.context.junit4.SpringRunner import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import org.springframework.test.web.servlet.result.MockMvcResultHandlers import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.transaction.annotation.Transactional import org.springframework.web.context.WebApplicationContext @SpringBootTest @Transactional @RunWith(SpringRunner::class) class SecurityTest { @Autowired lateinit var webCtx: WebApplicationContext lateinit var mockMvc: MockMvc @Before fun setup() { mockMvc = MockMvcBuilders.webAppContextSetup(webCtx) .apply<DefaultMockMvcBuilder>(SecurityMockMvcConfigurers.springSecurity()) .build() } @Test fun getLoginPageAsAnonymousShouldBe200() { mockMvc.perform(get("/login")) .andExpect(status().isOk()) } }
ivms/src/test/kotlin/pl/loziuu/ivms/presentation/SecurityTest.kt
417850703
package com.infinum.dbinspector.ui.schema.shared import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import com.infinum.dbinspector.domain.schema.shared.models.SchemaType import com.infinum.dbinspector.ui.schema.tables.TablesFragment import com.infinum.dbinspector.ui.schema.triggers.TriggersFragment import com.infinum.dbinspector.ui.schema.views.ViewsFragment internal class SchemaTypeAdapter( fragmentActivity: FragmentActivity, private val databasePath: String, private val databaseName: String, ) : FragmentStateAdapter(fragmentActivity) { override fun createFragment(position: Int): Fragment = when (SchemaType(position)) { SchemaType.TABLE -> TablesFragment.newInstance(databasePath, databaseName) SchemaType.VIEW -> ViewsFragment.newInstance(databasePath, databaseName) SchemaType.TRIGGER -> TriggersFragment.newInstance(databasePath, databaseName) } override fun getItemCount(): Int = SchemaType.values().size }
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/schema/shared/SchemaTypeAdapter.kt
2192956079
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.test.KtTestCompiler import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class InstanceOfCheckForExceptionSpec : Spek({ val subject by memoized { InstanceOfCheckForException() } val wrapper by memoized( factory = { KtTestCompiler.createEnvironment() }, destructor = { it.dispose() } ) describe("InstanceOfCheckForException rule") { it("has is and as checks") { val code = """ fun x() { try { } catch(e: Exception) { if (e is IllegalArgumentException || (e as IllegalArgumentException) != null) { return } } } """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).hasSize(2) } it("has nested is and as checks") { val code = """ fun x() { try { } catch(e: Exception) { if (1 == 1) { val b = e !is IllegalArgumentException || (e as IllegalArgumentException) != null } } } """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).hasSize(2) } it("has no instance of check") { val code = """ fun x() { try { } catch(e: Exception) { val s = "" if (s is String || (s as String) != null) { val other: Exception? = null val b = other !is IllegalArgumentException || (other as IllegalArgumentException) != null } } } """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } it("has no checks for the subtype of an exception") { val code = """ interface I fun foo() { try { } catch(e: Exception) { if (e is I || (e as I) != null) { } } } """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } } })
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/InstanceOfCheckForExceptionSpec.kt
2575718031
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * 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.nextcloud.client.core import java.util.concurrent.atomic.AtomicBoolean /** * This is a wrapper for a function run in background. * * Runs task function and posts result if task is not cancelled. */ internal class Task<T>( private val postResult: (Runnable) -> Unit, private val taskBody: () -> T, private val onSuccess: OnResultCallback<T>?, private val onError: OnErrorCallback? ) : Runnable, Cancellable { private val cancelled = AtomicBoolean(false) override fun run() { @Suppress("TooGenericExceptionCaught") // this is exactly what we want here try { val result = taskBody.invoke() if (!cancelled.get()) { postResult.invoke(Runnable { onSuccess?.invoke(result) }) } } catch (t: Throwable) { if (!cancelled.get()) { postResult(Runnable { onError?.invoke(t) }) } } } override fun cancel() { cancelled.set(true) } }
src/main/java/com/nextcloud/client/core/Task.kt
2812733514
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.forecast.model.forecast.openweathermap import io.michaelrocks.forecast.model.WeatherType import org.junit.Test import org.junit.Assert.* import org.mockito.Mockito.* import rx.Observable import java.util.Date import java.util.UUID class OpenWeatherMapFetcherTest { @Test fun testGetForecast() { val id = UUID.randomUUID() val cityId = 42 val service = mock(OpenWeatherMapService::class.java).apply { val current = OwmCurrentForecast( Date(1000L), OwmConditions(0f, 50), OwmWeather(800, "Clear", "clear") ) `when`(getCurrentForecast(cityId)).thenReturn(Observable.just(current)) val daily = OwmDailyForecastCollection( OwmCity(cityId, "City", "Country"), listOf(OwmDailyForecast(Date(2L), OwmTemperature(10f, 20f, 30f, 40f))) ) `when`(getDailyForecast(cityId, 1)).thenReturn(Observable.just(daily)) } val fetcher = OpenWeatherMapFetcher(service) val forecast = fetcher .getForecast(id, cityId) .toBlocking() .single() verify(service, times(1)).getCurrentForecast(cityId) verify(service, times(1)).getDailyForecast(cityId, 1) assertEquals(id, forecast.id) assertEquals(Date(1000L), forecast.date) assertEquals(cityId, forecast.city.id) assertEquals("City", forecast.city.name) assertEquals("Country", forecast.city.country) assertEquals(0f, forecast.temperature.current, 0.1f) assertEquals(10f, forecast.temperature.morning, 0.1f) assertEquals(20f, forecast.temperature.day, 0.1f) assertEquals(30f, forecast.temperature.evening, 0.1f) assertEquals(40f, forecast.temperature.night, 0.1f) assertEquals(WeatherType.CLEAR, forecast.weather.type) assertEquals("clear", forecast.weather.description) } }
app/src/test/kotlin/io/michaelrocks/forecast/model/forecast/openweathermap/OpenWeatherMapFetcherTest.kt
1168961020
package com.github.perseacado.feedbackui.slack.client /** * @author Marco Eigletsberger, 24.06.16. */ interface SlackClient { fun postMessage(username: String, text: String, channel: String, url: String); fun uploadFile(filename: String, channel: String, file: ByteArray): String; }
feedback-ui-slack/src/main/java/com/github/perseacado/feedbackui/slack/client/SlackClient.kt
185959570
/* * 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.room.* @Dao interface TimeIntervalDao { @Query("""SELECT * FROM time_intervals WHERE project_id = :projectId AND (start_in_milliseconds >= :startInMilliseconds OR stop_in_milliseconds = 0) ORDER BY stop_in_milliseconds ASC, start_in_milliseconds ASC""") fun findAll(projectId: Long, startInMilliseconds: Long): List<TimeIntervalEntity> @Query("SELECT * FROM time_intervals WHERE _id = :id LIMIT 1") fun find(id: Long): TimeIntervalEntity? @Query("""SELECT * FROM time_intervals WHERE project_id = :projectId AND stop_in_milliseconds = 0""") fun findActiveTime(projectId: Long): TimeIntervalEntity? @Insert fun add(entity: TimeIntervalEntity): Long @Update fun update(entities: List<TimeIntervalEntity>) @Delete fun remove(entities: List<TimeIntervalEntity>) }
app/src/main/java/me/raatiniemi/worker/data/projects/TimeIntervalDao.kt
1158768592
package pyxis.uzuki.live.richutilskt.module.reference import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import java.lang.ref.WeakReference import java.util.* /** * RichUtilsKt * Class: ActivityReference * Created by Pyxis on 2/4/18. * * Description: */ object ActivityReference { private var mTopActivityWeakRef: WeakReference<Activity>? = null private val mActivityList: LinkedList<Activity> = LinkedList() private var mApplicationWeakRef: WeakReference<Application>? = null private val mCallbacks = object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, bundle: Bundle?) { mActivityList.add(activity) setTopActivityWeakRef(activity) } override fun onActivityStarted(activity: Activity) { setTopActivityWeakRef(activity) } override fun onActivityResumed(activity: Activity) { setTopActivityWeakRef(activity) } override fun onActivityDestroyed(activity: Activity) { mActivityList.remove(activity) } override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle?) {} } @JvmStatic fun initialize(application: Application) { mApplicationWeakRef = WeakReference(application) application.registerActivityLifecycleCallbacks(mCallbacks) } @JvmStatic fun getActivtyReference(): Activity? { if (mTopActivityWeakRef != null) { val activity = (mTopActivityWeakRef as WeakReference<Activity>).get() if (activity != null) { return activity } } val size = mActivityList.size return if (size > 0) mActivityList[size - 1] else null } @JvmStatic fun getContext(): Context { return getActivtyReference() ?: mApplicationWeakRef?.get() as Context } @JvmStatic fun getActivityList() = mActivityList private fun setTopActivityWeakRef(activity: Activity) { if (mTopActivityWeakRef == null || activity != (mTopActivityWeakRef as WeakReference<Activity>).get()) { mTopActivityWeakRef = WeakReference(activity) } } }
RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/module/reference/ActivityReference.kt
2073482334
package com.renard.auto_adapter.processor import java.util.* import javax.lang.model.element.AnnotationValue import javax.lang.model.util.SimpleAnnotationValueVisitor7 class IntAnnotationValueVisitor : SimpleAnnotationValueVisitor7<Void, Void>() { internal val ids: MutableList<Int> = ArrayList() override fun visitInt(value: Int, v: Void?): Void? { ids.add(value) return null } override fun visitArray(list: List<AnnotationValue>, v: Void?): Void? { ids.addAll(list.map { it.value as Int }) return null } }
auto-adapter-processor/src/main/java/com/renard/auto_adapter/processor/IntAnnotationValueVisitor.kt
529422837
/* * Copyright (c) 2016. KESTI co, ltd * 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 debop4k.core.kodatimes import org.joda.time.DateTime import org.joda.time.DateTimeZone /** * [DateTime] 의 TimeZone 정보를 제공합니다 * * @author [email protected] */ open class TimestampZoneText(val datetime: DateTime?) { constructor(timestamp: Long, zone: DateTimeZone) : this(DateTime(timestamp, zone)) constructor(timestamp: Long, zoneId: String) : this(DateTime(timestamp, DateTimeZone.forID(zoneId))) val timestamp: Long? get() = datetime?.millis val zoneId: String? get() = datetime?.zone?.id val timetext: String? get() = datetime?.toIsoFormatHMSString() override fun toString(): String { return "TimestampZoneText(timestamp=$timestamp, zoneId=$zoneId, timetext=$timetext)" } }
debop4k-core/src/main/kotlin/debop4k/core/kodatimes/TimestampZoneText.kt
990450592
package me.hyemdooly.sangs.dimigo.app.project.service import android.app.Notification import android.app.Service import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.IBinder import android.support.v4.app.NotificationCompat import io.realm.Realm import me.hyemdooly.sangs.dimigo.app.project.receiver.ScreenOnOffReceiver import me.hyemdooly.sangs.dimigo.app.project.R class STERealtimeService : Service() { lateinit var screenReceiver: ScreenOnOffReceiver override fun onCreate() { Realm.init(applicationContext) registerStatusReceiver() startForeground(33233317, getNotification(this)) } override fun onDestroy() { unregisterStatusReceiver() stopForeground(true) } override fun onBind(p0: Intent?): IBinder? { return null } private fun registerStatusReceiver() { screenReceiver = ScreenOnOffReceiver() val filter = IntentFilter() filter.addAction(Intent.ACTION_SCREEN_ON) filter.addAction(Intent.ACTION_SCREEN_OFF) registerReceiver(screenReceiver, filter) } private fun unregisterStatusReceiver() { if(screenReceiver != null){ unregisterReceiver(screenReceiver) } } private fun getNotification(paramContext: Context): Notification { val smallIcon = R.drawable.ic_eco_energy val notification = NotificationCompat.Builder(paramContext, "SaveEnergy") .setSmallIcon(smallIcon) .setPriority(NotificationCompat.PRIORITY_MIN) .setAutoCancel(true) .setWhen(0) .setContentTitle("휴대폰 사용절약 프로젝트 진행!") .setContentText("휴대폰을 사용하지 않으면 지구가 치유됩니다 :)").build() notification.flags = 16 return notification } }
app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/service/STERealtimeService.kt
912121886
package voice.data.legacy enum class LegacyBookType { COLLECTION_FOLDER, COLLECTION_FILE, SINGLE_FOLDER, SINGLE_FILE, }
data/src/main/kotlin/voice/data/legacy/LegacyBookType.kt
2783338915
package demo.featuretest import act.controller.Controller import act.controller.annotation.TemplateContext import act.controller.annotation.UrlContext import org.osgl.mvc.annotation.GetAction @UrlContext("/kotlin") @TemplateContext("/kotlin") class KotlinDemo : Controller.Util() { @GetAction fun home() { } @GetAction("hello") fun hello() { text("Hello from Kotlin") } } fun main(args: Array<String>) { act.Act.start("Kotlin Demo") }
feature-test/src/main/java/demo/featuretest/KotlinDemo.kt
914513960
package org.graphqlscs.type import org.springframework.stereotype.Component import java.util.* @Component class Text2Txt { fun subject(word1: String, word2: String, word3: String): String { //CONVERT ENGLISH TEXT txt INTO MOBILE TELEPHONE TXT //BY SUBSTITUTING ABBREVIATIONS FOR COMMON WORDS var word1 = word1 var word2 = word2 var word3 = word3 word1 = word1.lowercase(Locale.getDefault()) word2 = word2.lowercase(Locale.getDefault()) word3 = word3.lowercase(Locale.getDefault()) var result = "" if (word1 == "two") { result = "2" } if (word1 == "for" || word1 == "four") { result = "4" } if (word1 == "you") { result = "u" } if (word1 == "and") { result = "n" } if (word1 == "are") { result = "r" } else if (word1 == "see" && word2 == "you") { result = "cu" } else if (word1 == "by" && word2 == "the" && word3 == "way") { result = "btw" } return result } }
jdk_8_maven/cs/graphql/graphql-scs/src/main/kotlin/org/graphqlscs/type/Text2Txt.kt
4098131124
package xyz.b515.schedule.db import android.content.Context import android.database.sqlite.SQLiteDatabase import android.util.Log import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper import com.j256.ormlite.dao.Dao import com.j256.ormlite.support.ConnectionSource import com.j256.ormlite.table.TableUtils import xyz.b515.schedule.entity.Course import xyz.b515.schedule.entity.Spacetime import java.sql.SQLException class DBHelper(context: Context) : OrmLiteSqliteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { val courseDao: Dao<Course, Int> by lazy<Dao<Course, Int>> { getDao(Course::class.java) } val spacetimeDao: Dao<Spacetime, Int> by lazy<Dao<Spacetime, Int>> { getDao(Spacetime::class.java) } override fun onCreate(db: SQLiteDatabase, connectionSource: ConnectionSource) { try { TableUtils.createTable(connectionSource, Course::class.java) TableUtils.createTable(connectionSource, Spacetime::class.java) } catch (e: SQLException) { Log.e(DBHelper::class.java.name, "onCreate", e) throw RuntimeException(e) } } override fun onUpgrade(db: SQLiteDatabase, connectionSource: ConnectionSource, oldVersion: Int, newVersion: Int) { try { TableUtils.dropTable<Course, Any>(connectionSource, Course::class.java, true) TableUtils.dropTable<Spacetime, Any>(connectionSource, Spacetime::class.java, true) onCreate(db, connectionSource) } catch (e: SQLException) { Log.e(DBHelper::class.java.name, "onUpgrade", e) throw RuntimeException(e) } } companion object { private val DATABASE_NAME = "schedule.db" private val DATABASE_VERSION = 2 } }
app/src/main/kotlin/xyz/b515/schedule/db/DBHelper.kt
1640726664
package fr.free.nrw.commons.utils.model enum class ConnectionType(private val text: String) { WIFI_NETWORK("wifi"), CELLULAR_4G("cellular-4g"), CELLULAR_3G("cellular-3g"), CELLULAR("cellular"), NO_INTERNET("no-internet"); override fun toString(): String { return text } }
app/src/main/java/fr/free/nrw/commons/utils/model/ConnectionType.kt
1685549729
package ownDataRepresentation.fileSystem import de.esymetric.jerusalem.ownDataRepresentation.Transition import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.LatLonDir import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedWayCostFile import de.esymetric.jerusalem.routing.RoutingHeuristics.Companion.BLOCKED_WAY_COST import org.junit.jupiter.api.Test import kotlin.test.assertEquals class PartitionedWayCostFileTest { @Test fun testUShortWayCost() { val partitionedWayCostFile = PartitionedWayCostFile("testData", false) val latLonDir = LatLonDir(48.11, 11.48) val id = partitionedWayCostFile.insertWay(latLonDir, 0.0, 1.0, 100.0, 500.0, 999.0, BLOCKED_WAY_COST) val id2 = partitionedWayCostFile.insertWay(latLonDir, 2000.0, 333.0, 100.0, 500.0, 999.0, BLOCKED_WAY_COST) partitionedWayCostFile.close() val partitionedWayCostFile2 = PartitionedWayCostFile("testData", true) val t = Transition() partitionedWayCostFile2.readTransitionCost(latLonDir, id, t) assertEquals(0.0, t.costFoot) assertEquals(1.0, t.costBike) assertEquals(100.0, t.costRacingBike) assertEquals(500.0, t.costMountainBike) assertEquals(999.0, t.costCar) assertEquals(BLOCKED_WAY_COST, t.costCarShortest) partitionedWayCostFile2.readTransitionCost(latLonDir, id2, t) assertEquals(1000.0, t.costFoot) // max assertEquals(333.0, t.costBike) assertEquals(100.0, t.costRacingBike) assertEquals(500.0, t.costMountainBike) assertEquals(999.0, t.costCar) assertEquals(BLOCKED_WAY_COST, t.costCarShortest) partitionedWayCostFile2.close() } }
src/test/java/ownDataRepresentation/fileSystem/PartitionedWayCostFileTest.kt
3850589352
package ademar.study.reddit.plataform.factories import android.content.Intent import javax.inject.Inject class IntentFactory @Inject constructor() { fun makeIntent(): Intent { return Intent() } }
Projects/Reddit/app/src/main/java/ademar/study/reddit/plataform/factories/IntentFactory.kt
4084687535
package six.ca.dagger101.fourth.dagger import dagger.Module import dagger.Provides import six.ca.dagger101.fourth.Cat import six.ca.dagger101.fourth.CatService @Module class CatModule { @Provides fun cat(catService: CatService): Cat { return Cat(catService) } @Provides fun catService() : CatService { return CatService() } }
deprecated/Tools/DaggerPlayground/app/src/main/java/six/ca/dagger101/fourth/dagger/CatModule.kt
1734567764
package org.tasks.tags import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.EditText import androidx.activity.viewModels import androidx.core.widget.addTextChangedListener import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.R import org.tasks.Strings.isNullOrEmpty import org.tasks.billing.Inventory import org.tasks.data.TagData import org.tasks.databinding.ActivityTagPickerBinding import org.tasks.injection.ThemedInjectingAppCompatActivity import org.tasks.themes.ColorProvider import org.tasks.themes.Theme import java.util.* import javax.inject.Inject @AndroidEntryPoint class TagPickerActivity : ThemedInjectingAppCompatActivity() { @Inject lateinit var theme: Theme @Inject lateinit var inventory: Inventory @Inject lateinit var colorProvider: ColorProvider private val viewModel: TagPickerViewModel by viewModels() private var taskIds: ArrayList<Long>? = null private lateinit var editText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent taskIds = intent.getSerializableExtra(EXTRA_TASKS) as ArrayList<Long>? if (savedInstanceState == null) { intent.getParcelableArrayListExtra<TagData>(EXTRA_SELECTED)?.let { viewModel.setSelected( it, intent.getParcelableArrayListExtra(EXTRA_PARTIALLY_SELECTED) ) } } val binding = ActivityTagPickerBinding.inflate(layoutInflater) editText = binding.searchInput.apply { addTextChangedListener( onTextChanged = { text, _, _, _ -> onSearch(text) } ) } setContentView(binding.root) val toolbar = binding.toolbar toolbar.setNavigationIcon(R.drawable.ic_outline_arrow_back_24px) toolbar.setNavigationOnClickListener { onBackPressed() } val themeColor = theme.themeColor themeColor.applyToNavigationBar(this) val recyclerAdapter = TagRecyclerAdapter(this, viewModel, inventory, colorProvider) { tagData, vh -> onToggle(tagData, vh) } val recyclerView = binding.recyclerView recyclerView.adapter = recyclerAdapter (recyclerView.itemAnimator as DefaultItemAnimator?)!!.supportsChangeAnimations = false recyclerView.layoutManager = LinearLayoutManager(this) viewModel.observe(this) { recyclerAdapter.submitList(it) } editText.setText(viewModel.text) } private fun onToggle(tagData: TagData, vh: TagPickerViewHolder) = lifecycleScope.launch { val newTag = tagData.id == null val newState = viewModel.toggle(tagData, vh.isChecked || newTag) vh.updateCheckbox(newState) if (newTag) { clear() } } private fun onSearch(text: CharSequence?) { viewModel.search(text?.toString() ?: "") } override fun onBackPressed() { if (isNullOrEmpty(viewModel.text)) { val data = Intent() data.putExtra(EXTRA_TASKS, taskIds) data.putParcelableArrayListExtra(EXTRA_PARTIALLY_SELECTED, viewModel.getPartiallySelected()) data.putParcelableArrayListExtra(EXTRA_SELECTED, viewModel.getSelected()) setResult(Activity.RESULT_OK, data) finish() } else { clear() } } private fun clear() { editText.setText("") } companion object { const val EXTRA_SELECTED = "extra_tags" const val EXTRA_PARTIALLY_SELECTED = "extra_partial" const val EXTRA_TASKS = "extra_tasks" } }
app/src/main/java/org/tasks/tags/TagPickerActivity.kt
1196311098
package com.decisionkitchen.decisionkitchen import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.drawable.GradientDrawable import android.location.Location import android.os.Bundle import android.support.design.widget.CoordinatorLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.View import android.widget.Button import android.widget.CheckBox import android.widget.LinearLayout import android.widget.TextView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.* import java.util.* data class Question (val title: String, val options: Array<String>); class GameActivity : Activity() { private var mRecyclerView: RecyclerView? = null private var mAdapter: RecyclerView.Adapter<GameAdapter.ViewHolder>? = null private var mLayoutManager: RecyclerView.LayoutManager? = null private var group : Group? = null private var groupRef: DatabaseReference? = null private var question: Int = -1 private var gameId: Int? = null private var user: FirebaseUser? = null private var qOrder: ArrayList<Int> = ArrayList<Int>() private var questions: ArrayList<Question> = arrayListOf( Question("How much do you want to spend?", arrayOf("$", "$$", "$$$", "$$$$")), Question("What kind of food do you want?", arrayOf("Breakfast & Brunch", "Chinese", "Diners", "Fast Food", "Hot Pot", "Italian", "Japanese", "Korean", "Mongolian", "Pizza", "Steakhouses", "Sushi Bars", "American (Traditional)", "Vegetarian")), Question("Delivery of dine-in?", arrayOf("Delivery", "Dine-in")) ) private var location: Location? = null private var responses: ArrayList<ArrayList<Int>> = ArrayList<ArrayList<Int>>(); public fun getContext(): Context { return this } public fun getGameActivity(): GameActivity { return this } fun render() { if (question == questions.size) { val intent: Intent = Intent(applicationContext, FinishedActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) applicationContext.startActivity(intent) } else if (group != null && groupRef != null && qOrder != null && question != -1 && user != null && gameId != null) { val q = questions[question] (findViewById(R.id.question) as TextView).text = q.title var options:List<String> = ArrayList<String>() for (question in q.options) { options += question } mAdapter = GameAdapter(options, responses[question], mRecyclerView, getGameActivity(), q.title) mRecyclerView!!.adapter = mAdapter } } fun nextQuestion() { val game = group!!.games!![gameId!!] question++ if (question < questions.size) render() else { groupRef!!.child("games").child(gameId.toString()).child("responses").child(user!!.uid) .setValue(Response(responses, hashMapOf("latitude" to location!!.latitude, "longitude" to location!!.longitude))) } } public fun nextQuestion(view: View) { nextQuestion() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game) responses = ArrayList<ArrayList<Int>>(questions.size); val database = FirebaseDatabase.getInstance() user = FirebaseAuth.getInstance().currentUser; location = getIntent().extras["LOCATION"] as Location groupRef = database.getReference("groups/" + getIntent().getStringExtra("GROUP_ID")) val groupListener = object : ValueEventListener { override fun onCancelled(p0: DatabaseError?) { } override fun onDataChange(dataSnapshot: DataSnapshot) { group = dataSnapshot.getValue<Group>(Group::class.java)!! if (gameId == null) { for (index in 0 .. (group!!.games!!.size - 1)) { val game = group!!.games!![index] if (game.meta!!.end == null && (game.responses == null || !game.responses.containsKey(user!!.uid))) { gameId = index for (i in 0 .. (questions.size - 1)) { qOrder.add(i) val tmp = ArrayList<Int>(questions[i].options.size) for (j in 0 .. questions[i].options.size - 1) { tmp.add(0) } responses.add(tmp); } Collections.shuffle(qOrder); nextQuestion() return } } val intent: Intent = Intent(applicationContext, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) applicationContext.startActivity(intent) } else { render() } } } groupRef!!.addValueEventListener(groupListener) mRecyclerView = findViewById(R.id.checkbox_recycler) as RecyclerView mRecyclerView!!.setHasFixedSize(true) val rParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT) mRecyclerView!!.layoutParams = rParams mLayoutManager = LinearLayoutManager(getContext()) mRecyclerView!!.layoutManager = mLayoutManager mLayoutManager!!.setMeasuredDimension(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT) mAdapter = GameAdapter(ArrayList<String>(), ArrayList<Int>(), mRecyclerView, getGameActivity(), "" ) mRecyclerView!!.adapter = mAdapter } }
Android/app/src/main/java/com/decisionkitchen/decisionkitchen/GameActivity.kt
2007911703
package com.intellij.configurationStore import org.xmlpull.mxp1.MXParser import org.xmlpull.v1.XmlPullParser internal inline fun lazyPreloadScheme(bytes: ByteArray, isUseOldFileNameSanitize: Boolean, consumer: (name: String?, parser: XmlPullParser) -> Unit) { val parser = MXParser() parser.setInput(bytes.inputStream().reader()) consumer(preload(isUseOldFileNameSanitize, parser), parser) } private fun preload(isUseOldFileNameSanitize: Boolean, parser: MXParser): String? { var eventType = parser.eventType fun findName(): String? { eventType = parser.next() while (eventType != XmlPullParser.END_DOCUMENT) { when (eventType) { XmlPullParser.START_TAG -> { if (parser.name == "option" && parser.getAttributeValue(null, "name") == "myName") { return parser.getAttributeValue(null, "value") } } } eventType = parser.next() } return null } do { when (eventType) { XmlPullParser.START_TAG -> { if (!isUseOldFileNameSanitize || parser.name != "component") { if (parser.name == "profile" || (isUseOldFileNameSanitize && parser.name == "copyright")) { return findName() } else if (parser.name == "inspections") { // backward compatibility - we don't write PROFILE_NAME_TAG anymore return parser.getAttributeValue(null, "profile_name") ?: findName() } else { return null } } } } eventType = parser.next() } while (eventType != XmlPullParser.END_DOCUMENT) return null }
platform/configuration-store-impl/src/schemeLoader.kt
16380536
package ch.bailu.aat_lib.map.layer.selector import ch.bailu.aat_lib.coordinates.BoundingBoxE6 import ch.bailu.aat_lib.dispatcher.OnContentUpdatedInterface import ch.bailu.aat_lib.gpx.GpxInformation import ch.bailu.aat_lib.gpx.GpxNodeFinder import ch.bailu.aat_lib.gpx.GpxPointNode import ch.bailu.aat_lib.map.MapColor import ch.bailu.aat_lib.map.MapContext import ch.bailu.aat_lib.map.edge.EdgeViewInterface import ch.bailu.aat_lib.map.edge.Position import ch.bailu.aat_lib.map.layer.MapLayerInterface import ch.bailu.aat_lib.preferences.StorageInterface import ch.bailu.aat_lib.preferences.map.SolidMapGrid import ch.bailu.aat_lib.service.ServicesInterface import ch.bailu.aat_lib.util.IndexedMap import ch.bailu.aat_lib.util.Rect abstract class AbsNodeSelectorLayer( private val services: ServicesInterface, s: StorageInterface, mc: MapContext, private val pos: Position ) : MapLayerInterface, OnContentUpdatedInterface, EdgeViewInterface { private val square_size = mc.metrics.density.toPixel_i(SQUARE_SIZE.toFloat()) private val square_hsize = mc.metrics.density.toPixel_i(SQUARE_HSIZE.toFloat()) private var visible = true private val infoCache = IndexedMap<Int, GpxInformation>() private val centerRect = Rect() private var foundID = 0 private var foundIndex = 0 private var selectedNode: GpxPointNode? = null private val sgrid = SolidMapGrid(s, mc.solidKey) private var coordinates = sgrid.createCenterCoordinatesLayer(services) companion object { const val SQUARE_SIZE = 30 const val SQUARE_HSIZE = SQUARE_SIZE / 2 } init { centerRect.left = 0 centerRect.right = square_size centerRect.top = 0 centerRect.bottom = square_size } open fun getSelectedNode(): GpxPointNode? { return selectedNode } override fun drawForeground(mcontext: MapContext) { if (visible) { centerRect.offsetTo( mcontext.metrics.width / 2 - square_hsize, mcontext.metrics.height / 2 - square_hsize ) val centerBounding = BoundingBoxE6() val lt = mcontext.metrics.fromPixel(centerRect.left, centerRect.top) val rb = mcontext.metrics.fromPixel(centerRect.right, centerRect.bottom) if (lt != null && rb != null) { centerBounding.add(lt) centerBounding.add(rb) findNodeAndNotify(centerBounding) } centerRect.offset(mcontext.metrics.left, mcontext.metrics.top) drawSelectedNode(mcontext) drawCenterSquare(mcontext) coordinates.drawForeground(mcontext) } } override fun drawInside(mcontext: MapContext) { if (visible) { coordinates.drawInside(mcontext) } } private fun findNodeAndNotify(centerBounding: BoundingBoxE6) { if (selectedNode == null || !centerBounding.contains(selectedNode)) { if (findNode(centerBounding)) { val info = infoCache.getValue(foundID) val node = selectedNode if (info is GpxInformation && node is GpxPointNode) { setSelectedNode(foundID, info, node, foundIndex) } } } } private fun findNode(centerBounding: BoundingBoxE6): Boolean { var found = false var i = 0 while (i < infoCache.size() && !found) { val list = infoCache.getValueAt(i)!!.gpxList val finder = GpxNodeFinder(centerBounding) finder.walkTrack(list) if (finder.haveNode()) { found = true foundID = infoCache.getKeyAt(i)!! foundIndex = finder.nodeIndex selectedNode = finder.node } i++ } return found } abstract fun setSelectedNode(IID: Int, info: GpxInformation, node: GpxPointNode, index: Int) private fun drawSelectedNode(mcontext: MapContext) { val node = selectedNode if (node != null) { val selectedPixel = mcontext.metrics.toPixel(node) mcontext.draw() .bitmap(mcontext.draw().nodeBitmap, selectedPixel, MapColor.NODE_SELECTED) } } private fun drawCenterSquare(mcontext: MapContext) { mcontext.draw().rect(centerRect, mcontext.draw().gridPaint) mcontext.draw().point(mcontext.metrics.centerPixel) } override fun onContentUpdated(iid: Int, info: GpxInformation) { if (info.isLoaded) { infoCache.put(iid, info) } else { infoCache.remove(iid) } } override fun onPreferencesChanged(s: StorageInterface, key: String) { if (sgrid.hasKey(key)) { coordinates = sgrid.createCenterCoordinatesLayer(services) } } override fun show() { visible = true } override fun hide() { visible = false } override fun pos() : Position { return pos } }
aat-lib/src/main/java/ch/bailu/aat_lib/map/layer/selector/AbsNodeSelectorLayer.kt
3773468759
package net.nemerosa.ontrack.extension.vault import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.stereotype.Component @Component @ConfigurationProperties(prefix = "ontrack.config.vault") class VaultConfigProperties { /** * URI to the Vault end point */ var uri = "http://localhost:8200" /** * Token authentication */ var token = "test" /** * Key prefix */ var prefix = "ontrack/keys" }
ontrack-extension-vault/src/main/java/net/nemerosa/ontrack/extension/vault/VaultConfigProperties.kt
492200578
package net.nemerosa.ontrack.extension.bitbucket.cloud.configuration import net.nemerosa.ontrack.extension.bitbucket.cloud.AbstractBitbucketCloudTestSupport import net.nemerosa.ontrack.extension.bitbucket.cloud.TestOnBitbucketCloud import net.nemerosa.ontrack.extension.bitbucket.cloud.bitbucketCloudTestConfigMock import net.nemerosa.ontrack.extension.bitbucket.cloud.bitbucketCloudTestConfigReal import net.nemerosa.ontrack.model.support.ConnectorStatus import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertNotNull import kotlin.test.assertNull class BitbucketCloudConnectorStatusIndicatorIT : AbstractBitbucketCloudTestSupport() { @Autowired private lateinit var bitbucketCloudConnectorStatusIndicator: BitbucketCloudConnectorStatusIndicator @TestOnBitbucketCloud fun `Connector status indicator OK`() { val config = bitbucketCloudTestConfigReal() doTest(config) { assertNull(it.error, "Bitbucket Cloud connection OK") } } @Test fun `Connector status indicator not OK`() { val config = bitbucketCloudTestConfigMock() doTest(config) { assertNotNull(it.error, "Bitbucket Cloud connection NOT OK") } } private fun doTest(config: BitbucketCloudConfiguration, check: (ConnectorStatus) -> Unit) { asAdmin { withDisabledConfigurationTest { bitbucketCloudConfigurationService.newConfiguration(config) } val statuses = bitbucketCloudConnectorStatusIndicator.statuses val status = statuses.find { it.description.connector.type == "bitbucket-cloud" && it.description.connector.name == config.name && it.description.connection == config.workspace } assertNotNull(status) { check(it) } } } }
ontrack-extension-bitbucket-cloud/src/test/java/net/nemerosa/ontrack/extension/bitbucket/cloud/configuration/BitbucketCloudConnectorStatusIndicatorIT.kt
170747833
/** * 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 import com.mycollab.core.MyCollabException import org.slf4j.LoggerFactory import java.lang.reflect.Method /** * @author MyCollab Ltd. * @since 1.0 */ object ProjectResources { private val LOG = LoggerFactory.getLogger(ProjectResources::class.java) private var toHtmlMethod: Method? = null init { try { val resourceCls = Class.forName("com.mycollab.module.project.ui.ProjectAssetsManager") toHtmlMethod = resourceCls.getMethod("toHtml", String::class.java) } catch (e: Exception) { throw MyCollabException("Can not reload resource", e) } } fun getFontIconHtml(type: String): String = try { toHtmlMethod!!.invoke(null, type) as String } catch (e: Exception) { LOG.error("Can not get resource type $type") "" } }
mycollab-services/src/main/java/com/mycollab/module/project/ProjectResources.kt
2040190776
package net.bjoernpetersen.musicbot.api.player import net.bjoernpetersen.musicbot.spi.plugin.Suggester internal data class DefaultSuggester(val suggester: Suggester?)
src/main/kotlin/net/bjoernpetersen/musicbot/api/player/DefaultSuggester.kt
2389918276
package com.mobilejazz.colloc.feature.encoder.domain.interactor import com.mobilejazz.colloc.domain.model.Language import com.mobilejazz.colloc.ext.toJsonElement import com.mobilejazz.colloc.randomString import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.verify import kotlinx.serialization.json.Json import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.io.File internal class AngularEncodeInteractorTest { @TempDir private val localizationDirectory: File = File("{src/test/resources}/encode_localization/") @MockK private lateinit var json: Json @BeforeEach fun setUp() { MockKAnnotations.init(this) } @Test fun `assert content encoded properly`() { val language = Language(code = randomString(), name = randomString()) val expectedTranslation = randomString() val rawTranslation = anyTranslation() val dictionary = mapOf(language to rawTranslation) val translationHierarchy = rawTranslation.mapValues { it.value.toJsonElement() } every { json.encodeToString(any(), translationHierarchy) } returns expectedTranslation givenEncodeInteractor()(localizationDirectory, dictionary) verify(exactly = 1) { json.encodeToString(any(), translationHierarchy) } val actualTranslation = File(localizationDirectory, "angular/${language.code}.json").readText() assertEquals(expectedTranslation, actualTranslation) } private fun givenEncodeInteractor() = AngularEncodeInteractor(json) }
server/src/test/kotlin/com/mobilejazz/colloc/feature/encoder/domain/interactor/AngularEncodeInteractorTest.kt
4045323041
/* * 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.tasks import com.netflix.spinnaker.gradle.extension.Plugins import org.gradle.api.DefaultTask import org.gradle.api.logging.LogLevel import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction /** * Task to register a spinnaker plugin. * This task will invoke a spinnaker API to register 'spinnaker plugin' metadata with Front50. */ open class RegistrationTask : DefaultTask() { @Internal override fun getGroup(): String? = Plugins.GROUP @TaskAction fun doAction() { project.logger.log(LogLevel.INFO, "Registration with spinnaker is not complete!!") } }
spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/tasks/RegistrationTask.kt
771360024
/* * Copyright 2018 Stéphane Baiget * * 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.sbgapps.scoreit.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.sbgapps.scoreit.ui.R import com.sbgapps.scoreit.ui.base.BaseFragment import com.sbgapps.scoreit.ui.ext.observe import com.sbgapps.scoreit.ui.model.UniversalLap import com.sbgapps.scoreit.ui.viewmodel.UniversalViewModel import com.sbgapps.scoreit.ui.widget.LinearListView import kotlinx.android.synthetic.main.fragment_universal_edition.* import kotlinx.android.synthetic.main.item_universal_edition.view.* import org.koin.androidx.viewmodel.ext.android.sharedViewModel class UniversalEditionFragment : BaseFragment() { private val model by sharedViewModel<UniversalViewModel>() private val adapter: PlayerAdapter = PlayerAdapter() private var points = mutableListOf<Int>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_universal_edition, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { players.setAdapter(adapter) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observe(model.getEditedLap(), ::setGame) } private fun setGame(laps: Pair<UniversalLap, List<String>>?) { laps?.let { points = it.first.points adapter.items = it.second.zip(it.first.points) } } inner class PlayerAdapter : LinearListView.Adapter<Pair<String, Int>>() { override val layoutId = R.layout.item_universal_edition override fun bind(position: Int, view: View) { val (player, _points) = getItem(position) with(view) { playerName.text = player playerPoints.text = _points.toString() plusOne.setOnClickListener { addPoints(1, position, playerPoints) } plusFive.setOnClickListener { addPoints(5, position, playerPoints) } plusTen.setOnClickListener { addPoints(10, position, playerPoints) } plusHundred.setOnClickListener { addPoints(100, position, playerPoints) } minusOne.setOnClickListener { addPoints(-1, position, playerPoints) } minusFive.setOnClickListener { addPoints(-5, position, playerPoints) } minusTen.setOnClickListener { addPoints(-10, position, playerPoints) } minusHundred.setOnClickListener { addPoints(-100, position, playerPoints) } } } private fun addPoints(_points: Int, position: Int, textView: TextView) { points[position] += _points textView.text = points[position].toString() } } companion object { fun newInstance() = UniversalEditionFragment() } }
ui/src/main/java/com/sbgapps/scoreit/ui/view/UniversalEditionFragment.kt
3198906467
/* * Copyright 2018 Stéphane Baiget * * 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.sbgapps.scoreit.cache.di import com.sbgapps.scoreit.cache.DatabaseRepo import com.sbgapps.scoreit.cache.UniversalGameRepository import com.sbgapps.scoreit.cache.db.DatabaseInitializer import com.sbgapps.scoreit.domain.model.UniversalLapEntity import com.sbgapps.scoreit.domain.repository.GameRepository import org.koin.dsl.module.module val dataModule = module { factory { DatabaseRepo(get()) } factory { DatabaseInitializer(get()) } factory { UniversalGameRepository( get(), get() ) as GameRepository<UniversalLapEntity> } }
data/src/main/java/com/sbgapps/scoreit/cache/di/DataModule.kt
1632912787
package com.nilhcem.henripotier.ui.cart import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.nilhcem.henripotier.core.cart.ShoppingCart import com.nilhcem.henripotier.core.extensions.createHolder import com.nilhcem.henripotier.core.extensions.getView import com.nilhcem.henripotier.core.extensions.replaceAll import java.util.ArrayList class CartAdapter(val cart: ShoppingCart) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var items: ArrayList<CartItemData> = ArrayList() set(value) { $items.replaceAll(value) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = createHolder(CartItem(parent.getContext())) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = getView<CartItem>(holder).bindData(items.get(position), position >= cart.getNbItemsInCart()) override fun getItemCount(): Int = items.size() }
app/src/main/kotlin/com/nilhcem/henripotier/ui/cart/CartAdapter.kt
84194769
package org.jetbrains.protocolReader import gnu.trove.THashSet import org.jetbrains.io.JsonReaderEx import org.jetbrains.jsonProtocol.JsonParseMethod import java.lang.reflect.Method import java.lang.reflect.ParameterizedType import java.util.Arrays import java.util.Comparator import java.util.LinkedHashMap class ReaderRoot<R>(public val type: Class<R>, private val typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>) { private val visitedInterfaces = THashSet<Class<*>>(1) val methodMap = LinkedHashMap<Method, ReadDelegate>(); init { readInterfaceRecursive(type) } throws(javaClass<JsonProtocolModelParseException>()) private fun readInterfaceRecursive(clazz: Class<*>) { if (visitedInterfaces.contains(clazz)) { return } visitedInterfaces.add(clazz) // todo sort by source location val methods = clazz.getMethods() Arrays.sort<Method>(methods, object : Comparator<Method> { override fun compare(o1: Method, o2: Method): Int { return o1.getName().compareTo(o2.getName()) } }) for (m in methods) { val jsonParseMethod = m.getAnnotation<JsonParseMethod>(javaClass<JsonParseMethod>()) if (jsonParseMethod == null) { continue } val exceptionTypes = m.getExceptionTypes() if (exceptionTypes.size() > 1) { throw JsonProtocolModelParseException("Too many exception declared in " + m) } var returnType = m.getGenericReturnType() var isList = false if (returnType is ParameterizedType) { val parameterizedType = returnType as ParameterizedType if (parameterizedType.getRawType() == javaClass<List<Any>>()) { isList = true returnType = parameterizedType.getActualTypeArguments()[0] } } //noinspection SuspiciousMethodCalls var typeWriter: TypeWriter<*>? = typeToTypeHandler.get(returnType) if (typeWriter == null) { typeWriter = createHandler(typeToTypeHandler, m.getReturnType()) if (typeWriter == null) { throw JsonProtocolModelParseException("Unknown return type in " + m) } } val arguments = m.getGenericParameterTypes() if (arguments.size() > 2) { throw JsonProtocolModelParseException("Exactly one argument is expected in " + m) } val argument = arguments[0] if (argument == javaClass<JsonReaderEx>() || argument == javaClass<Any>()) { methodMap.put(m, ReadDelegate(typeWriter!!, isList, arguments.size() != 1)) } else { throw JsonProtocolModelParseException("Unrecognized argument type in " + m) } } for (baseType in clazz.getGenericInterfaces()) { if (baseType !is Class<*>) { throw JsonProtocolModelParseException("Base interface must be class in " + clazz) } readInterfaceRecursive(baseType) } } public fun writeStaticMethodJava(scope: ClassScope) { val out = scope.output for (entry in methodMap.entrySet()) { out.newLine() entry.getValue().write(scope, entry.getKey(), out) out.newLine() } } }
platform/script-debugger/protocol/protocol-reader/src/ReaderRoot.kt
2518344426
package be.florien.anyflow.data import java.text.SimpleDateFormat import java.util.* object TimeOperations { private const val AMPACHE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX" private val ampacheCompleteFormatter = SimpleDateFormat(AMPACHE_DATE_FORMAT, Locale.getDefault()) private val ampacheGetFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.US) var currentTimeUpdater: CurrentTimeUpdater? = null fun getCurrentDate(): Calendar { var calendar = Calendar.getInstance() calendar = currentTimeUpdater?.getCurrentTimeUpdated(calendar) ?: calendar return calendar } fun getCurrentDatePlus(field: Int, increment: Int): Calendar { var calendar = Calendar.getInstance().apply { add(field, increment) } calendar = currentTimeUpdater?.getCurrentTimeUpdated(calendar) ?: calendar return calendar } fun getDateFromMillis(millis: Long): Calendar = Calendar.getInstance().apply { timeInMillis = millis } fun getDateFromAmpacheComplete(formatted: String): Calendar = Calendar.getInstance().apply { time = ampacheCompleteFormatter.parse(formatted) ?: throw IllegalArgumentException("The provided string could not be parsed to an ampache date") } fun getAmpacheCompleteFormatted(time: Calendar): String = ampacheCompleteFormatter.format(time.time) fun getAmpacheGetFormatted(time: Calendar): String = ampacheGetFormatter.format(time.time) interface CurrentTimeUpdater { fun getCurrentTimeUpdated(current: Calendar): Calendar } }
app/src/main/java/be/florien/anyflow/data/TimeOperations.kt
2136559863
package com.emogoth.android.phone.mimi.span import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.net.Uri import android.os.Handler import android.os.Looper import android.text.TextPaint import android.view.View import android.widget.Toast import com.emogoth.android.phone.mimi.R import com.emogoth.android.phone.mimi.util.MimiUtil import com.google.android.material.dialog.MaterialAlertDialogBuilder class YoutubeLinkSpan(private val videoId: String, private val linkColor: Int) : LongClickableSpan() { override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = true ds.color = linkColor } override fun onClick(widget: View) { openLink(widget.context) } private fun showChoiceDialog(context: Context) { val url = MimiUtil.https() + "youtube.com/watch?v=" + videoId val handler = Handler(Looper.getMainLooper()) handler.post { MaterialAlertDialogBuilder(context) .setTitle(R.string.youtube_link) .setItems(R.array.youtube_dialog_list) { dialog, which -> if (which == 0) { openLink(context) } else { val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.setPrimaryClip(ClipData.newPlainText("youtube_link", url)) Toast.makeText(context, R.string.link_copied_to_clipboard, Toast.LENGTH_SHORT).show() } } .setCancelable(true) .show() .setCanceledOnTouchOutside(true) } } private fun openLink(context: Context) { val url = MimiUtil.https() + "youtube.com/watch?v=" + videoId val openIntent = Intent(Intent.ACTION_VIEW) openIntent.data = Uri.parse(url) context.startActivity(openIntent) } override fun onLongClick(v: View): Boolean { showChoiceDialog(v.context) return true } }
mimi-app/src/main/java/com/emogoth/android/phone/mimi/span/YoutubeLinkSpan.kt
1360654748
package nl.endran.skeleton.kotlin.mvp import android.os.Bundle import android.support.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup abstract class BaseFragmentView<VM, P : BaseFragmentPresenter<VM>> { protected var rootView: View? = null protected var presenter: P? = null open fun inflate(inflater: LayoutInflater, container: ViewGroup, @SuppressWarnings("unused") savedInstanceState: Bundle?): View { rootView = inflater.inflate(getViewId(), container, false) return rootView!! } fun androidViewReady() { if (rootView != null) { prepare(rootView!!) } } fun deflate() { stop() rootView = null } fun start(presenter: P) { this.presenter = presenter val viewModel = getViewModel() presenter.start(viewModel) } fun stop() { presenter?.stop() presenter = null } /** * Return the view id to be inflated */ @LayoutRes protected abstract fun getViewId(): Int /** * Create and return the implementation of the ViewModel */ protected abstract fun getViewModel(): VM /** * Convenience method so that the implementation knows when UI widget can be obtained and prepared. */ protected abstract fun prepare(rootView: View); }
KotlinSkeleton/app/src/main/java/nl/endran/skeleton/kotlin/mvp/BaseFragmentView.kt
2668276905