path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
lite/examples/sound_classification/android/app/src/main/java/org/tensorflow/lite/examples/soundclassifier/SoundClassifier.kt
thezwick
345,521,429
false
null
/* * Copyright 2020 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tensorflow.lite.examples.soundclassifier import android.content.Context import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaRecorder import android.os.SystemClock import android.util.Log import androidx.annotation.MainThread import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.nio.FloatBuffer import java.util.Locale import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlin.math.ceil import kotlin.math.sin import org.tensorflow.lite.Interpreter import org.tensorflow.lite.support.common.FileUtil /** * Performs classification on sound. * * <p>The API supports models which accept sound input via {@code AudioRecord} and one classification output tensor. * The output of the recognition is emitted as LiveData of Map. * */ class SoundClassifier(context: Context, private val options: Options = Options()) : DefaultLifecycleObserver { class Options constructor( /** Path of the converted model label file, relative to the assets/ directory. */ val metadataPath: String = "labels.txt", /** Path of the converted .tflite file, relative to the assets/ directory. */ val modelPath: String = "sound_classifier.tflite", /** The required audio sample rate in Hz. */ val sampleRate: Int = 44_100, /** How many milliseconds to sleep between successive audio sample pulls. */ val audioPullPeriod: Long = 50L, /** Number of warm up runs to do after loading the TFLite model. */ val warmupRuns: Int = 3, /** Number of points in average to reduce noise. */ val pointsInAverage: Int = 10, /** Overlap factor of recognition period */ var overlapFactor: Float = 0.8f, /** Probability value above which a class is labeled as active (i.e., detected) the display. */ var probabilityThreshold: Float = 0.3f, ) val isRecording: Boolean get() = recordingThread?.isAlive == true /** As the result of sound classification, this value emits map of probabilities */ val probabilities: LiveData<Map<String, Float>> get() = _probabilities private val _probabilities = MutableLiveData<Map<String, Float>>() private val recordingBufferLock: ReentrantLock = ReentrantLock() var isClosed: Boolean = true private set /** * LifecycleOwner instance to deal with RESUME, PAUSE and DESTROY events automatically. * You can also handle those events by calling `start()`, `stop()` and `close()` methods * manually. */ var lifecycleOwner: LifecycleOwner? = null @MainThread set(value) { if (field === value) return field?.lifecycle?.removeObserver(this) field = value?.also { it.lifecycle.addObserver(this) } } /** Overlap factor of recognition period */ var overlapFactor: Float get() = options.overlapFactor set(value) { options.overlapFactor = value.also { recognitionPeriod = (1000L * (1 - value)).toLong() } } /** Probability value above which a class is labeled as active (i.e., detected) the display. */ var probabilityThreshold: Float get() = options.probabilityThreshold set(value) { options.probabilityThreshold = value } /** Paused by user */ var isPaused: Boolean = false set(value) { field = value if (value) stop() else start() } /** Names of the model's output classes. */ lateinit var labelList: List<String> private set /** How many milliseconds between consecutive model inference calls. */ private var recognitionPeriod = (1000L * (1 - overlapFactor)).toLong() /** The TFLite interpreter instance. */ private lateinit var interpreter: Interpreter /** Audio length (in # of PCM samples) required by the TFLite model. */ private var modelInputLength = 0 /** Number of output classes of the TFLite model. */ private var modelNumClasses = 0 /** Used to hold the real-time probabilities predicted by the model for the output classes. */ private lateinit var predictionProbs: FloatArray /** Latest prediction latency in milliseconds. */ private var latestPredictionLatencyMs = 0f private var recordingThread: Thread? = null private var recognitionThread: Thread? = null private var recordingOffset = 0 private lateinit var recordingBuffer: ShortArray /** Buffer that holds audio PCM sample that are fed to the TFLite model for inference. */ private lateinit var inputBuffer: FloatBuffer init { loadLabels(context) setupInterpreter(context) warmUpModel() } override fun onResume(owner: LifecycleOwner) = start() override fun onPause(owner: LifecycleOwner) = stop() /** * Starts sound classification, which triggers running of * `recordingThread` and `recognitionThread`. */ fun start() { if (!isPaused) { startAudioRecord() } } /** * Stops sound classification, which triggers interruption of * `recordingThread` and `recognitionThread`. */ fun stop() { if (isClosed || !isRecording) return recordingThread?.interrupt() recognitionThread?.interrupt() _probabilities.postValue(labelList.associateWith { 0f }) } fun close() { stop() if (isClosed) return interpreter.close() isClosed = true } /** Retrieve labels from "labels.txt" file */ private fun loadLabels(context: Context) { try { val reader = BufferedReader(InputStreamReader(context.assets.open(options.metadataPath))) val wordList = mutableListOf<String>() reader.useLines { lines -> lines.forEach { wordList.add(it.split(" ").last()) } } labelList = wordList.map { it.toTitleCase() } } catch (e: IOException) { Log.e(TAG, "Failed to read model ${options.metadataPath}: ${e.message}") } } private fun setupInterpreter(context: Context) { interpreter = try { val tfliteBuffer = FileUtil.loadMappedFile(context, options.modelPath) Log.i(TAG, "Done creating TFLite buffer from ${options.modelPath}") Interpreter(tfliteBuffer, Interpreter.Options()) } catch (e: IOException) { Log.e(TAG, "Failed to load TFLite model - ${e.message}") return } // Inspect input and output specs. val inputShape = interpreter.getInputTensor(0).shape() Log.i(TAG, "TFLite model input shape: ${inputShape.contentToString()}") modelInputLength = inputShape[1] val outputShape = interpreter.getOutputTensor(0).shape() Log.i(TAG, "TFLite output shape: ${outputShape.contentToString()}") modelNumClasses = outputShape[1] if (modelNumClasses != labelList.size) { Log.e( TAG, "Mismatch between metadata number of classes (${labelList.size})" + " and model output length ($modelNumClasses)" ) } // Fill the array with NaNs initially. predictionProbs = FloatArray(modelNumClasses) { Float.NaN } inputBuffer = FloatBuffer.allocate(modelInputLength) } private fun warmUpModel() { generateDummyAudioInput(inputBuffer) for (n in 0 until options.warmupRuns) { val t0 = SystemClock.elapsedRealtimeNanos() // Create input and output buffers. val outputBuffer = FloatBuffer.allocate(modelNumClasses) inputBuffer.rewind() outputBuffer.rewind() interpreter.run(inputBuffer, outputBuffer) Log.i( TAG, "Switches: Done calling interpreter.run(): %s (%.6f ms)".format( outputBuffer.array().contentToString(), (SystemClock.elapsedRealtimeNanos() - t0) / NANOS_IN_MILLIS ) ) } } private fun generateDummyAudioInput(inputBuffer: FloatBuffer) { val twoPiTimesFreq = 2 * Math.PI.toFloat() * 1000f for (i in 0 until modelInputLength) { val x = i.toFloat() / (modelInputLength - 1) inputBuffer.put(i, sin(twoPiTimesFreq * x.toDouble()).toFloat()) } } /** Start a thread to pull audio samples in continuously. */ @Synchronized private fun startAudioRecord() { if (isRecording) return recordingThread = AudioRecordingThread().apply { start() } isClosed = false } /** Start a thread that runs model inference (i.e., recognition) at a regular interval. */ private fun startRecognition() { recognitionThread = RecognitionThread().apply { start() } } /** Runnable class to run a thread for audio recording */ private inner class AudioRecordingThread : Thread() { override fun run() { var bufferSize = AudioRecord.getMinBufferSize( options.sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT ) if (bufferSize == AudioRecord.ERROR || bufferSize == AudioRecord.ERROR_BAD_VALUE) { bufferSize = options.sampleRate * 2 Log.w(TAG, "bufferSize has error or bad value") } Log.i(TAG, "bufferSize = $bufferSize") val record = AudioRecord( // including MIC, UNPROCESSED, and CAMCORDER. MediaRecorder.AudioSource.VOICE_RECOGNITION, options.sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize ) if (record.state != AudioRecord.STATE_INITIALIZED) { Log.e(TAG, "AudioRecord failed to initialize") return } Log.i(TAG, "Successfully initialized AudioRecord") val bufferSamples = bufferSize / 2 val audioBuffer = ShortArray(bufferSamples) val recordingBufferSamples = ceil(modelInputLength.toFloat() / bufferSamples.toDouble()) .toInt() * bufferSamples Log.i(TAG, "recordingBufferSamples = $recordingBufferSamples") recordingOffset = 0 recordingBuffer = ShortArray(recordingBufferSamples) record.startRecording() Log.i(TAG, "Successfully started AudioRecord recording") // Start recognition (model inference) thread. startRecognition() while (!isInterrupted) { try { TimeUnit.MILLISECONDS.sleep(options.audioPullPeriod) } catch (e: InterruptedException) { Log.w(TAG, "Sleep interrupted in audio recording thread.") break } when (record.read(audioBuffer, 0, audioBuffer.size)) { AudioRecord.ERROR_INVALID_OPERATION -> { Log.w(TAG, "AudioRecord.ERROR_INVALID_OPERATION") } AudioRecord.ERROR_BAD_VALUE -> { Log.w(TAG, "AudioRecord.ERROR_BAD_VALUE") } AudioRecord.ERROR_DEAD_OBJECT -> { Log.w(TAG, "AudioRecord.ERROR_DEAD_OBJECT") } AudioRecord.ERROR -> { Log.w(TAG, "AudioRecord.ERROR") } bufferSamples -> { // We apply locks here to avoid two separate threads (the recording and // recognition threads) reading and writing from the recordingBuffer at the same // time, which can cause the recognition thread to read garbled audio snippets. recordingBufferLock.withLock { audioBuffer.copyInto( recordingBuffer, recordingOffset, 0, bufferSamples ) recordingOffset = (recordingOffset + bufferSamples) % recordingBufferSamples } } } } } } private inner class RecognitionThread : Thread() { override fun run() { if (modelInputLength <= 0 || modelNumClasses <= 0) { Log.e(TAG, "Switches: Cannot start recognition because model is unavailable.") return } val outputBuffer = FloatBuffer.allocate(modelNumClasses) while (!isInterrupted) { try { TimeUnit.MILLISECONDS.sleep(recognitionPeriod) } catch (e: InterruptedException) { Log.w(TAG, "Sleep interrupted in recognition thread.") break } var samplesAreAllZero = true recordingBufferLock.withLock { var j = (recordingOffset - modelInputLength) % modelInputLength if (j < 0) { j += modelInputLength } for (i in 0 until modelInputLength) { val s = if (i >= options.pointsInAverage && j >= options.pointsInAverage) { ((j - options.pointsInAverage + 1)..j).map { recordingBuffer[it % modelInputLength] } .average() } else { recordingBuffer[j % modelInputLength] } j += 1 if (samplesAreAllZero && s.toInt() != 0) { samplesAreAllZero = false } inputBuffer.put(i, s.toFloat()) } } if (samplesAreAllZero) { Log.w(TAG, "No audio input: All audio samples are zero!") continue } val t0 = SystemClock.elapsedRealtimeNanos() inputBuffer.rewind() outputBuffer.rewind() interpreter.run(inputBuffer, outputBuffer) outputBuffer.rewind() outputBuffer.get(predictionProbs) // Copy data to predictionProbs. val probList = predictionProbs.map { if (it > probabilityThreshold) it else 0f } _probabilities.postValue(labelList.zip(probList).toMap()) latestPredictionLatencyMs = ((SystemClock.elapsedRealtimeNanos() - t0) / 1e6).toFloat() } } } companion object { private const val TAG = "SoundClassifier" /** Number of nanoseconds in a millisecond */ private const val NANOS_IN_MILLIS = 1_000_000.toDouble() } } private fun String.toTitleCase() = splitToSequence("_") .map { it.capitalize(Locale.ROOT) } .joinToString(" ") .trim()
1
null
1
1
bc3e2ff42e2a2ce2aff0aa10d7ec7f66911cd1ed
14,528
sawit_detector_demo
Apache License 2.0
common-view/src/main/java/ru/boronin/common/view/viewpager2/ViewPagerFragmentAdapter.kt
boronin-serge
242,097,636
false
null
package ru.boronin.cardtasker.common.presentation import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter class ViewPagerFragmentAdapter( activity: FragmentActivity ) : FragmentStateAdapter(activity) { private val items: MutableList<Fragment> = mutableListOf() override fun createFragment(position: Int) = items[position] override fun getItemCount() = items.size fun update(items: List<Fragment>) { this.items.clear() this.items.addAll(items) notifyDataSetChanged() } }
1
null
1
2
07d177d9e9ded6fdf76e0f43ef4cd455ff0692fd
608
simpleweather
MIT License
app/src/main/java/com/hzm/sharedpreference/PropertyListAdapter.kt
Rohaid-Bhatti
707,578,011
false
{"Kotlin": 53772}
package com.hzm.sharedpreference import android.app.AlertDialog import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.hzm.sharedpreference.dataClass.PropertyListItem import com.hzm.sharedpreference.propertyWork.propertyDB.PropertyDatabase import com.hzm.sharedpreference.propertyWork.propertyDB.PropertyEntity import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class PropertyListAdapter: ListAdapter<PropertyListItem, PropertyListAdapter.PropertyViewHolder>(PropertyDiffCallback()) { private var unfilteredPropertyList: List<PropertyListItem> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PropertyViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_property, parent, false) return PropertyViewHolder(view) } override fun onBindViewHolder(holder: PropertyViewHolder, position: Int) { val property = getItem(position) holder.bind(property) } fun setUnfilteredPropertyList(list: List<PropertyListItem>) { unfilteredPropertyList = list submitList(list) } /*fun filterBySearchQuery(query: String) { val filteredList = unfilteredPropertyList.filter { property -> // Check if the query matches any property or location details property.address.contains(query, true) || property.city.contains(query, true) || property.type.contains(query, true) || property.interior.contains(query, true) || property.size.contains(query, true) } submitList(filteredList) val filteredProperties = propertyDAO.searchProperties(query) submitList(filteredProperties) } fun filterByFurnished(criteria: String) { val filteredList = unfilteredPropertyList.filter { property -> // Filter based on Furnished or Not Furnished criteria.isEmpty() || property.interior.equals(criteria, ignoreCase = true) } submitList(filteredList) } fun filterByType(criteria: String) { val filteredList = unfilteredPropertyList.filter { property -> // Filter based on Sale or Rent criteria.isEmpty() || property.type.equals(criteria, ignoreCase = true) } submitList(filteredList) }*/ inner class PropertyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val textViewRoom: TextView = itemView.findViewById(R.id.textViewRoom) private val textViewBed: TextView = itemView.findViewById(R.id.textViewBed) private val textViewBath: TextView = itemView.findViewById(R.id.textViewBath) private val textViewFloor: TextView = itemView.findViewById(R.id.textViewFloor) private val textViewType: TextView = itemView.findViewById(R.id.textViewType) private val textViewInterior: TextView = itemView.findViewById(R.id.textViewInterior) private val textViewSize: TextView = itemView.findViewById(R.id.textViewSize) private val textViewArea: TextView = itemView.findViewById(R.id.textViewArea) private val textViewUserEmail: TextView = itemView.findViewById(R.id.textViewUserEmail) val btnEdit = itemView.findViewById<Button>(R.id.btnEdit) val btnDelete = itemView.findViewById<Button>(R.id.btnDelete) fun bind(property: PropertyListItem) { textViewRoom.text = "Rooms: ${property.numberOfRoom}" textViewBed.text = "Bedrooms: ${property.numberOfBedroom}" textViewBath.text = "Bathrooms: ${property.numberOfBathroom}" textViewFloor.text = "Floor: ${property.floor}" textViewType.text = "Type: ${property.type}" textViewInterior.text = "Interior: ${property.interior}" textViewSize.text = "Size: ${property.size}" textViewArea.text = "Area: ${property.address}, ${property.city}" textViewUserEmail.text = "User Email: ${property.userEmail}" btnEdit.setOnClickListener { // Handle the "Edit" button click here onEditClick(property) } btnDelete.setOnClickListener { // Handle the "Delete" button click here onDeleteClick(property) } } // Function to handle "Edit" button click private fun onEditClick(property: PropertyListItem) { // Implement your edit functionality here, e.g., open an edit activity/fragment val intent = Intent(itemView.context, EditPropertyActivity::class.java) intent.putExtra("propertyId", property.houseId) itemView.context.startActivity(intent) } // Function to handle "Delete" button click private fun onDeleteClick(property: PropertyListItem) { // Implement your delete functionality here, e.g., show a confirmation dialog val alertDialog = AlertDialog.Builder(itemView.context) alertDialog.setTitle("Confirm Deletion") alertDialog.setMessage("Are you sure you want to delete this property?") alertDialog.setPositiveButton("Yes") { _, _ -> // User confirmed deletion, delete the property from both tables CoroutineScope(Dispatchers.IO).launch { val propertyDao = PropertyDatabase.getDatabase(itemView.context).propertyDao() propertyDao.deleteProperty(PropertyEntity( houseId = property.houseId, numberOfRoom = property.numberOfRoom, numberOfBedroom = property.numberOfBedroom, numberOfBathroom = property.numberOfBathroom, floor = property.floor, type = property.type, interior = property.interior, size = property.size, userEmail = property.userEmail)) propertyDao.deleteLocationByHouseId(property.houseId) } Toast.makeText(itemView.context, "Delete Successfully", Toast.LENGTH_SHORT).show() } alertDialog.setNegativeButton("No") { dialog, _ -> dialog.dismiss() } alertDialog.show() } } } class PropertyDiffCallback : DiffUtil.ItemCallback<PropertyListItem>() { override fun areItemsTheSame(oldItem: PropertyListItem, newItem: PropertyListItem): Boolean { return oldItem.houseId == newItem.houseId } override fun areContentsTheSame(oldItem: PropertyListItem, newItem: PropertyListItem): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
7c2e48ecfd819c62e539e16a228661daea9de4ba
7,124
Property-Manager-App
MIT License
modulecheck-parsing/wiring/src/main/kotlin/modulecheck/parsing/wiring/RealAndroidDataBindingNameProvider.kt
RBusarow
316,627,145
false
null
/* * Copyright (C) 2021-2022 Rick Busarow * 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 modulecheck.parsing.wiring import modulecheck.api.context.androidDataBindingDeclarationsForSourceSetName import modulecheck.api.context.classpathDependencies import modulecheck.parsing.gradle.model.SourceSetName import modulecheck.parsing.source.AndroidDataBindingDeclaredName import modulecheck.parsing.source.internal.AndroidDataBindingNameProvider import modulecheck.project.McProject import modulecheck.project.isAndroid import modulecheck.project.project import modulecheck.utils.lazy.LazySet import modulecheck.utils.lazy.emptyLazySet import modulecheck.utils.lazy.toLazySet class RealAndroidDataBindingNameProvider constructor( private val project: McProject, private val sourceSetName: SourceSetName ) : AndroidDataBindingNameProvider { override suspend fun get(): LazySet<AndroidDataBindingDeclaredName> { if (!project.isAndroid()) return emptyLazySet() val local = project.androidDataBindingDeclarationsForSourceSetName(sourceSetName) val transitive = project.classpathDependencies() .get(sourceSetName) .map { tpd -> val sourceProject = tpd.source.project(project) tpd.contributed.project(project) .androidDataBindingDeclarationsForSourceSetName( tpd.source.declaringSourceSetName(sourceProject.isAndroid()) ) } return listOf(local) .plus(transitive) .toLazySet() } }
76
null
7
95
24e7c7667490630d30cf8b59cd504cd863cd1fba
2,001
ModuleCheck
Apache License 2.0
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceEntityStorageImpl.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.trace import com.intellij.openapi.util.registry.Registry import com.intellij.util.ExceptionUtil import com.intellij.util.ObjectUtils import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.getDiff import com.intellij.workspaceModel.storage.impl.exceptions.AddDiffException import com.intellij.workspaceModel.storage.impl.exceptions.PersistentIdAlreadyExistsException import com.intellij.workspaceModel.storage.impl.external.EmptyExternalEntityMapping import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.external.MutableExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex.MutableVirtualFileIndex.Companion.VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex import org.jetbrains.annotations.TestOnly import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import kotlin.reflect.KClass import kotlin.reflect.KProperty1 internal data class EntityReferenceImpl<E : WorkspaceEntity>(private val id: EntityId) : EntityReference<E>() { override fun resolve(storage: EntityStorage): E? { @Suppress("UNCHECKED_CAST") return (storage as AbstractEntityStorage).entityDataById(id)?.createEntity(storage) as? E } } internal class EntityStorageSnapshotImpl constructor( override val entitiesByType: ImmutableEntitiesBarrel, override val refs: RefsTable, override val indexes: StorageIndexes ) : EntityStorageSnapshot, AbstractEntityStorage() { // This cache should not be transferred to other versions of storage private val persistentIdCache = ConcurrentHashMap<PersistentEntityId<*>, WorkspaceEntity>() @Suppress("UNCHECKED_CAST") override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entity = persistentIdCache.getOrPut(id) { super.resolve(id) ?: NULL_ENTITY } return if (entity !== NULL_ENTITY) entity as E else null } override fun toSnapshot(): EntityStorageSnapshot = this companion object { private val NULL_ENTITY = ObjectUtils.sentinel("null entity", WorkspaceEntity::class.java) val EMPTY = EntityStorageSnapshotImpl(ImmutableEntitiesBarrel.EMPTY, RefsTable(), StorageIndexes.EMPTY) } } internal class MutableEntityStorageImpl( override val entitiesByType: MutableEntitiesBarrel, override val refs: MutableRefsTable, override val indexes: MutableStorageIndexes, @Volatile private var trackStackTrace: Boolean = false ) : MutableEntityStorage, AbstractEntityStorage() { internal val changeLog = WorkspaceBuilderChangeLog() // Temporal solution for accessing error in deft project. internal var throwExceptionOnError = false internal fun incModificationCount() { this.changeLog.modificationCount++ } override val modificationCount: Long get() = this.changeLog.modificationCount private val writingFlag = AtomicBoolean() @Volatile private var stackTrace: String? = null @Volatile private var threadId: Long? = null @Volatile private var threadName: String? = null // --------------- Replace By Source stuff ----------- internal var useNewRbs = Registry.`is`("ide.workspace.model.rbs.as.tree", true) @TestOnly internal var keepLastRbsEngine = false internal var engine: ReplaceBySourceOperation? = null @set:TestOnly internal var upgradeEngine: ((ReplaceBySourceOperation) -> Unit)? = null // --------------- Replace By Source stuff ----------- override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> { @Suppress("UNCHECKED_CAST") return entitiesByType[entityClass.toClassId()]?.all()?.map { it.wrapAsModifiable(this) } as? Sequence<E> ?: emptySequence() } override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R> { val classId = entityClass.toClassId() @Suppress("UNCHECKED_CAST") return indexes.softLinks.getIdsByEntry(id).asSequence() .filter { it.clazz == classId } .map { entityDataByIdOrDie(it).wrapAsModifiable(this) as R } } override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null val entityData: WorkspaceEntityData<WorkspaceEntity> = entityDataById(entityIds) as? WorkspaceEntityData<WorkspaceEntity> ?: return null @Suppress("UNCHECKED_CAST") return entityData.wrapAsModifiable(this) as E? } // Do not remove cast to Class<out TypedEntity>. kotlin fails without it @Suppress("USELESS_CAST") override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> { return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source -> indexes.entitySourceIndex .getIdsByEntry(source)!!.map { val entityDataById: WorkspaceEntityData<WorkspaceEntity> = this.entityDataById(it) as? WorkspaceEntityData<WorkspaceEntity> ?: run { reportErrorAndAttachStorage("Cannot find an entity by id $it", this@MutableEntityStorageImpl) error("Cannot find an entity by id $it") } entityDataById.wrapAsModifiable(this) } .groupBy { (it as WorkspaceEntityBase).getEntityInterface() } } } override fun <T : WorkspaceEntity> addEntity(entity: T) { try { lockWrite() entity as ModifiableWorkspaceEntityBase<T> entity.applyToBuilder(this) } finally { unlockWrite() } } // This should be removed or not extracted into the interface fun <T : WorkspaceEntity, D: ModifiableWorkspaceEntityBase<T>> putEntity(entity: D) { try { lockWrite() val newEntityData = entity.getEntityData() // Check for persistent id uniqueness assertUniquePersistentId(newEntityData) entitiesByType.add(newEntityData, entity.getEntityClass().toClassId()) // Add the change to changelog createAddEvent(newEntityData) // Update indexes indexes.entityAdded(newEntityData) } finally { unlockWrite() } } private fun <T : WorkspaceEntity> assertUniquePersistentId(pEntityData: WorkspaceEntityData<T>) { pEntityData.persistentId()?.let { persistentId -> val ids = indexes.persistentIdIndex.getIdsByEntry(persistentId) if (ids != null) { // Oh, oh. This persistent id exists already // Fallback strategy: remove existing entity with all it's references val existingEntityData = entityDataByIdOrDie(ids) val existingEntity = existingEntityData.createEntity(this) removeEntity(existingEntity) LOG.error( """ addEntity: persistent id already exists. Replacing entity with the new one. Persistent id: $persistentId Existing entity data: $existingEntityData New entity data: $pEntityData Broken consistency: $brokenConsistency """.trimIndent(), PersistentIdAlreadyExistsException(persistentId) ) if (throwExceptionOnError) { throw PersistentIdAlreadyExistsException(persistentId) } } } } @Suppress("UNCHECKED_CAST") override fun <M : ModifiableWorkspaceEntity<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T { try { lockWrite() val entityId = (e as WorkspaceEntityBase).id val originalEntityData = this.getOriginalEntityData(entityId) as WorkspaceEntityData<T> // Get entity data that will be modified val copiedData = entitiesByType.getEntityDataForModification(entityId) as WorkspaceEntityData<T> val modifiableEntity = copiedData.wrapAsModifiable(this) as M val beforePersistentId = if (e is WorkspaceEntityWithPersistentId) e.persistentId else null val originalParents = this.getOriginalParents(entityId.asChild()) val beforeParents = this.refs.getParentRefsOfChild(entityId.asChild()) val beforeChildren = this.refs.getChildrenRefsOfParentBy(entityId.asParent()).flatMap { (key, value) -> value.map { key to it } } // Execute modification code (modifiableEntity as ModifiableWorkspaceEntityBase<*>).allowModifications { modifiableEntity.change() } // Check for persistent id uniqueness if (beforePersistentId != null) { val newPersistentId = copiedData.persistentId() if (newPersistentId != null) { val ids = indexes.persistentIdIndex.getIdsByEntry(newPersistentId) if (beforePersistentId != newPersistentId && ids != null) { // Oh, oh. This persistent id exists already. // Remove an existing entity and replace it with the new one. val existingEntityData = entityDataByIdOrDie(ids) val existingEntity = existingEntityData.createEntity(this) removeEntity(existingEntity) LOG.error(""" modifyEntity: persistent id already exists. Replacing entity with the new one. Old entity: $existingEntityData Persistent id: $copiedData Broken consistency: $brokenConsistency """.trimIndent(), PersistentIdAlreadyExistsException(newPersistentId)) if (throwExceptionOnError) { throw PersistentIdAlreadyExistsException(newPersistentId) } } } else { LOG.error("Persistent id expected for entity: $copiedData") } } if (!modifiableEntity.changedProperty.contains("entitySource") || modifiableEntity.changedProperty.size > 1) { // Add an entry to changelog addReplaceEvent(this, entityId, beforeChildren, beforeParents, copiedData, originalEntityData, originalParents) } if (modifiableEntity.changedProperty.contains("entitySource")) { updateEntitySource(entityId, originalEntityData, copiedData) } val updatedEntity = copiedData.createEntity(this) this.indexes.updatePersistentIdIndexes(this, updatedEntity, beforePersistentId, copiedData, modifiableEntity) return updatedEntity } finally { unlockWrite() } } private fun <T : WorkspaceEntity> updateEntitySource(entityId: EntityId, originalEntityData: WorkspaceEntityData<T>, copiedEntityData: WorkspaceEntityData<T>) { val newSource = copiedEntityData.entitySource val originalSource = this.getOriginalSourceFromChangelog(entityId) ?: originalEntityData.entitySource this.changeLog.addChangeSourceEvent(entityId, copiedEntityData, originalSource) indexes.entitySourceIndex.index(entityId, newSource) newSource.virtualFileUrl?.let { indexes.virtualFileIndex.index(entityId, VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY, it) } } override fun removeEntity(e: WorkspaceEntity): Boolean { try { lockWrite() LOG.debug { "Removing ${e.javaClass}..." } e as WorkspaceEntityBase return removeEntityByEntityId(e.id) // NB: This method is called from `createEntity` inside persistent id checking. It's possible that after the method execution // the store is in inconsistent state, so we can't call assertConsistency here. } finally { unlockWrite() } } private fun getRbsEngine(): ReplaceBySourceOperation { if (useNewRbs) { return ReplaceBySourceAsTree() } else { return ReplaceBySourceAsGraph() } } /** * TODO Spacial cases: when source filter returns true for all entity sources. */ override fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: EntityStorage) { try { lockWrite() replaceWith as AbstractEntityStorage val rbsEngine = getRbsEngine() if (keepLastRbsEngine) { engine = rbsEngine } upgradeEngine?.let { it(rbsEngine) } rbsEngine.replace(this, replaceWith, sourceFilter) } finally { unlockWrite() } } override fun collectChanges(original: EntityStorage): Map<Class<*>, List<EntityChange<*>>> { try { lockWrite() val originalImpl = original as AbstractEntityStorage val res = HashMap<Class<*>, MutableList<EntityChange<*>>>() for ((entityId, change) in this.changeLog.changeLog) { when (change) { is ChangeEntry.AddEntity -> { val addedEntity = change.entityData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Added(addedEntity)) } is ChangeEntry.RemoveEntity -> { val removedData = originalImpl.entityDataById(change.id) ?: continue val removedEntity = removedData.createEntity(originalImpl) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Removed(removedEntity)) } is ChangeEntry.ReplaceEntity -> { @Suppress("DuplicatedCode") val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } is ChangeEntry.ChangeEntitySource -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } is ChangeEntry.ReplaceAndChangeSource -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.dataChange.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } } } return res } finally { unlockWrite() } } override fun toSnapshot(): EntityStorageSnapshot { val newEntities = entitiesByType.toImmutable() val newRefs = refs.toImmutable() val newIndexes = indexes.toImmutable() return EntityStorageSnapshotImpl(newEntities, newRefs, newIndexes) } override fun isEmpty(): Boolean = this.changeLog.changeLog.isEmpty() override fun addDiff(diff: MutableEntityStorage) { try { lockWrite() diff as MutableEntityStorageImpl applyDiffProtection(diff, "addDiff") AddDiffOperation(this, diff).addDiff() } finally { unlockWrite() } } @Suppress("UNCHECKED_CAST") override fun <T> getMutableExternalMapping(identifier: String): MutableExternalEntityMapping<T> { try { lockWrite() val mapping = indexes.externalMappings.computeIfAbsent( identifier) { MutableExternalEntityMappingImpl<T>() } as MutableExternalEntityMappingImpl<T> mapping.setTypedEntityStorage(this) return mapping } finally { unlockWrite() } } override fun getMutableVirtualFileUrlIndex(): MutableVirtualFileUrlIndex { try { lockWrite() val virtualFileIndex = indexes.virtualFileIndex virtualFileIndex.setTypedEntityStorage(this) return virtualFileIndex } finally { unlockWrite() } } internal fun addDiffAndReport(message: String, left: EntityStorage?, right: EntityStorage) { reportConsistencyIssue(message, AddDiffException(message), null, left, right, this) } private fun applyDiffProtection(diff: AbstractEntityStorage, method: String) { LOG.trace { "Applying $method. Builder: $diff" } if (diff.storageIsAlreadyApplied) { LOG.error("Builder is already applied.\n Info: \n${diff.applyInfo}") } else { diff.storageIsAlreadyApplied = true var info = "Applying builder using $method. Previous stack trace >>>>\n" if (LOG.isTraceEnabled) { val currentStackTrace = ExceptionUtil.currentStackTrace() info += "\n$currentStackTrace" } info += "<<<<" diff.applyInfo = info } } // modificationCount is not incremented internal fun removeEntityByEntityId(idx: EntityId, entityFilter: (EntityId) -> Boolean = { true }): Boolean { val accumulator: MutableSet<EntityId> = mutableSetOf(idx) if (!entitiesByType.exists(idx)) { return false } accumulateEntitiesToRemove(idx, accumulator, entityFilter) val originals = accumulator.associateWith { this.getOriginalEntityData(it) as WorkspaceEntityData<WorkspaceEntity> to this.getOriginalParents(it.asChild()) } for (id in accumulator) { val entityData = entityDataById(id) if (entityData is SoftLinkable) indexes.removeFromSoftLinksIndex(entityData) entitiesByType.remove(id.arrayId, id.clazz) } // Update index // Please don't join it with the previous loop for (id in accumulator) indexes.entityRemoved(id) accumulator.forEach { LOG.debug { "Cascade removing: ${ClassToIntConverter.INSTANCE.getClassOrDie(it.clazz)}-${it.arrayId}" } this.changeLog.addRemoveEvent(it, originals[it]!!.first, originals[it]!!.second) } return true } private fun lockWrite() { val currentThread = Thread.currentThread() if (writingFlag.getAndSet(true)) { if (threadId != null && threadId != currentThread.id) { LOG.error(""" Concurrent write to builder from the following threads First Thread: $threadName Second Thread: ${currentThread.name} Previous stack trace: $stackTrace """.trimIndent()) trackStackTrace = true } } if (trackStackTrace || LOG.isTraceEnabled) { stackTrace = ExceptionUtil.currentStackTrace() } threadId = currentThread.id threadName = currentThread.name } private fun unlockWrite() { writingFlag.set(false) stackTrace = null threadId = null threadName = null } internal fun <T : WorkspaceEntity> createAddEvent(pEntityData: WorkspaceEntityData<T>) { val entityId = pEntityData.createEntityId() this.changeLog.addAddEvent(entityId, pEntityData) } /** * Cleanup references and accumulate hard linked entities in [accumulator] */ private fun accumulateEntitiesToRemove(id: EntityId, accumulator: MutableSet<EntityId>, entityFilter: (EntityId) -> Boolean) { val children = refs.getChildrenRefsOfParentBy(id.asParent()) for ((connectionId, childrenIds) in children) { for (childId in childrenIds) { if (childId.id in accumulator) continue if (!entityFilter(childId.id)) continue accumulator.add(childId.id) accumulateEntitiesToRemove(childId.id, accumulator, entityFilter) refs.removeRefsByParent(connectionId, id.asParent()) } } val parents = refs.getParentRefsOfChild(id.asChild()) for ((connectionId, parent) in parents) { refs.removeParentToChildRef(connectionId, parent, id.asChild()) } } companion object { private val LOG = logger<MutableEntityStorageImpl>() fun create(): MutableEntityStorageImpl { return from(EntityStorageSnapshotImpl.EMPTY) } fun from(storage: EntityStorage): MutableEntityStorageImpl { storage as AbstractEntityStorage val newBuilder = when (storage) { is EntityStorageSnapshotImpl -> { val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType) val copiedRefs = MutableRefsTable.from(storage.refs) val copiedIndex = storage.indexes.toMutable() MutableEntityStorageImpl(copiedBarrel, copiedRefs, copiedIndex) } is MutableEntityStorageImpl -> { val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType.toImmutable()) val copiedRefs = MutableRefsTable.from(storage.refs.toImmutable()) val copiedIndexes = storage.indexes.toMutable() MutableEntityStorageImpl(copiedBarrel, copiedRefs, copiedIndexes, storage.trackStackTrace) } } LOG.trace { "Create new builder $newBuilder from $storage.\n${currentStackTrace(10)}" } return newBuilder } internal fun addReplaceEvent( builder: MutableEntityStorageImpl, entityId: EntityId, beforeChildren: List<Pair<ConnectionId, ChildEntityId>>, beforeParents: Map<ConnectionId, ParentEntityId>, copiedData: WorkspaceEntityData<out WorkspaceEntity>, originalEntity: WorkspaceEntityData<out WorkspaceEntity>, originalParents: Map<ConnectionId, ParentEntityId>, ) { val parents = builder.refs.getParentRefsOfChild(entityId.asChild()) val unmappedChildren = builder.refs.getChildrenRefsOfParentBy(entityId.asParent()) val children = unmappedChildren.flatMap { (key, value) -> value.map { key to it } } // Collect children changes val beforeChildrenSet = beforeChildren.toMutableSet() val (removedChildren, addedChildren) = getDiff(beforeChildrenSet, children) // Collect parent changes val parentsMapRes: MutableMap<ConnectionId, ParentEntityId?> = beforeParents.toMutableMap() for ((connectionId, parentId) in parents) { val existingParent = parentsMapRes[connectionId] if (existingParent != null) { if (existingParent == parentId) { parentsMapRes.remove(connectionId, parentId) } else { parentsMapRes[connectionId] = parentId } } else { parentsMapRes[connectionId] = parentId } } val removedKeys = beforeParents.keys - parents.keys removedKeys.forEach { parentsMapRes[it] = null } builder.changeLog.addReplaceEvent(entityId, copiedData, originalEntity, originalParents, addedChildren, removedChildren, parentsMapRes) } } } internal sealed class AbstractEntityStorage : EntityStorage { internal abstract val entitiesByType: EntitiesBarrel internal abstract val refs: AbstractRefsTable internal abstract val indexes: StorageIndexes internal var brokenConsistency: Boolean = false internal var storageIsAlreadyApplied = false internal var applyInfo: String? = null override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> { @Suppress("UNCHECKED_CAST") return entitiesByType[entityClass.toClassId()]?.all()?.map { it.createEntity(this) } as? Sequence<E> ?: emptySequence() } override fun <E : WorkspaceEntity> entitiesAmount(entityClass: Class<E>): Int { return entitiesByType[entityClass.toClassId()]?.size() ?: 0 } internal fun entityDataById(id: EntityId): WorkspaceEntityData<out WorkspaceEntity>? = entitiesByType[id.clazz]?.get(id.arrayId) internal fun entityDataByIdOrDie(id: EntityId): WorkspaceEntityData<out WorkspaceEntity> { val entityFamily = entitiesByType[id.clazz] ?: error( "Entity family doesn't exist or has no entities: ${id.clazz.findWorkspaceEntity()}") return entityFamily.get(id.arrayId) ?: error("Cannot find an entity by id $id") } override fun <E : WorkspaceEntity, R : WorkspaceEntity> referrers(e: E, entityClass: KClass<R>, property: KProperty1<R, EntityReference<E>>): Sequence<R> { TODO() //return entities(entityClass.java).filter { property.get(it).resolve(this) == e } } override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R> { val classId = entityClass.toClassId() @Suppress("UNCHECKED_CAST") return indexes.softLinks.getIdsByEntry(id).asSequence() .filter { it.clazz == classId } .map { entityDataByIdOrDie(it).createEntity(this) as R } } override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null @Suppress("UNCHECKED_CAST") return entityDataById(entityIds)?.createEntity(this) as E? } // Do not remove cast to Class<out TypedEntity>. kotlin fails without it @Suppress("USELESS_CAST") override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> { return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source -> indexes.entitySourceIndex .getIdsByEntry(source)!!.map { this.entityDataById(it)?.createEntity(this) ?: run { reportErrorAndAttachStorage("Cannot find an entity by id $it", this@AbstractEntityStorage) error("Cannot find an entity by id $it") } } .groupBy { (it as WorkspaceEntityBase).getEntityInterface() } } } @Suppress("UNCHECKED_CAST") override fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T> { val index = indexes.externalMappings[identifier] as? ExternalEntityMappingImpl<T> if (index == null) return EmptyExternalEntityMapping as ExternalEntityMapping<T> index.setTypedEntityStorage(this) return index } override fun getVirtualFileUrlIndex(): VirtualFileUrlIndex { indexes.virtualFileIndex.setTypedEntityStorage(this) return indexes.virtualFileIndex } override fun <E : WorkspaceEntity> createReference(e: E): EntityReference<E> = EntityReferenceImpl((e as WorkspaceEntityBase).id) internal fun assertConsistencyInStrictMode(message: String, sourceFilter: ((EntitySource) -> Boolean)?, left: EntityStorage?, right: EntityStorage?) { if (ConsistencyCheckingMode.current != ConsistencyCheckingMode.DISABLED) { try { this.assertConsistency() } catch (e: Throwable) { brokenConsistency = true val storage = if (this is MutableEntityStorage) this.toSnapshot() as AbstractEntityStorage else this val report = { reportConsistencyIssue(message, e, sourceFilter, left, right, storage) } if (ConsistencyCheckingMode.current == ConsistencyCheckingMode.ASYNCHRONOUS) { consistencyChecker.execute(report) } else { report() } } } } companion object { val LOG = logger<AbstractEntityStorage>() private val consistencyChecker = AppExecutorUtil.createBoundedApplicationPoolExecutor("Check workspace model consistency", 1) } } /** This function exposes `brokenConsistency` property to the outside and should be removed along with the property itself */ val EntityStorage.isConsistent: Boolean get() = !(this as AbstractEntityStorage).brokenConsistency
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
28,593
intellij-community
Apache License 2.0
cards-dto/src/main/kotlin/org/tsdes/cards/dto/Rarity.kt
BM0B0T
399,238,117
false
null
package org.tsdes.cards.dto enum class Rarity { BRONZE, SILVER, GOLD, PINK_DIAMOND }
0
Kotlin
0
1
55822f3a340d67d1dd3df535f9f64554cc06aac9
90
PG6100-Tasks
Apache License 2.0
todoapp/app/src/mock/java/com/example/android/architecture/blueprints/todoapp/data/FakeTasksRemoteDataSource.kt
SerjSmor
70,144,663
true
null
/* * 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 com.example.android.architecture.blueprints.todoapp.data import android.support.annotation.VisibleForTesting import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource import com.google.common.collect.Lists import java.util.* /** * Implementation of a remote data source with static access to the data for easy testing. */ class FakeTasksRemoteDataSource// Prevent direct instantiation. private constructor() : TasksDataSource { override fun getTasks(callback: TasksDataSource.LoadTasksCallback) { callback.onTasksLoaded(Lists.newArrayList(TASKS_SERVICE_DATA.values)) } override fun getTask(taskId: String, callback: TasksDataSource.GetTaskCallback) { val task = TASKS_SERVICE_DATA[taskId] callback.onTaskLoaded(task!!) } override fun saveTask(task: Task) { TASKS_SERVICE_DATA.put(task.id, task) } override fun completeTask(task: Task) { val completedTask = Task(task.title, task.description, task.id, true) TASKS_SERVICE_DATA.put(task.id, completedTask) } override fun completeTask(taskId: String) { // Not required for the remote data source. } override fun activateTask(task: Task) { val activeTask = Task(task.title, task.description, task.id) TASKS_SERVICE_DATA.put(task.id, activeTask) } override fun activateTask(taskId: String) { // Not required for the remote data source. } override fun clearCompletedTasks() { val it = TASKS_SERVICE_DATA.entries.iterator() while (it.hasNext()) { val entry = it.next() if (entry.value.isCompleted) { it.remove() } } } override fun refreshTasks() { // Not required because the {@link TasksRepository} handles the logic of refreshing the // tasks from all the available data sources. } override fun deleteTask(taskId: String) { TASKS_SERVICE_DATA.remove(taskId) } override fun deleteAllTasks() { TASKS_SERVICE_DATA.clear() } @VisibleForTesting fun addTasks(vararg tasks: Task) { for (task in tasks) { TASKS_SERVICE_DATA.put(task.id, task) } } companion object { private var INSTANCE: FakeTasksRemoteDataSource? = null private val TASKS_SERVICE_DATA = LinkedHashMap<String, Task>() val instance: FakeTasksRemoteDataSource get() { if (INSTANCE == null) { INSTANCE = FakeTasksRemoteDataSource() } return INSTANCE as FakeTasksRemoteDataSource } } }
0
Kotlin
1
21
e63f7aa426cb9460429fd046331df552bbc3839a
3,301
android-architecture
Apache License 2.0
clients/graphql-kotlin-client-gson/src/main/kotlin/com/expediagroup/graphql/client/gson/OptionalInput.kt
Wernerson
377,828,460
true
{"Kotlin": 1589698, "Mustache": 7027, "JavaScript": 3942, "HTML": 2744, "CSS": 297}
package com.expediagroup.graphql.client.gson import com.google.gson.TypeAdapter import com.google.gson.annotations.JsonAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter @JsonAdapter(OptionalInputTypeAdapter::class) sealed class OptionalInput<out T> { object Undefined : OptionalInput<Nothing>() { override fun toString(): String = "Undefined" } data class Defined<out U>(val value: U?) : OptionalInput<U>() } internal class OptionalInputTypeAdapter : TypeAdapter<OptionalInput<*>>() { override fun write(out: JsonWriter, value: OptionalInput<*>?) { when (value) { null -> out.nullValue() is OptionalInput.Defined -> out } } override fun read(`in`: JsonReader?): OptionalInput<*> { TODO("Not yet implemented") } }
0
Kotlin
0
0
8721e08773e34bc823775b13d689c3e4e391a0ce
843
graphql-kotlin
Apache License 2.0
src/main/kotlin/com/alcosi/nft/apigateway/service/multiWallet/HttpServiceMultiWalletProvider.kt
alcosi
713,491,219
false
{"Kotlin": 335209, "Java": 39800, "HTML": 4727, "PLpgSQL": 1275, "JavaScript": 1127, "CSS": 824}
/* * Copyright (c) 2023 Alcosi Group Ltd. 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.alcosi.nft.apigateway.service.multiWallet import com.alcosi.lib.utils.PrepareHexService import org.springframework.http.HttpMethod import org.springframework.web.reactive.function.client.WebClient import reactor.core.publisher.Mono /** * Represents a provider for retrieving wallet configurations from an HTTP service. * * @param hexService The instance of PrepareHexService used for preparing wallet addresses. * @param webClient The instance of WebClient used for making HTTP requests. * @param serviceAddress The address of the HTTP service. * @param httpMethod The HTTP method to be used for the request. */ open class HttpServiceMultiWalletProvider( protected val hexService: PrepareHexService, protected val webClient: WebClient, protected val serviceAddress: String, protected val httpMethod: HttpMethod, ) : MultiWalletProvider { /** * Retrieves the list of wallet configurations for a specific wallet. * * @param wallet The wallet identifier. * @return A Mono that emits the MultiWalletConfig object containing the list of wallets and the profile ID. */ override fun getWalletsListByWallet(wallet: String): Mono<MultiWalletProvider.MultiWalletConfig> { val rqUri = serviceAddress + hexService.prepareAddr(wallet) val httpRs = webClient .method(httpMethod) .uri(rqUri) .retrieve() return httpRs.bodyToMono(MultiWalletProvider.MultiWalletConfig::class.java) } }
0
Kotlin
0
0
ffa0409d568c8e4e05ee6aa1c3b83fd2c10954ca
2,149
alcosi_blockchain_api_gateway
Apache License 2.0
core/src/main/java/com/midnight/core/domain/ProductionCountriesModelCore.kt
alireza-87
455,999,190
false
null
package com.midnight.core.domain data class ProductionCountriesModelCore ( val iso31661 : String, val name : String?, )
0
Kotlin
0
1
61ca0bd902e9e7b1f03c35e9dd8bc60fb95891e4
132
movies_browser
MIT License
TenextllSDKDemo/app/src/main/java/com/tenext/demo/adapter/ListHolder.kt
wenext-ops
250,197,017
false
null
package com.tenext.demo.adapter import android.content.Context import android.view.ViewGroup import com.tenext.demo.holder.BaseHolder abstract class ListHolder<T : Any> : BaseHolder<T> { constructor(context: Context, root: ViewGroup, resLayout: Int) : super(context, root, resLayout) }
0
Kotlin
1
0
4266bd268686ab0bf6799ac0168967281fdc2051
291
LLForAndroid
MIT License
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/SpacingBetweenDeclarationsWithCommentsRule.kt
pinterest
64,293,719
false
null
package com.pinterest.ktlint.ruleset.standard.rules import com.pinterest.ktlint.rule.engine.core.api.AutocorrectDecision import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE import com.pinterest.ktlint.rule.engine.core.api.RuleId import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint.Status.EXPERIMENTAL import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint.Status.STABLE import com.pinterest.ktlint.rule.engine.core.api.ifAutocorrectAllowed import com.pinterest.ktlint.rule.engine.core.api.prevLeaf import com.pinterest.ktlint.rule.engine.core.api.prevSibling import com.pinterest.ktlint.ruleset.standard.StandardRule import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiComment import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.startOffset /** * @see https://youtrack.jetbrains.com/issue/KT-35088 */ @SinceKtlint("0.37", EXPERIMENTAL) @SinceKtlint("0.46", STABLE) public class SpacingBetweenDeclarationsWithCommentsRule : StandardRule("spacing-between-declarations-with-comments") { override fun beforeVisitChildNodes( node: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> AutocorrectDecision, ) { if (node is PsiComment) { val declaration = node.parent as? KtDeclaration ?: return val isTailComment = node.startOffset > declaration.startOffset if (isTailComment || declaration.getPrevSiblingIgnoringWhitespaceAndComments() !is KtDeclaration) return val prevSibling = declaration.node.prevSibling { it.elementType != WHITE_SPACE } if (prevSibling != null && prevSibling.elementType != FILE && prevSibling !is PsiComment ) { if (declaration.prevSibling is PsiWhiteSpace && declaration.prevSibling.text.count { it == '\n' } < 2) { emit( node.startOffset, "Declarations and declarations with comments should have an empty space between.", true, ).ifAutocorrectAllowed { val indent = node.prevLeaf()?.text?.trim('\n') ?: "" (declaration.prevSibling.node as LeafPsiElement).rawReplaceWithText("\n\n$indent") } } } } } } public val SPACING_BETWEEN_DECLARATIONS_WITH_COMMENTS_RULE_ID: RuleId = SpacingBetweenDeclarationsWithCommentsRule().ruleId
83
null
509
6,205
80c4d5d822d47bb7077a874ebb9105097f2eb1c2
2,920
ktlint
MIT License
src/rider/main/kotlin/previewer/AvaloniaPreviewerSession.kt
Keroosha
242,771,985
true
{"Kotlin": 39372, "C#": 2222}
package me.fornever.avaloniarider.previewer import com.jetbrains.rd.util.* import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.reactive.ISource import com.jetbrains.rd.util.reactive.Signal import kotlinx.coroutines.* import me.fornever.avaloniarider.bson.BsonStreamReader import me.fornever.avaloniarider.bson.BsonStreamWriter import me.fornever.avaloniarider.controlmessages.* import java.io.DataInputStream import java.net.ServerSocket import java.nio.file.Path import kotlin.io.use /** * Avalonia previewer session. * * @param serverSocket server socket to connect to the previewer. Will be owned * by the session (i.e. it will manage the socket lifetime). */ class AvaloniaPreviewerSession( private val serverSocket: ServerSocket, private val outputBinaryPath: Path) { companion object { private val logger = getLogger<AvaloniaPreviewerSession>() } private val sessionStartedSignal = Signal<StartDesignerSessionMessage>() private val requestViewportResizeSignal = Signal<RequestViewportResizeMessage>() private val frameSignal = Signal<FrameMessage>() private val updateXamlResultSignal = Signal<UpdateXamlResultMessage>() // TODO[F]: Show error message in the editor control (#41) val sessionStarted: ISource<StartDesignerSessionMessage> = sessionStartedSignal val requestViewportResize: ISource<RequestViewportResizeMessage> = requestViewportResizeSignal val frame: ISource<FrameMessage> = frameSignal val updateXamlResult: ISource<UpdateXamlResultMessage> = updateXamlResultSignal private lateinit var reader: BsonStreamReader private lateinit var writer: BsonStreamWriter fun processSocketMessages() { Lifetime.using { lifetime -> val avaloniaMessages = AvaloniaMessages.getInstance() serverSocket.use { serverSocket -> val socket = serverSocket.accept() serverSocket.close() socket.use { socket.getInputStream().use { DataInputStream(it).use { input -> socket.getOutputStream().use { output -> writer = BsonStreamWriter(lifetime, avaloniaMessages.outgoingTypeRegistry, output) reader = BsonStreamReader(avaloniaMessages.incomingTypeRegistry, input) while (!socket.isClosed) { val message = reader.readMessage() if (message == null) { logger.info { "Message == null received, terminating the connection" } return } handleMessage(message as AvaloniaMessage) } } } } } } } } fun sendClientSupportedPixelFormat() { writer.startSendMessage(ClientSupportedPixelFormatsMessage(intArrayOf(1))) } fun sendDpi(dpi: Double) { writer.startSendMessage(ClientRenderInfoMessage(dpi, dpi)) } fun sendXamlUpdate(content: String, xamlFilePathInsideProject: String) { val message = UpdateXamlMessage(content, outputBinaryPath.toString(), xamlFilePathInsideProject) writer.startSendMessage(message) } fun sendFrameAcknowledgement(frame: FrameMessage) { writer.startSendMessage(FrameReceivedMessage(frame.sequenceId)) } private fun handleMessage(message: AvaloniaMessage) { logger.trace { "Received message: $message" } when (message) { is StartDesignerSessionMessage -> sessionStartedSignal.fire(message) is UpdateXamlResultMessage -> { updateXamlResultSignal.fire(message) message.error?.let { // TODO[F]: Lower the priority to INFO since these errors are part of standard workflow (#41) logger.warn { "Error from UpdateXamlResultMessage: $it" } } } is RequestViewportResizeMessage -> requestViewportResizeSignal.fire(message) is FrameMessage -> frameSignal.fire(message) else -> logger.warn { "Message ignored: $message" } } } }
0
null
0
0
df39cdfff39b02e2dba23e6da44a41309cd6eee4
4,410
AvaloniaRider
MIT License
src/main/kotlin/com/github/pemistahl/lingua/api/Language.kt
pemistahl
157,676,060
false
null
/* * Copyright © 2018-today Peter M. Stahl [email protected] * * 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 expressed or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pemistahl.lingua.api import com.github.pemistahl.lingua.api.IsoCode639_1.AF import com.github.pemistahl.lingua.api.IsoCode639_1.AM import com.github.pemistahl.lingua.api.IsoCode639_1.AR import com.github.pemistahl.lingua.api.IsoCode639_1.AZ import com.github.pemistahl.lingua.api.IsoCode639_1.BE import com.github.pemistahl.lingua.api.IsoCode639_1.BG import com.github.pemistahl.lingua.api.IsoCode639_1.BN import com.github.pemistahl.lingua.api.IsoCode639_1.BS import com.github.pemistahl.lingua.api.IsoCode639_1.CA import com.github.pemistahl.lingua.api.IsoCode639_1.CS import com.github.pemistahl.lingua.api.IsoCode639_1.CY import com.github.pemistahl.lingua.api.IsoCode639_1.DA import com.github.pemistahl.lingua.api.IsoCode639_1.DE import com.github.pemistahl.lingua.api.IsoCode639_1.EL import com.github.pemistahl.lingua.api.IsoCode639_1.EN import com.github.pemistahl.lingua.api.IsoCode639_1.EO import com.github.pemistahl.lingua.api.IsoCode639_1.ES import com.github.pemistahl.lingua.api.IsoCode639_1.ET import com.github.pemistahl.lingua.api.IsoCode639_1.EU import com.github.pemistahl.lingua.api.IsoCode639_1.FA import com.github.pemistahl.lingua.api.IsoCode639_1.FI import com.github.pemistahl.lingua.api.IsoCode639_1.FR import com.github.pemistahl.lingua.api.IsoCode639_1.GA import com.github.pemistahl.lingua.api.IsoCode639_1.GU import com.github.pemistahl.lingua.api.IsoCode639_1.HE import com.github.pemistahl.lingua.api.IsoCode639_1.HI import com.github.pemistahl.lingua.api.IsoCode639_1.HR import com.github.pemistahl.lingua.api.IsoCode639_1.HU import com.github.pemistahl.lingua.api.IsoCode639_1.HY import com.github.pemistahl.lingua.api.IsoCode639_1.ID import com.github.pemistahl.lingua.api.IsoCode639_1.IS import com.github.pemistahl.lingua.api.IsoCode639_1.IT import com.github.pemistahl.lingua.api.IsoCode639_1.JA import com.github.pemistahl.lingua.api.IsoCode639_1.KA import com.github.pemistahl.lingua.api.IsoCode639_1.KK import com.github.pemistahl.lingua.api.IsoCode639_1.KO import com.github.pemistahl.lingua.api.IsoCode639_1.LA import com.github.pemistahl.lingua.api.IsoCode639_1.LG import com.github.pemistahl.lingua.api.IsoCode639_1.LT import com.github.pemistahl.lingua.api.IsoCode639_1.LV import com.github.pemistahl.lingua.api.IsoCode639_1.MI import com.github.pemistahl.lingua.api.IsoCode639_1.MK import com.github.pemistahl.lingua.api.IsoCode639_1.MN import com.github.pemistahl.lingua.api.IsoCode639_1.MR import com.github.pemistahl.lingua.api.IsoCode639_1.MS import com.github.pemistahl.lingua.api.IsoCode639_1.NB import com.github.pemistahl.lingua.api.IsoCode639_1.NL import com.github.pemistahl.lingua.api.IsoCode639_1.NN import com.github.pemistahl.lingua.api.IsoCode639_1.OM import com.github.pemistahl.lingua.api.IsoCode639_1.PA import com.github.pemistahl.lingua.api.IsoCode639_1.PL import com.github.pemistahl.lingua.api.IsoCode639_1.PT import com.github.pemistahl.lingua.api.IsoCode639_1.RO import com.github.pemistahl.lingua.api.IsoCode639_1.RU import com.github.pemistahl.lingua.api.IsoCode639_1.SI import com.github.pemistahl.lingua.api.IsoCode639_1.SK import com.github.pemistahl.lingua.api.IsoCode639_1.SL import com.github.pemistahl.lingua.api.IsoCode639_1.SN import com.github.pemistahl.lingua.api.IsoCode639_1.SO import com.github.pemistahl.lingua.api.IsoCode639_1.SQ import com.github.pemistahl.lingua.api.IsoCode639_1.SR import com.github.pemistahl.lingua.api.IsoCode639_1.ST import com.github.pemistahl.lingua.api.IsoCode639_1.SV import com.github.pemistahl.lingua.api.IsoCode639_1.SW import com.github.pemistahl.lingua.api.IsoCode639_1.TA import com.github.pemistahl.lingua.api.IsoCode639_1.TE import com.github.pemistahl.lingua.api.IsoCode639_1.TH import com.github.pemistahl.lingua.api.IsoCode639_1.TI import com.github.pemistahl.lingua.api.IsoCode639_1.TL import com.github.pemistahl.lingua.api.IsoCode639_1.TN import com.github.pemistahl.lingua.api.IsoCode639_1.TR import com.github.pemistahl.lingua.api.IsoCode639_1.TS import com.github.pemistahl.lingua.api.IsoCode639_1.UK import com.github.pemistahl.lingua.api.IsoCode639_1.UR import com.github.pemistahl.lingua.api.IsoCode639_1.VI import com.github.pemistahl.lingua.api.IsoCode639_1.XH import com.github.pemistahl.lingua.api.IsoCode639_1.YO import com.github.pemistahl.lingua.api.IsoCode639_1.ZH import com.github.pemistahl.lingua.api.IsoCode639_1.ZU import com.github.pemistahl.lingua.api.IsoCode639_3.AFR import com.github.pemistahl.lingua.api.IsoCode639_3.AMH import com.github.pemistahl.lingua.api.IsoCode639_3.ARA import com.github.pemistahl.lingua.api.IsoCode639_3.AZE import com.github.pemistahl.lingua.api.IsoCode639_3.BEL import com.github.pemistahl.lingua.api.IsoCode639_3.BEN import com.github.pemistahl.lingua.api.IsoCode639_3.BOS import com.github.pemistahl.lingua.api.IsoCode639_3.BUL import com.github.pemistahl.lingua.api.IsoCode639_3.CAT import com.github.pemistahl.lingua.api.IsoCode639_3.CES import com.github.pemistahl.lingua.api.IsoCode639_3.CYM import com.github.pemistahl.lingua.api.IsoCode639_3.DAN import com.github.pemistahl.lingua.api.IsoCode639_3.DEU import com.github.pemistahl.lingua.api.IsoCode639_3.ELL import com.github.pemistahl.lingua.api.IsoCode639_3.ENG import com.github.pemistahl.lingua.api.IsoCode639_3.EPO import com.github.pemistahl.lingua.api.IsoCode639_3.EST import com.github.pemistahl.lingua.api.IsoCode639_3.EUS import com.github.pemistahl.lingua.api.IsoCode639_3.FAS import com.github.pemistahl.lingua.api.IsoCode639_3.FIN import com.github.pemistahl.lingua.api.IsoCode639_3.FRA import com.github.pemistahl.lingua.api.IsoCode639_3.GLE import com.github.pemistahl.lingua.api.IsoCode639_3.GUJ import com.github.pemistahl.lingua.api.IsoCode639_3.HEB import com.github.pemistahl.lingua.api.IsoCode639_3.HIN import com.github.pemistahl.lingua.api.IsoCode639_3.HRV import com.github.pemistahl.lingua.api.IsoCode639_3.HUN import com.github.pemistahl.lingua.api.IsoCode639_3.HYE import com.github.pemistahl.lingua.api.IsoCode639_3.IND import com.github.pemistahl.lingua.api.IsoCode639_3.ISL import com.github.pemistahl.lingua.api.IsoCode639_3.ITA import com.github.pemistahl.lingua.api.IsoCode639_3.JPN import com.github.pemistahl.lingua.api.IsoCode639_3.KAT import com.github.pemistahl.lingua.api.IsoCode639_3.KAZ import com.github.pemistahl.lingua.api.IsoCode639_3.KOR import com.github.pemistahl.lingua.api.IsoCode639_3.LAT import com.github.pemistahl.lingua.api.IsoCode639_3.LAV import com.github.pemistahl.lingua.api.IsoCode639_3.LIT import com.github.pemistahl.lingua.api.IsoCode639_3.LUG import com.github.pemistahl.lingua.api.IsoCode639_3.MAR import com.github.pemistahl.lingua.api.IsoCode639_3.MKD import com.github.pemistahl.lingua.api.IsoCode639_3.MON import com.github.pemistahl.lingua.api.IsoCode639_3.MRI import com.github.pemistahl.lingua.api.IsoCode639_3.MSA import com.github.pemistahl.lingua.api.IsoCode639_3.NLD import com.github.pemistahl.lingua.api.IsoCode639_3.NNO import com.github.pemistahl.lingua.api.IsoCode639_3.NOB import com.github.pemistahl.lingua.api.IsoCode639_3.ORM import com.github.pemistahl.lingua.api.IsoCode639_3.PAN import com.github.pemistahl.lingua.api.IsoCode639_3.POL import com.github.pemistahl.lingua.api.IsoCode639_3.POR import com.github.pemistahl.lingua.api.IsoCode639_3.RON import com.github.pemistahl.lingua.api.IsoCode639_3.RUS import com.github.pemistahl.lingua.api.IsoCode639_3.SIN import com.github.pemistahl.lingua.api.IsoCode639_3.SLK import com.github.pemistahl.lingua.api.IsoCode639_3.SLV import com.github.pemistahl.lingua.api.IsoCode639_3.SNA import com.github.pemistahl.lingua.api.IsoCode639_3.SOM import com.github.pemistahl.lingua.api.IsoCode639_3.SOT import com.github.pemistahl.lingua.api.IsoCode639_3.SPA import com.github.pemistahl.lingua.api.IsoCode639_3.SQI import com.github.pemistahl.lingua.api.IsoCode639_3.SRP import com.github.pemistahl.lingua.api.IsoCode639_3.SWA import com.github.pemistahl.lingua.api.IsoCode639_3.SWE import com.github.pemistahl.lingua.api.IsoCode639_3.TAM import com.github.pemistahl.lingua.api.IsoCode639_3.TEL import com.github.pemistahl.lingua.api.IsoCode639_3.TGL import com.github.pemistahl.lingua.api.IsoCode639_3.THA import com.github.pemistahl.lingua.api.IsoCode639_3.TIR import com.github.pemistahl.lingua.api.IsoCode639_3.TSN import com.github.pemistahl.lingua.api.IsoCode639_3.TSO import com.github.pemistahl.lingua.api.IsoCode639_3.TUR import com.github.pemistahl.lingua.api.IsoCode639_3.UKR import com.github.pemistahl.lingua.api.IsoCode639_3.URD import com.github.pemistahl.lingua.api.IsoCode639_3.VIE import com.github.pemistahl.lingua.api.IsoCode639_3.XHO import com.github.pemistahl.lingua.api.IsoCode639_3.YOR import com.github.pemistahl.lingua.api.IsoCode639_3.ZHO import com.github.pemistahl.lingua.api.IsoCode639_3.ZUL import com.github.pemistahl.lingua.internal.Alphabet import com.github.pemistahl.lingua.internal.Alphabet.CYRILLIC import com.github.pemistahl.lingua.internal.Alphabet.DEVANAGARI import com.github.pemistahl.lingua.internal.Alphabet.ETHIOPIC import com.github.pemistahl.lingua.internal.Alphabet.GURMUKHI import com.github.pemistahl.lingua.internal.Alphabet.HAN import com.github.pemistahl.lingua.internal.Alphabet.HANGUL import com.github.pemistahl.lingua.internal.Alphabet.HIRAGANA import com.github.pemistahl.lingua.internal.Alphabet.KATAKANA import com.github.pemistahl.lingua.internal.Alphabet.LATIN import com.github.pemistahl.lingua.internal.Alphabet.NONE import com.github.pemistahl.lingua.internal.util.extension.enumSetOf import java.util.EnumSet /** * The supported detectable languages. */ enum class Language( val isoCode639_1: IsoCode639_1, val isoCode639_3: IsoCode639_3, internal val alphabets: EnumSet<Alphabet>, internal val uniqueCharacters: String?, ) { AFRIKAANS(AF, AFR, enumSetOf(Alphabet.LATIN), null), ALBANIAN(SQ, SQI, enumSetOf(Alphabet.LATIN), null), AMHARIC(AM, AMH, enumSetOf(Alphabet.ETHIOPIC), null), ARABIC(AR, ARA, enumSetOf(Alphabet.ARABIC), null), ARMENIAN(HY, HYE, enumSetOf(Alphabet.ARMENIAN), null), AZERBAIJANI(AZ, AZE, enumSetOf(Alphabet.LATIN), "Əə"), BASQUE(EU, EUS, enumSetOf(Alphabet.LATIN), null), BELARUSIAN(BE, BEL, enumSetOf(CYRILLIC), null), BENGALI(BN, BEN, enumSetOf(Alphabet.BENGALI), null), BOKMAL(NB, NOB, enumSetOf(Alphabet.LATIN), null), BOSNIAN(BS, BOS, enumSetOf(Alphabet.LATIN), null), BULGARIAN(BG, BUL, enumSetOf(CYRILLIC), null), CATALAN(CA, CAT, enumSetOf(Alphabet.LATIN), "Ïï"), CHINESE(ZH, ZHO, enumSetOf(HAN), null), CROATIAN(HR, HRV, enumSetOf(Alphabet.LATIN), null), CZECH(CS, CES, enumSetOf(Alphabet.LATIN), "ĚěŘřŮů"), DANISH(DA, DAN, enumSetOf(Alphabet.LATIN), null), DUTCH(NL, NLD, enumSetOf(Alphabet.LATIN), null), ENGLISH(EN, ENG, enumSetOf(Alphabet.LATIN), null), ESPERANTO(EO, EPO, enumSetOf(Alphabet.LATIN), "ĈĉĜĝĤĥĴĵŜŝŬŭ"), ESTONIAN(ET, EST, enumSetOf(Alphabet.LATIN), null), FINNISH(FI, FIN, enumSetOf(Alphabet.LATIN), null), FRENCH(FR, FRA, enumSetOf(Alphabet.LATIN), null), GANDA(LG, LUG, enumSetOf(Alphabet.LATIN), null), GEORGIAN(KA, KAT, enumSetOf(Alphabet.GEORGIAN), null), GERMAN(DE, DEU, enumSetOf(Alphabet.LATIN), "ß"), GREEK(EL, ELL, enumSetOf(Alphabet.GREEK), null), GUJARATI(GU, GUJ, enumSetOf(Alphabet.GUJARATI), null), HEBREW(HE, HEB, enumSetOf(Alphabet.HEBREW), null), HINDI(HI, HIN, enumSetOf(DEVANAGARI), null), HUNGARIAN(HU, HUN, enumSetOf(Alphabet.LATIN), "ŐőŰű"), ICELANDIC(IS, ISL, enumSetOf(Alphabet.LATIN), null), INDONESIAN(ID, IND, enumSetOf(Alphabet.LATIN), null), IRISH(GA, GLE, enumSetOf(Alphabet.LATIN), null), ITALIAN(IT, ITA, enumSetOf(Alphabet.LATIN), null), JAPANESE(JA, JPN, enumSetOf(HIRAGANA, KATAKANA, HAN), null), KAZAKH(KK, KAZ, enumSetOf(CYRILLIC), "ӘәҒғҚқҢңҰұ"), KOREAN(KO, KOR, enumSetOf(HANGUL), null), LATIN(LA, LAT, enumSetOf(Alphabet.LATIN), null), LATVIAN(LV, LAV, enumSetOf(Alphabet.LATIN), "ĢģĶķĻļŅņ"), LITHUANIAN(LT, LIT, enumSetOf(Alphabet.LATIN), "ĖėĮįŲų"), MACEDONIAN(MK, MKD, enumSetOf(CYRILLIC), "ЃѓЅѕЌќЏџ"), MALAY(MS, MSA, enumSetOf(Alphabet.LATIN), null), MAORI(MI, MRI, enumSetOf(Alphabet.LATIN), null), MARATHI(MR, MAR, enumSetOf(DEVANAGARI), "ळ"), MONGOLIAN(MN, MON, enumSetOf(CYRILLIC), "ӨөҮү"), NYNORSK(NN, NNO, enumSetOf(Alphabet.LATIN), null), OROMO(OM, ORM, enumSetOf(Alphabet.LATIN), null), PERSIAN(FA, FAS, enumSetOf(Alphabet.ARABIC), null), POLISH(PL, POL, enumSetOf(Alphabet.LATIN), "ŁłŃńŚśŹź"), PORTUGUESE(PT, POR, enumSetOf(Alphabet.LATIN), null), PUNJABI(PA, PAN, enumSetOf(GURMUKHI), null), ROMANIAN(RO, RON, enumSetOf(Alphabet.LATIN), "Țţ"), RUSSIAN(RU, RUS, enumSetOf(CYRILLIC), null), SERBIAN(SR, SRP, enumSetOf(CYRILLIC), "ЂђЋћ"), SHONA(SN, SNA, enumSetOf(Alphabet.LATIN), null), SINHALA(SI, SIN, enumSetOf(Alphabet.SINHALA), null), SLOVAK(SK, SLK, enumSetOf(Alphabet.LATIN), "Ĺ弾Ŕŕ"), SLOVENE(SL, SLV, enumSetOf(Alphabet.LATIN), null), SOMALI(SO, SOM, enumSetOf(Alphabet.LATIN), null), SOTHO(ST, SOT, enumSetOf(Alphabet.LATIN), null), SPANISH(ES, SPA, enumSetOf(Alphabet.LATIN), "¿¡"), SWAHILI(SW, SWA, enumSetOf(Alphabet.LATIN), null), SWEDISH(SV, SWE, enumSetOf(Alphabet.LATIN), null), TAGALOG(TL, TGL, enumSetOf(Alphabet.LATIN), null), TAMIL(TA, TAM, enumSetOf(Alphabet.TAMIL), null), TELUGU(TE, TEL, enumSetOf(Alphabet.TELUGU), null), THAI(TH, THA, enumSetOf(Alphabet.THAI), null), TIGRINYA(TI, TIR, enumSetOf(Alphabet.ETHIOPIC), null), TSONGA(TS, TSO, enumSetOf(Alphabet.LATIN), null), TSWANA(TN, TSN, enumSetOf(Alphabet.LATIN), null), TURKISH(TR, TUR, enumSetOf(Alphabet.LATIN), null), UKRAINIAN(UK, UKR, enumSetOf(CYRILLIC), "ҐґЄєЇї"), URDU(UR, URD, enumSetOf(Alphabet.ARABIC), null), VIETNAMESE( VI, VIE, enumSetOf(Alphabet.LATIN), "ẰằẦầẲẳẨẩẴẵẪẫẮắẤấẠạẶặẬậỀềẺẻỂểẼẽỄễẾếỆệỈỉĨĩỊịƠơỒồỜờỎỏỔổỞởỖỗỠỡỐốỚớỘộỢợƯưỪừỦủỬửŨũỮữỨứỤụỰựỲỳỶỷỸỹỴỵ", ), WELSH(CY, CYM, enumSetOf(Alphabet.LATIN), null), XHOSA(XH, XHO, enumSetOf(Alphabet.LATIN), null), // TODO for YORUBA: "E̩e̩Ẹ́ẹ́É̩é̩Ẹ̀ẹ̀È̩è̩Ẹ̄ẹ̄Ē̩ē̩ŌōO̩o̩Ọ́ọ́Ó̩ó̩Ọ̀ọ̀Ò̩ò̩Ọ̄ọ̄Ō̩ō̩ṢṣS̩s̩" YORUBA(YO, YOR, enumSetOf(Alphabet.LATIN), "Ṣṣ"), ZULU(ZU, ZUL, enumSetOf(Alphabet.LATIN), null), /** * The imaginary unknown language. * * This value is returned if no language can be detected reliably. */ UNKNOWN(IsoCode639_1.NONE, IsoCode639_3.NONE, enumSetOf(NONE), null), ; companion object { /** * Returns a list of all built-in languages. */ @JvmStatic fun all(): List<Language> = filterOutLanguages(UNKNOWN) /** * Returns a list of all built-in languages that are still spoken today. */ @JvmStatic fun allSpokenOnes(): List<Language> = filterOutLanguages(UNKNOWN, LATIN) /** * Returns a list of all built-in languages supporting the Arabic script. */ @JvmStatic fun allWithArabicScript(): List<Language> = values().filter { it.alphabets.contains(Alphabet.ARABIC) } /** * Returns a list of all built-in languages supporting the Cyrillic script. */ @JvmStatic fun allWithCyrillicScript(): List<Language> = values().filter { it.alphabets.contains(CYRILLIC) } /** * Returns a list of all built-in languages supporting the Devanagari script. */ @JvmStatic fun allWithDevanagariScript(): List<Language> = values().filter { it.alphabets.contains(DEVANAGARI) } /** * Returns a list of all built-in languages supporting the Ethiopic script. */ @JvmStatic fun allWithEthiopicScript(): List<Language> = values().filter { it.alphabets.contains(ETHIOPIC) } /** * Returns a list of all built-in languages supporting the Latin script. */ @JvmStatic fun allWithLatinScript(): List<Language> = values().filter { it.alphabets.contains(Alphabet.LATIN) } /** * Returns the language for the given ISO 639-1 code. */ @JvmStatic @Suppress("ktlint:standard:function-naming") fun getByIsoCode639_1(isoCode: IsoCode639_1): Language = values().first { it.isoCode639_1 == isoCode } /** * Returns the language for the given ISO 639-3 code. */ @JvmStatic @Suppress("ktlint:standard:function-naming") fun getByIsoCode639_3(isoCode: IsoCode639_3): Language = values().first { it.isoCode639_3 == isoCode } private fun filterOutLanguages(vararg languages: Language) = values().filterNot { it in languages } } }
6
null
63
703
6f990b7bded90d754696c4858452ab3cb9fe9ce8
17,429
lingua
Apache License 2.0
libs/shape/src/main/kotlin/mono/shape/connector/LineConnector.kt
tuanchauict
325,686,408
false
null
/* * Copyright (c) 2023, tuanchauict */ package mono.shape.connector import mono.graphics.geo.Point import mono.graphics.geo.PointF import mono.shape.collection.Identifier import mono.shape.shape.Line /** * A connector for [Line]. * * @param line The target of this connector * @param anchor The extra information for identifying which head of the line (start or end) * @param ratio The relative position of the connector based on the size of the box. * @param offset The absolute offset of the connector to the box */ class LineConnector( val line: Line, val anchor: Line.Anchor, val ratio: PointF, val offset: Point ) : Identifier by ConnectorIdentifier(line, anchor) { /** * A [Identifier] of Line's connector. * This is a minimal version of [LineConnector] that only has required information to identify * the connector. */ class ConnectorIdentifier(line: Line, anchor: Line.Anchor) : Identifier { override val id: String = toId(line, anchor) } companion object { fun toId(line: Line, anchor: Line.Anchor): String = "${line.id}@@${anchor.ordinal}" } }
11
Kotlin
1
129
624b287a2f13bf66fa98d81ae8c4b55d0f6c188b
1,142
MonoSketch
Apache License 2.0
app/src/main/java/com/sakethh/linkora/ui/screens/settings/specific/advanced/site_specific_user_agent/SiteSpecificUserAgentScreenVM.kt
sakethpathike
648,784,316
false
{"Kotlin": 1590874}
package com.sakethh.linkora.ui.screens.settings.specific.advanced.site_specific_user_agent import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.sakethh.linkora.data.local.SiteSpecificUserAgent import com.sakethh.linkora.data.local.links.LinksRepo import com.sakethh.linkora.data.local.site_specific_user_agent.SiteSpecificUserAgentRepo import com.sakethh.linkora.ui.CommonUiEvent import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SiteSpecificUserAgentScreenVM @Inject constructor( private val siteSpecificUserAgentRepo: SiteSpecificUserAgentRepo, private val linksRepo: LinksRepo ) : ViewModel() { private val _allSiteSpecificUserAgents = MutableStateFlow(emptyList<SiteSpecificUserAgent>()) val allSiteSpecificUserAgents = _allSiteSpecificUserAgents.asStateFlow() private val _uiEvent = Channel<CommonUiEvent>() val uiEvent = _uiEvent.receiveAsFlow() init { viewModelScope.launch { siteSpecificUserAgentRepo.getAllSiteSpecificUserAgent().collectLatest { _allSiteSpecificUserAgents.emit(it) } } } fun addANewSiteSpecificUserAgent(domain: String, userAgent: String) { viewModelScope.launch { if (siteSpecificUserAgentRepo.doesThisDomainExists(domain)) { _uiEvent.send(CommonUiEvent.ShowToast("given domain already exists")) } else { siteSpecificUserAgentRepo.addANewSiteSpecificUserAgent( siteSpecificUserAgent = SiteSpecificUserAgent( domain, userAgent ) ) updateUserAgentInLinkBasedTables(domain, userAgent) _uiEvent.send(CommonUiEvent.ShowToast("added the given domain successfully")) } } } fun deleteASiteSpecificUserAgent(domain: String) { viewModelScope.launch { siteSpecificUserAgentRepo.deleteASiteSpecificUserAgent( domain ) updateUserAgentInLinkBasedTables(domain = domain, newUserAgent = null) } } fun updateASpecificUserAgent(domain: String, newUserAgent: String) { viewModelScope.launch { siteSpecificUserAgentRepo.updateASpecificUserAgent(domain, newUserAgent) updateUserAgentInLinkBasedTables(domain, newUserAgent) } } private suspend fun updateUserAgentInLinkBasedTables(domain: String, newUserAgent: String?) { linksRepo.changeUserAgentInLinksTable(newUserAgent, domain) linksRepo.changeUserAgentInArchiveLinksTable(newUserAgent, domain) linksRepo.changeUserAgentInImportantLinksTable(newUserAgent, domain) linksRepo.changeUserAgentInHistoryTable(newUserAgent, domain) } }
9
Kotlin
11
307
ebbd4669a8e762587267560f60d0ec3339e9e75f
3,118
Linkora
MIT License
android/src/main/kotlin/com/difrancescogianmarco/arcore_flutter_plugin/ArCoreAugmentedImagesView.kt
giandifra
183,178,383
false
null
package com.difrancescogianmarco.arcore_flutter_plugin import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import android.util.Pair import com.difrancescogianmarco.arcore_flutter_plugin.flutter_models.FlutterArCoreNode import com.difrancescogianmarco.arcore_flutter_plugin.flutter_models.FlutterArCorePose import com.difrancescogianmarco.arcore_flutter_plugin.utils.ArCoreUtils import com.google.ar.core.AugmentedImage import com.google.ar.core.AugmentedImageDatabase import com.google.ar.core.Config import com.google.ar.core.TrackingState import com.google.ar.core.exceptions.CameraNotAvailableException import com.google.ar.core.exceptions.UnavailableException import com.google.ar.sceneform.AnchorNode import com.google.ar.sceneform.Scene import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import java.io.ByteArrayInputStream import java.io.IOException import java.util.* import com.google.ar.core.exceptions.* import com.google.ar.core.* import kotlinx.coroutines.* import kotlin.coroutines.CoroutineContext class ArCoreAugmentedImagesView(activity: Activity, context: Context, messenger: BinaryMessenger, id: Int, val useSingleImage: Boolean, debug: Boolean) : BaseArCoreView(activity, context, messenger, id, debug), CoroutineScope { private val TAG: String = ArCoreAugmentedImagesView::class.java.name private var sceneUpdateListener: Scene.OnUpdateListener // Augmented image and its associated center pose anchor, keyed by index of the augmented image in // the // database. private val augmentedImageMap = HashMap<Int, Pair<AugmentedImage, AnchorNode>>() private var job: Job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job init { sceneUpdateListener = Scene.OnUpdateListener { frameTime -> val frame = arSceneView?.arFrame ?: return@OnUpdateListener // If there is no frame or ARCore is not tracking yet, just return. if (frame.camera.trackingState != TrackingState.TRACKING) { return@OnUpdateListener } val updatedAugmentedImages = frame.getUpdatedTrackables(AugmentedImage::class.java) for (augmentedImage in updatedAugmentedImages) { when (augmentedImage.trackingState) { TrackingState.PAUSED -> { val text = String.format("Detected Image %d", augmentedImage.index) debugLog( text) } TrackingState.TRACKING -> { debugLog( "${augmentedImage.name} ${augmentedImage.trackingMethod}") if (!augmentedImageMap.containsKey(augmentedImage.index)) { debugLog( "${augmentedImage.name} ASSENTE") val centerPoseAnchor = augmentedImage.createAnchor(augmentedImage.centerPose) val anchorNode = AnchorNode() anchorNode.anchor = centerPoseAnchor augmentedImageMap[augmentedImage.index] = Pair.create(augmentedImage, anchorNode) } sendAugmentedImageToFlutter(augmentedImage) } TrackingState.STOPPED -> { debugLog( "STOPPED: ${augmentedImage.name}") val anchorNode = augmentedImageMap[augmentedImage.index]!!.second augmentedImageMap.remove(augmentedImage.index) arSceneView?.scene?.removeChild(anchorNode) val text = String.format("Removed Image %d", augmentedImage.index) debugLog( text) } else -> { } } } } } private fun sendAugmentedImageToFlutter(augmentedImage: AugmentedImage) { val map: HashMap<String, Any> = HashMap<String, Any>() map["name"] = augmentedImage.name map["index"] = augmentedImage.index map["extentX"] = augmentedImage.extentX map["extentZ"] = augmentedImage.extentZ map["centerPose"] = FlutterArCorePose.fromPose(augmentedImage.centerPose).toHashMap() map["trackingMethod"] = augmentedImage.trackingMethod.ordinal activity.runOnUiThread { methodChannel.invokeMethod("onTrackingImage", map) } } /* fun setImage(image: AugmentedImage, anchorNode: AnchorNode) { if (!mazeRenderable.isDone) { Log.d(TAG, "loading maze renderable still in progress. Wait to render again") CompletableFuture.allOf(mazeRenderable) .thenAccept { aVoid: Void -> setImage(image, anchorNode) } .exceptionally { throwable -> Log.e(TAG, "Exception loading", throwable) null } return } // Set the anchor based on the center of the image. // anchorNode.anchor = image.createAnchor(image.centerPose) val mazeNode = Node() mazeNode.setParent(anchorNode) mazeNode.renderable = mazeRenderable.getNow(null) *//* // Make sure longest edge fits inside the image val maze_edge_size = 492.65f val max_image_edge = Math.max(image.extentX, image.extentZ) val maze_scale = max_image_edge / maze_edge_size // Scale Y extra 10 times to lower the wall of maze mazeNode.localScale = Vector3(maze_scale, maze_scale * 0.1f, maze_scale)*//* }*/ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (isSupportedDevice) { debugLog( call.method + "called on supported device") when (call.method) { "init" -> { debugLog( "INIT AUGMENTED IMAGES") arScenViewInit(call, result) } "load_single_image_on_db" -> { debugLog( "load_single_image_on_db") val map = call.arguments as HashMap<String, Any> val singleImageBytes = map["bytes"] as? ByteArray setupSession(singleImageBytes, true) } "load_multiple_images_on_db" -> { debugLog( "load_multiple_image_on_db") val map = call.arguments as HashMap<String, Any> val dbByteMap = map["bytesMap"] as? Map<String, ByteArray> setupSession(dbByteMap) } "load_augmented_images_database" -> { debugLog( "LOAD DB") val map = call.arguments as HashMap<String, Any> val dbByteArray = map["bytes"] as? ByteArray setupSession(dbByteArray, false) } "attachObjectToAugmentedImage" -> { debugLog( "attachObjectToAugmentedImage") val map = call.arguments as HashMap<String, Any> val flutterArCoreNode = FlutterArCoreNode(map["node"] as HashMap<String, Any>) val index = map["index"] as Int if (augmentedImageMap.containsKey(index)) { // val augmentedImage = augmentedImageMap[index]!!.first val anchorNode = augmentedImageMap[index]!!.second // setImage(augmentedImage, anchorNode) // onAddNode(flutterArCoreNode, result) NodeFactory.makeNode(activity.applicationContext, flutterArCoreNode, debug) { node, throwable -> debugLog( "inserted ${node?.name}") if (node != null) { node.setParent(anchorNode) arSceneView?.scene?.addChild(anchorNode) result.success(null) } else if (throwable != null) { result.error("attachObjectToAugmentedImage error", throwable.localizedMessage, null) } } } else { result.error("attachObjectToAugmentedImage error", "Augmented image there isn't ona hashmap", null) } } "removeARCoreNodeWithIndex" -> { debugLog( "removeObject") try { val map = call.arguments as HashMap<String, Any> val index = map["index"] as Int removeNode(augmentedImageMap[index]!!.second) augmentedImageMap.remove(index) result.success(null) } catch (ex: Exception) { result.error("removeARCoreNodeWithIndex", ex.localizedMessage, null) } } "dispose" -> { debugLog( " updateMaterials") job.cancel() dispose() } else -> { result.notImplemented() } } } else { debugLog( "Impossible call " + call.method + " method on unsupported device") job.cancel() result.error("Unsupported Device", "", null) } } private fun arScenViewInit(call: MethodCall, result: MethodChannel.Result) { arSceneView?.scene?.addOnUpdateListener(sceneUpdateListener) onResume() result.success(null) } override fun onResume() { debugLog( "onResume") if (arSceneView == null) { debugLog( "arSceneView NULL") return } debugLog( "arSceneView NOT null") if (arSceneView?.session == null) { debugLog( "session NULL") if (!ArCoreUtils.hasCameraPermission(activity)) { ArCoreUtils.requestCameraPermission(activity, RC_PERMISSIONS) return } debugLog( "Camera has permission") // If the session wasn't created yet, don't resume rendering. // This can happen if ARCore needs to be updated or permissions are not granted yet. try { val session = ArCoreUtils.createArSession(activity, installRequested, false) if (session == null) { installRequested = false return } else { val config = Config(session) config.focusMode = Config.FocusMode.AUTO config.updateMode = Config.UpdateMode.LATEST_CAMERA_IMAGE config.planeFindingMode = Config.PlaneFindingMode.DISABLED session.configure(config) arSceneView?.setupSession(session) } } catch (e: UnavailableException) { ArCoreUtils.handleSessionException(activity, e) } } try { arSceneView?.resume() debugLog( "arSceneView.resume()") } catch (ex: CameraNotAvailableException) { ArCoreUtils.displayError(activity, "Unable to get camera", ex) debugLog( "CameraNotAvailableException") activity.finish() return } } fun setupSession(bytes: ByteArray?, useSingleImage: Boolean) { debugLog( "setupSession()") try { val session = arSceneView?.session ?: return val config = Config(session) config.focusMode = Config.FocusMode.AUTO config.updateMode = Config.UpdateMode.LATEST_CAMERA_IMAGE bytes?.let { if (useSingleImage) { if (!addImageToAugmentedImageDatabase(config, bytes)) { throw Exception("Could not setup augmented image database") } } else { if (!useExistingAugmentedImageDatabase(config, bytes)) { throw Exception("Could not setup augmented image database") } } } session.configure(config) arSceneView?.setupSession(session) } catch (ex: Exception) { debugLog( ex.localizedMessage) } } fun setupSession(bytesMap: Map<String, ByteArray>?) { debugLog( "setupSession()") try { val session = arSceneView?.session ?: return val config = Config(session) config.focusMode = Config.FocusMode.AUTO config.updateMode = Config.UpdateMode.LATEST_CAMERA_IMAGE bytesMap?.let { addMultipleImagesToAugmentedImageDatabase(config, bytesMap, session) } } catch (ex: Exception) { debugLog( ex.localizedMessage) } } private fun addMultipleImagesToAugmentedImageDatabase(config: Config, bytesMap: Map<String, ByteArray>, session: Session) { debugLog( "addImageToAugmentedImageDatabase") val augmentedImageDatabase = AugmentedImageDatabase(arSceneView?.session) launch { val operation = async(Dispatchers.Default) { for ((key, value) in bytesMap) { val augmentedImageBitmap = loadAugmentedImageBitmap(value) try { augmentedImageDatabase.addImage(key, augmentedImageBitmap) } catch (ex: Exception) { debugLog("Image with the title $key cannot be added to the database. " + "The exception was thrown: " + ex?.toString()) } } if (augmentedImageDatabase?.getNumImages() == 0) { throw Exception("Could not setup augmented image database") } config.augmentedImageDatabase = augmentedImageDatabase session.configure(config) arSceneView?.setupSession(session) } operation.await() } } private fun addImageToAugmentedImageDatabase(config: Config, bytes: ByteArray): Boolean { debugLog( "addImageToAugmentedImageDatabase") try { val augmentedImageBitmap = loadAugmentedImageBitmap(bytes) ?: return false val augmentedImageDatabase = AugmentedImageDatabase(arSceneView?.session) augmentedImageDatabase.addImage("image_name", augmentedImageBitmap) config.augmentedImageDatabase = augmentedImageDatabase return true } catch (ex:Exception) { debugLog(ex.localizedMessage) return false } } private fun useExistingAugmentedImageDatabase(config: Config, bytes: ByteArray): Boolean { debugLog( "useExistingAugmentedImageDatabase") return try { val inputStream = ByteArrayInputStream(bytes) val augmentedImageDatabase = AugmentedImageDatabase.deserialize(arSceneView?.session, inputStream) config.augmentedImageDatabase = augmentedImageDatabase true } catch (e: IOException) { Log.e(TAG, "IO exception loading augmented image database.", e) false } } private fun loadAugmentedImageBitmap(bitmapdata: ByteArray): Bitmap? { debugLog( "loadAugmentedImageBitmap") try { return BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.size) } catch (e: Exception) { Log.e(TAG, "IO exception loading augmented image bitmap.", e) return null } } }
138
null
263
418
49e716172807e288a98e02fa7a8c567b57e58b45
16,022
arcore_flutter_plugin
MIT License
eux-nav-rinasak-webapp/src/main/kotlin/no/nav/eux/rinasak/webapp/RinasakerMapper.kt
navikt
663,010,258
false
{"Kotlin": 34464, "HTML": 2030, "Makefile": 122, "Dockerfile": 88}
package no.nav.eux.rinasak.webapp import no.nav.eux.rinasak.model.dto.NavRinasakCreateRequest import no.nav.eux.rinasak.model.dto.NavRinasakFinnRequest import no.nav.eux.rinasak.model.dto.NavRinasakFinnResponse import no.nav.eux.rinasak.model.dto.NavRinasakPatch import no.nav.eux.rinasak.model.entity.Dokument import no.nav.eux.rinasak.model.entity.InitiellFagsak import no.nav.eux.rinasak.openapi.model.* import java.time.LocalDateTime import java.time.ZoneOffset.UTC import java.util.UUID.randomUUID val NavRinasakCreateType.navRinasakCreateRequest get() = NavRinasakCreateRequest( navRinasakUuid = randomUUID(), rinasakId = rinasakId, overstyrtEnhetsnummer = overstyrtEnhetsnummer, opprettetBruker = "ukjent", opprettetTidspunkt = LocalDateTime.now(), initiellFagsak = initiellFagsak.toInitiellFagsakCreateRequest(), dokumenter = dokumenter.toDokumentCreateRequests() ) val NavRinasakPatchType.navRinasakPatch get() = NavRinasakPatch( rinasakId = rinasakId, overstyrtEnhetsnummer = overstyrtEnhetsnummer, initiellFagsak = initiellFagsak.toInitiellFagsakPatchRequest(), dokumenter = dokumenter.toDokumentPatchRequests() ) val NavRinasakSearchCriteriaType.navRinasakFinnRequest get() = NavRinasakFinnRequest( rinasakId = rinasakId ) fun NavRinasakFinnResponse.toNavRinasakType() = NavRinasakType( rinasakId = navRinasak.rinasakId, overstyrtEnhetsnummer = navRinasak.overstyrtEnhetsnummer, opprettetBruker = navRinasak.opprettetBruker, opprettetTidspunkt = navRinasak.opprettetTidspunkt.atOffset(UTC), initiellFagsak = initiellFagsak?.toInitiellFagsakType(), dokumenter = dokumenter?.map { it.toDokumentType() } ) fun List<NavRinasakDokumentCreateType>?.toDokumentCreateRequests() = this?.let { sedCreateTypes -> sedCreateTypes.map { it.toDokumentCreateRequest() } } ?: emptyList() fun List<NavRinasakDokumentPatchType>?.toDokumentPatchRequests() = this?.let { sedCreateTypes -> sedCreateTypes.map { it.toDokumentPatchRequest() } } ?: emptyList() fun NavRinasakDokumentCreateType.toDokumentCreateRequest() = NavRinasakCreateRequest.DokumentCreateRequest( dokumentUuid = randomUUID(), sedId = sedId, sedVersjon = sedVersjon, dokumentInfoId = dokumentInfoId, sedType = sedType, ) fun NavRinasakDokumentPatchType.toDokumentPatchRequest() = NavRinasakPatch.DokumentPatch( dokumentUuid = randomUUID(), sedId = sedId, sedVersjon = sedVersjon, dokumentInfoId = dokumentInfoId, sedType = sedType, ) fun NavRinasakInitiellFagsakCreateType?.toInitiellFagsakCreateRequest() = this?.let { NavRinasakCreateRequest.FagsakCreateRequest( id = id, tema = it.tema, system = it.system, nr = it.nr, type = it.type, fnr = it.fnr, arkiv = it.arkiv ) } fun NavRinasakInitiellFagsakPatchType?.toInitiellFagsakPatchRequest() = this?.let { NavRinasakPatch.InitiellFagsakPatch( id = id, tema = it.tema, system = it.system, nr = it.nr, type = it.type, fnr = it.fnr, arkiv = it.arkiv, ) } fun List<NavRinasakFinnResponse>.toNavRinasakSearchResponseType() = NavRinasakSearchResponseType(navRinasaker = map { it.toNavRinasakType() }) fun Dokument.toDokumentType() = DokumentType( sedId = sedId, sedVersjon = sedVersjon, sedType = sedType, dokumentInfoId = dokumentInfoId, opprettetBruker = opprettetBruker, opprettetTidspunkt = opprettetTidspunkt.atOffset(UTC), ) fun InitiellFagsak.toInitiellFagsakType() = FagsakType( id = id, tema = tema, system = system, nr = nr, type = type, fnr = fnr, arkiv = arkiv, opprettetBruker = opprettetBruker, opprettetTidspunkt = opprettetTidspunkt.atOffset(UTC), )
2
Kotlin
0
0
faa09c76870ddf1068b73ba6d16905b4796811ea
4,135
eux-nav-rinasak
MIT License
plugin/src/main/kotlin/org/neotech/plugin/rootcoverage/JaCoCoConfiguration.kt
NeoTech-Software
152,748,748
false
null
package org.neotech.plugin.rootcoverage import org.gradle.api.Project import org.gradle.api.file.FileTree import org.neotech.plugin.rootcoverage.utilities.fileTree internal fun RootCoveragePluginExtension.getFileFilterPatterns(): List<String> = listOf( "**/AutoValue_*.*", // Filter to remove generated files from: https://github.com/google/auto //"**/*JavascriptBridge.class", // Android Databinding "**/*databinding", "**/*binders", "**/*layouts", "**/BR.class", // Filter to remove generated databinding files // Core Android generated class filters "**/R.class", "**/R$*.class", "**/Manifest*.*", "**/BuildConfig.class", "android/**/*.*", "**/*\$ViewBinder*.*", "**/*\$ViewInjector*.*", "**/Lambda$*.class", "**/Lambda.class", "**/*Lambda.class", "**/*Lambda*.class", "**/*\$InjectAdapter.class", "**/*\$ModuleAdapter.class", "**/*\$ViewInjector*.class" ) + excludes internal fun RootCoveragePluginExtension.getBuildVariantFor(project: Project): String = buildVariantOverrides[project.path] ?: buildVariant internal fun Project.getExecutionDataFileTree(includeUnitTestResults: Boolean, includeConnectedDevicesResults: Boolean, includeGradleManagedDevicesResults: Boolean): FileTree? { val buildFolderPatterns = mutableListOf<String>() if (includeUnitTestResults) { // TODO instead of hardcoding this, obtain the location from the test tasks, something like this? // tasks.withType(Test::class.java).all { testTask -> // testTask.extensions.findByType(JacocoTaskExtension::class.java)?.apply { // destinationFile // } // } // These are legacy paths for older now unsupported AGP version, they are just here for // reference and are not added to prevent existing files from polluting results // // buildFolderPatterns.add("jacoco/test*UnitTest.exec") // rootFolderPatterns.add("jacoco.exec") // Note this is not a build folder pattern and is based off project.projectDir // Android Build Tools Plugin 7.0+ buildFolderPatterns.add("outputs/unit_test_code_coverage/*/*.exec") } if (includeConnectedDevicesResults) { // These are legacy paths for older now unsupported AGP version, they are just here for // reference and are not added to prevent existing files from polluting results // // Android Build Tools Plugin 3.2 // buildFolderPatterns.add("outputs/code-coverage/connected/*coverage.ec") // // Android Build Tools Plugin 3.3-7.0 // buildFolderPatterns.add("outputs/code_coverage/*/connected/*coverage.ec") // Android Build Tools Plugin 7.1+ buildFolderPatterns.add("outputs/code_coverage/*/connected/*/coverage.ec") } if(includeGradleManagedDevicesResults) { // Gradle Managed Devices 7.4 // buildFolderPatterns.add("outputs/managed_device_code_coverage/*/coverage.ec") // Gradle Managed Devices 8.3+ buildFolderPatterns.add("outputs/managed_device_code_coverage/*/*/coverage.ec") } return if(buildFolderPatterns.isEmpty()) { null } else { fileTree(layout.buildDirectory, includes = buildFolderPatterns) } }
5
null
23
68
4ce3c6cfc64013e78dc2f8266425307844eef7a2
3,307
Android-Root-Coverage-Plugin
Apache License 2.0
krossbow-websocket-core/src/commonMain/kotlin/org/hildan/krossbow/websocket/WebSocketConnection.kt
joffrey-bion
190,066,229
false
null
package org.hildan.krossbow.websocket import kotlinx.coroutines.flow.* import kotlinx.io.bytestring.* /** * Represents a web socket connection to another endpoint. * * Implementations must be safe to call concurrently. */ interface WebSocketConnection { /** * The URL that was used to connect this web socket. */ val url: String /** * The host to which this web socket is connected. */ val host: String get() = url.substringAfter("://").substringBefore("/").substringBefore(":") /** * If false, sending frames should not be attempted and will likely throw an exception. * If true, sending frames will likely succeed. * However, no guarantees can be made because there could be a race condition between WS closure and a "send" call. * * This is usually based on the underlying web socket implementation "closed for send" status. * However, some web socket implementations like OkHttp or iOS don't expose their status, and `canSend` always returns `true`. * Note that OkHttp always allows calls to its `send` methods (which are turned into no-ops when the web socket is closed). */ val canSend: Boolean /** * The single-consumer hot flow of incoming web socket frames. * * This flow is designed for a single-consumer. * If multiple collectors collect it at the same time, each frame will go to only one of them in a fan-out manner. * For a broadcast behaviour, use [Flow.shareIn] to convert this flow into a [SharedFlow]. * * This flow is hot, meaning that the frames are coming and are buffered even when there is no collector. * This means that it's ok to have a delay between the connection and the collection of [incomingFrames], no * frames will be lost. * It's also ok to stop collecting the flow, and start again later: the frames that are received in the meantime * are buffered and sent to the collector when it comes back. */ val incomingFrames: Flow<WebSocketFrame> /** * Sends a web socket text frame. * * This method suspends until the underlying web socket implementation has processed the message. * Some implementations don't provide any ways to track when exactly the message is sent. * For those implementations, this method returns immediately without suspending. */ suspend fun sendText(frameText: String) /** * Sends a web socket binary frame. * * This method suspends until the underlying web socket implementation has processed the message. * Some implementations don't provide any ways to track when exactly the message is sent. * For those implementations, this method returns immediately without suspending. */ suspend fun sendBinary(frameData: ByteString) /** * Sends a web socket close frame with the given [code] and [reason], and closes the connection. * * The [code] can be any of the [WebSocketCloseCodes] defined by the specification, except * [NO_STATUS_CODE][WebSocketCloseCodes.NO_STATUS_CODE] and [NO_CLOSE_FRAME][WebSocketCloseCodes.NO_CLOSE_FRAME] * which are reserved for representing the absence of close code or close frame and should not be sent in a frame * (as defined by the specification in * [section 7.4.1 of RFC-6455](https://tools.ietf.org/html/rfc6455#section-7.4.1)). * * The [reason] must not be longer than 123 *bytes* (not characters!) when encoded in UTF-8, due to the limit on * control frames defined by the web socket protocol specification * [RFC-6455](https://tools.ietf.org/html/rfc6455#section-5.5). * You can use [String.truncateToCloseFrameReasonLength] if you don't control the length of the reason and yet still * want to avoid exceptions. */ suspend fun close(code: Int = WebSocketCloseCodes.NORMAL_CLOSURE, reason: String? = null) } interface WebSocketConnectionWithPing : WebSocketConnection { /** * Sends a web socket ping frame. */ suspend fun sendPing(frameData: ByteString) } interface WebSocketConnectionWithPingPong : WebSocketConnectionWithPing { /** * Sends an unsolicited web socket pong frame. * * Note that implementations usually take care of sending Pong frames corresponding to each received Ping frame, so * applications should not bother dealing with Pongs in general. * Unsolicited Pong frames may be sent, however, for instance to serve as unidirectional heart beats. */ suspend fun sendPong(frameData: ByteString) }
15
null
15
199
4cc809eaf64331536677757fe4bf5d6fc34f6716
4,591
krossbow
MIT License
app/src/main/java/at/jku/enternot/service/CameraMovementServiceImpl.kt
Shynixn
135,711,058
false
{"Kotlin": 78788}
package at.jku.enternot.service import android.app.Application import android.arch.lifecycle.MutableLiveData import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.util.Log import at.jku.enternot.R import at.jku.enternot.contract.CameraMovementService import at.jku.enternot.contract.ConnectionService import org.jetbrains.anko.doAsync import kotlin.math.roundToInt class CameraMovementServiceImpl(private val applicationContext: Application, private val connectionService: ConnectionService) : CameraMovementService, SensorEventListener { private val logTag = this::class.java.simpleName private val sensorManager = applicationContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager private val gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) private val axisData = MutableLiveData<Triple<Float, Float, Float>>() private lateinit var calibrationValues: Triple<Float, Float, Float> init { this.loadCalibrationValues() } /** * Enables or disables the camera movement. * @param b True if the camera movement should be enabled otherwise false. */ override fun enableCameraMovement(b: Boolean) { if(b) { sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_NORMAL) } else { sensorManager.unregisterListener(this, gyroscope) } } /** * Gets the axis moving data. */ override fun getAxisData(): MutableLiveData<Triple<Float, Float, Float>> { return axisData } /** * Reads a set of axis data, calculate the average value for all three axis * and saves these values to the local storage. */ override fun calibrateSensor(f: () -> Unit) { sensorManager.registerListener(CalibrationListener { listener, data -> sensorManager.unregisterListener(listener, gyroscope) val average = Triple( data.map { it.first }.average().toFloat(), data.map { it.second }.average().toFloat(), data.map { it.third }.average().toFloat() ) saveCalibrationValues(average) f.invoke() }, gyroscope, SensorManager.SENSOR_DELAY_FASTEST) } /** * Sends axis data to the pi. */ override fun sendAxisData(data: Triple<Float, Float, Float>) { doAsync { val x: Int val y: Int if(isInPortrait()) { x = data.first.roundToInt() y = data.second.roundToInt() } else { x = data.second.roundToInt() y = data.first.roundToInt() } if(x > 0 || x < 0 || y > 0 || y < 0) { val responseCode = connectionService.post("/camera/position", applicationContext, CameraPosition((x * 36).toFloat(), (y * 36).toFloat())) Log.d(logTag, "Response code: $responseCode") } } } data class CameraPosition(val x_angle: Float, val y_angle: Float) private fun isInPortrait(): Boolean = applicationContext.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT /** * Saves the calibration values to the shared preferences. */ private fun saveCalibrationValues(average: Triple<Float, Float, Float>) { val sharedPref = applicationContext.getSharedPreferences( applicationContext.getString(R.string.preference_file_key), Context.MODE_PRIVATE) this.calibrationValues = average with(sharedPref.edit()) { putFloat("averageX", average.first) putFloat("averageY", average.second) putFloat("averageZ", average.third) apply() } } /** * Loads the calibration values from the shared preferences. */ private fun loadCalibrationValues() { val sharedPref = applicationContext.getSharedPreferences( applicationContext.getString(R.string.preference_file_key), Context.MODE_PRIVATE ) val x = sharedPref.getFloat("averageX", 0F) val y = sharedPref.getFloat("averageY", 0F) val z = sharedPref.getFloat("averageZ", 0F) this.calibrationValues = Triple(x, y, z) } class CalibrationListener(val callback: (listener: CalibrationListener, data: List<Triple<Float, Float, Float>>) -> Unit) : SensorEventListener { private val samples = 250 private val calibrationData: MutableList<Triple<Float, Float, Float>> = mutableListOf() /** * Called when the accuracy of the registered sensor has changed. Unlike * onSensorChanged(), this is only called when this accuracy value changes. * * * See the SENSOR_STATUS_* constants in * [SensorManager][android.hardware.SensorManager] for details. * * @param accuracy The new accuracy of this sensor, one of * `SensorManager.SENSOR_STATUS_*` */ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // Again we don't need this. Why there is no abstract adapter so we can only implement // the onSensorChange method. } /** * Called when there is a new sensor event. Note that "on changed" * is somewhat of a misnomer, as this will also be called if we have a * new reading from a sensor with the exact same sensor values (but a * newer timestamp). * * * See [SensorManager][android.hardware.SensorManager] * for details on possible sensor types. * * See also [SensorEvent][android.hardware.SensorEvent]. * * * **NOTE:** The application doesn't own the * [event][android.hardware.SensorEvent] * object passed as a parameter and therefore cannot hold on to it. * The object may be part of an internal pool and may be reused by * the framework. * * @param event the [SensorEvent][android.hardware.SensorEvent]. */ override fun onSensorChanged(event: SensorEvent?) { if (calibrationData.size <= samples && event != null) { calibrationData.add(Triple(event.values[0], event.values[1], event.values[2])) } else if (calibrationData.size >= samples) { callback.invoke(this, calibrationData) } } } /** * Called when the accuracy of the registered sensor has changed. Unlike * onSensorChanged(), this is only called when this accuracy value changes. * * * See the SENSOR_STATUS_* constants in * [SensorManager][android.hardware.SensorManager] for details. * * @param accuracy The new accuracy of this sensor, one of * `SensorManager.SENSOR_STATUS_*` */ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // We don't need this method. :D } /** * Called when there is a new sensor event. Note that "on changed" * is somewhat of a misnomer, as this will also be called if we have a * new reading from a sensor with the exact same sensor values (but a * newer timestamp). * * * See [SensorManager][android.hardware.SensorManager] * for details on possible sensor types. * * See also [SensorEvent][android.hardware.SensorEvent]. * * * **NOTE:** The application doesn't own the * [event][android.hardware.SensorEvent] * object passed as a parameter and therefore cannot hold on to it. * The object may be part of an internal pool and may be reused by * the framework. * * @param event the [SensorEvent][android.hardware.SensorEvent]. */ override fun onSensorChanged(event: SensorEvent?) { if(event != null) { this.axisData.postValue(Triple( event.values[0] - calibrationValues.first, event.values[1] - calibrationValues.second, event.values[2] - calibrationValues.third )) } } }
0
Kotlin
0
1
f1046f21bb0c66e9a5d1e4e78a67a035e725ac6a
8,487
enternot-app
MIT License
domain/src/main/kotlin/no/nav/su/se/bakover/domain/vedtak/VedtakIverksattSøknadsbehandling.kt
navikt
227,366,088
false
{"Kotlin": 9487258, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.domain.vedtak import no.nav.su.se.bakover.domain.søknadsbehandling.IverksattSøknadsbehandling /** * Grupperer avslag og innvilgelser. */ sealed interface VedtakIverksattSøknadsbehandling : Stønadsvedtak { override val behandling: IverksattSøknadsbehandling }
6
Kotlin
1
1
357eaae76b66b996661ceccb594a9bb7b206e2d6
296
su-se-bakover
MIT License
kotlin-sdk/kotlin/src/main/kotlin/io/logto/sdk/core/constant/QueryKey.kt
logto-io
397,657,445
false
null
package io.logto.sdk.core.constant object QueryKey { const val CLIENT_ID = "client_id" const val CODE = "code" const val CODE_CHALLENGE = "code_challenge" const val CODE_CHALLENGE_METHOD = "code_challenge_method" const val CODE_VERIFIER = "code_verifier" const val ERROR = "error" const val ERROR_DESCRIPTION = "error_description" const val GRANT_TYPE = "grant_type" const val POST_LOGOUT_REDIRECT_URI = "post_logout_redirect_uri" const val PROMPT = "prompt" const val REDIRECT_URI = "redirect_uri" const val REFRESH_TOKEN = "refresh_token" const val RESOURCE = "resource" const val RESPONSE_TYPE = "response_type" const val SCOPE = "scope" const val STATE = "state" const val TOKEN = "token" const val ORGANIZATION_ID = "organization_id" const val LOGIN_HINT = "login_hint" const val FIRST_SCREEN = "first_screen" const val IDENTIFIER = "identifier" const val DIRECT_SIGN_IN = "direct_sign_in" }
1
null
6
7
f8e94f533d2e60b029bca455fdcb1c050ce0a68d
986
kotlin
MIT License
app/src/main/java/com/example/peanutbook/fakeappka/ui/MainController.kt
JosefHruska
118,558,284
false
null
package com.example.peanutbook.fakeappka.ui import com.example.peanutbook.fakeappka.ui.base.BaseController /** * Controller for [MainActivity] * * @author <NAME> (<EMAIL>) */ interface MainController: BaseController { }
1
null
1
1
fd8a8791eeac603b297c76636ba44172313668f1
227
FakeHacksHackhatonApp
MIT License
app/src/main/java/com/amitranofinzi/vimata/data/model/TestSet.kt
Ggino11
788,949,158
false
{"Kotlin": 368820}
package com.amitranofinzi.vimata.data.model import androidx.annotation.NonNull import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey /** * Represents a set of tests created by a trainer for an athlete. * This is a Room entity annotated for database table creation. * The `testSets` table has foreign key relationships with the `users` table. * * @property id The unique ID of the test set. And the firebase document ID * @property title The title of the test set. * @property trainerID The ID of the trainer who created the test set. * @property athleteID The ID of the athlete for whom the test set was created. */ @Entity(tableName = "testSets", foreignKeys = [ ForeignKey( entity = User::class, parentColumns = ["uid"], childColumns = ["trainerID"], onDelete = ForeignKey.CASCADE ), ForeignKey( entity = User::class, parentColumns = ["uid"], childColumns = ["athleteID"], onDelete = ForeignKey.CASCADE )], indices = [androidx.room.Index(value = ["trainerID"]), androidx.room.Index(value = ["athleteID"])] ) data class TestSet ( @PrimaryKey @NonNull val id: String = "", val title: String = "", val trainerID: String = "", val athleteID: String = "", ) { constructor() : this( id = "", title = "", trainerID = "", athleteID = "", ) }
0
Kotlin
0
0
b52fbb6a00375a55ff1df74b71ae0531702dd5fc
1,462
ProgettoAmitranoFinzi-progMob
MIT License
sample-compose-fragments/src/main/java/uk/gov/hmrc/sample_compose_fragments/navigator/Navigator.kt
hmrc
299,591,950
false
{"Kotlin": 510085, "Ruby": 10066, "Shell": 1395}
/* * Copyright 2023 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.sample_compose_fragments.navigator import androidx.fragment.app.Fragment interface Navigator { fun Fragment.gotoAtomText() fun Fragment.gotoAtomButton() fun Fragment.gotoAtomDivider() fun Fragment.gotoTextInputView() fun Fragment.gotoCurrencyInputView() fun Fragment.gotoMultiRowTextFragment() fun Fragment.gotoMoleculeH4TitleBodyView() fun Fragment.gotoMoleculeH5TitleBodyView() fun Fragment.gotoMoleculeInsetView() fun Fragment.gotoMoleculeInsetTextView() fun Fragment.gotoMoleculeBoldTitleBodyView() fun Fragment.gotoMoleculeSwitchRowView() fun Fragment.gotoMoleculeWarningView() fun Fragment.gotoMoleculeTabBarView() fun Fragment.gotoMoleculeSelectRowView() fun Fragment.goToMoleculeStatusView() fun Fragment.goToIconButtonCardView() fun Fragment.goBack() }
4
Kotlin
3
7
fbbc75c9cf5a6b5fc1f9cb021eb780d5a2bea937
1,478
android-components
Apache License 2.0
src/test/kotlin/org/kotlinbitcointools/ur/BytewordsTest.kt
kotlin-bitcoin-tools
662,277,344
false
{"Kotlin": 78108, "Java": 10358, "Just": 254}
package org.kotlinbitcointools.ur import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue // Taken from URKit's BytewordsTests.swift // https://github.com/BlockchainCommons/URKit/blob/master/Tests/URKitTests/BytewordsTests.swift class BytewordsTest { @Test fun `Encoding bytewords`() { val input = byteArrayOf(0x00, 0x01, 0x02, 0x80.toByte(), 0xff.toByte()) assertEquals( expected = "able acid also lava zoom jade need echo taxi", actual = Bytewords.encode(input, Bytewords.Style.STANDARD) ) assertEquals( expected = "able-acid-also-lava-zoom-jade-need-echo-taxi", actual = Bytewords.encode(input, Bytewords.Style.URI) ) assertEquals( expected = "aeadaolazmjendeoti", actual = Bytewords.encode(input, Bytewords.Style.MINIMAL) ) } @Test fun `Decoding bytewords`() { val input = byteArrayOf(0x00, 0x01, 0x02, 0x80.toByte(), 0xff.toByte()) assertTrue( input.contentEquals( Bytewords.decode("able acid also lava zoom jade need echo taxi", Bytewords.Style.STANDARD) ) ) assertTrue( input.contentEquals( Bytewords.decode("able-acid-also-lava-zoom-jade-need-echo-taxi", Bytewords.Style.URI) ) ) assertTrue( input.contentEquals( Bytewords.decode("aeadaolazmjendeoti", Bytewords.Style.MINIMAL) ) ) } @Test fun `Incorrect checksum throws`() { assertFailsWith<InvalidChecksumException> { Bytewords.decode("able acid also lava zero jade need echo wolf", Bytewords.Style.STANDARD) } assertFailsWith<InvalidChecksumException> { Bytewords.decode("able-acid-also-lava-zero-jade-need-echo-wolf", Bytewords.Style.URI) } assertFailsWith<InvalidChecksumException> { Bytewords.decode("aeadaolazojendeowf", Bytewords.Style.MINIMAL) } } @Test fun `Message is too short throws`() { assertFailsWith<InvalidChecksumException> { Bytewords.decode("wolf", Bytewords.Style.STANDARD) } } @Test fun `Invalid byteword throws`() { assertFailsWith<InvalidBytewordException> { Bytewords.decode("mango", Bytewords.Style.STANDARD) } assertFailsWith<InvalidBytewordException> { Bytewords.decode("ma", Bytewords.Style.MINIMAL) } } @Test fun `Bigger input encodes correctly`() { val input = listOf( 245, 215, 20, 198, 241, 235, 69, 59, 209, 205, 165, 18, 150, 158, 116, 135, 229, 212, 19, 159, 17, 37, 239, 240, 253, 11, 109, 191, 37, 242, 38, 120, 223, 41, 156, 189, 242, 254, 147, 204, 66, 163, 216, 175, 191, 72, 169, 54, 32, 60, 144, 230, 210, 137, 184, 197, 33, 113, 88, 14, 157, 31, 177, 46, 1, 115, 205, 69, 225, 150, 65, 235, 58, 144, 65, 240, 133, 69, 113, 247, 63, 53, 242, 165, 160, 144, 26, 13, 79, 237, 133, 71, 82, 69, 254, 165, 138, 41, 85, 24 ).map { it.toByte() }.toByteArray() val expectedEncoded = "yank toys bulb skew when warm free fair tent swan open brag mint noon jury list view tiny brew note body data webs what zinc bald join runs data whiz days keys user diet news ruby whiz zone menu surf flew omit trip pose runs fund part even crux fern math visa tied loud redo silk curl jugs hard beta next cost puma drum acid junk swan free very mint flap warm fact math flap what limp free jugs yell fish epic whiz open numb math city belt glow wave limp fuel grim free zone open love diet gyro cats fizz holy city puff" val expectedEncodedMinimal = "yktsbbswwnwmfefrttsnonbgmtnnjyltvwtybwnebydawswtzcbdjnrsdawzdsksurdtnsrywzzemusffwottppersfdptencxfnmhvatdldroskcljshdbantctpadmadjksnfevymtfpwmftmhfpwtlpfejsylfhecwzonnbmhcybtgwwelpflgmfezeonledtgocsfzhycypf" assertEquals( expected = expectedEncoded, actual = Bytewords.encode(input, Bytewords.Style.STANDARD) ) assertEquals( expected = expectedEncodedMinimal, actual = Bytewords.encode(input, Bytewords.Style.MINIMAL) ) } }
0
Kotlin
0
0
90e0d5d3ccefd4c4fe0854a583f3bbf1f3b7145b
4,346
ur
Apache License 2.0
app/src/main/java/com/nandra/myschool/adapter/ChatDetailListAdapter.kt
nandrasaputra
235,056,472
false
null
package com.nandra.myschool.adapter import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.ale.infra.manager.IMMessage import com.nandra.myschool.adapter.viewholder.ChatDetailReceivedMessageViewHolder import com.nandra.myschool.adapter.viewholder.ChatDetailSentMessageViewHolder class ChatDetailListAdapter : ListAdapter<IMMessage, RecyclerView.ViewHolder>(channelDetailDiffUtilCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when(viewType) { VIEW_TYPE_MESSAGE_SENT -> { ChatDetailSentMessageViewHolder.create(parent) } VIEW_TYPE_MESSAGE_RECEIVE -> { ChatDetailReceivedMessageViewHolder.create(parent)} else -> throw IllegalArgumentException("Unknown View Type $viewType") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when(getItemViewType(position)) { VIEW_TYPE_MESSAGE_SENT -> { (holder as ChatDetailSentMessageViewHolder).bindView(getItem(position)) } VIEW_TYPE_MESSAGE_RECEIVE -> { (holder as ChatDetailReceivedMessageViewHolder).bindView(getItem(position)) } } } override fun getItemViewType(position: Int): Int { val message = getItem(position) return if (message.isMsgSent) { VIEW_TYPE_MESSAGE_SENT } else { VIEW_TYPE_MESSAGE_RECEIVE } } companion object { private const val VIEW_TYPE_MESSAGE_SENT = 1 private const val VIEW_TYPE_MESSAGE_RECEIVE = 2 private val channelDetailDiffUtilCallback = object : DiffUtil.ItemCallback<IMMessage>() { override fun areItemsTheSame(oldItem: IMMessage, newItem: IMMessage): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: IMMessage, newItem: IMMessage): Boolean { return oldItem.messageId == newItem.messageId } } } }
0
Kotlin
0
7
ba2970f561b85866742290a8f77c854f7e7ef515
2,123
MySchool
Apache License 2.0
src/app/src/main/kotlin/org/imperial/mrc/hint/logging/LogMetadata.kt
mrc-ide
186,620,695
false
{"Markdown": 9, "Dockerfile": 2, "Ignore List": 3, "YAML": 13, "Gradle": 6, "Shell": 19, "Batchfile": 1, "INI": 11, "Java": 23, "HTML": 3, "Text": 6, "Kotlin": 184, "Java Properties": 1, "XML": 4, "JSON": 6, "JavaScript": 6, "JSON with Comments": 2, "FreeMarker": 3, "Fluent": 2, "Vue": 81, "SCSS": 11}
package org.imperial.mrc.hint.logging import org.imperial.mrc.hint.ConfiguredAppProperties import org.imperial.mrc.hint.models.ErrorDetail import org.springframework.http.HttpStatus import javax.servlet.http.HttpServletRequest data class Client( val agent: String? = null, val geoIp: String? = null, val sessionId: String? = null ) data class AppOrigin( val name: String? = "hint", val profileUrl: String? = ConfiguredAppProperties().applicationUrl, val type: String? = "backend" ) data class Request( val method: String, val path: String, val hostname: String, val client: Client ) { constructor(request: HttpServletRequest) : this( request.method, request.servletPath, request.serverName, Client(request.getHeader("User-Agent"), request.remoteAddr, request.session.id) ) } data class Response(val message: String? = null, val status: HttpStatus? = null) data class ErrorMessage(val error: Throwable? = null, val details: ErrorDetail? = null, val key: String? = null) data class LogMetadata( val action: String? = null, val error: ErrorMessage? = null, val request: Request? = null, val response: Response? = null, val username: String? = null, val app: AppOrigin? = AppOrigin(), val tags: List<String>? = emptyList() )
21
TypeScript
2
1
f46238ae819de61e3cc483e8812c6039ccd9a6a4
1,444
hint
MIT License
src/main/kotlin/org/wagham/db/utils/Aliases.kt
kaironbot
540,862,397
false
{"Kotlin": 216574}
package org.wagham.db.utils typealias PlayerId = String typealias ItemId = String typealias CharacterId = String typealias BinaryData = String
1
Kotlin
0
0
f4fa864299990de40c764742523fba22ad885464
146
kabot-db-connector
MIT License
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/tasks/KotlinCompileCommon.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.gradle.tasks import org.gradle.api.Project import org.gradle.api.tasks.compile.AbstractCompile import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments import org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment import org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner import org.jetbrains.kotlin.compilerRunner.OutputItemsCollectorImpl import org.jetbrains.kotlin.incremental.ChangedFiles import java.io.File internal open class KotlinCompileCommon : AbstractKotlinCompile<K2MetadataCompilerArguments>() { override fun populateCompilerArguments(): K2MetadataCompilerArguments = K2MetadataCompilerArguments() override fun getSourceRoots(): SourceRoots = SourceRoots.KotlinOnly.create(getSource()) override fun findKotlinCompilerJar(project: Project): File? = findKotlinMetadataCompilerJar(project) override fun callCompiler(args: K2MetadataCompilerArguments, sourceRoots: SourceRoots, changedFiles: ChangedFiles) { val classpathList = classpath.files.toMutableList() val friendTask = friendTaskName?.let { project.tasks.findByName(it) } as? AbstractCompile friendTask?.let { classpathList.add(it.destinationDir) } with(args) { classpath = classpathList.joinToString(File.pathSeparator) destination = destinationDir.canonicalPath freeArgs = sourceRoots.kotlinSourceFiles.map { it.canonicalPath } } val messageCollector = GradleMessageCollector(logger) val outputItemCollector = OutputItemsCollectorImpl() val compilerRunner = GradleCompilerRunner(project) val environment = GradleCompilerEnvironment(compilerJar, messageCollector, outputItemCollector, args) val exitCode = compilerRunner.runMetadataCompiler(sourceRoots.kotlinSourceFiles, args, environment) throwGradleExceptionIfError(exitCode) } }
4
null
4
83
4383335168338df9bbbe2a63cb213a68d0858104
2,552
kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FourKeysKeyboard.kt
ashtanko
203,993,092
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 4 Keys Keyboard. * @see <a href="https://leetcode.com/problems/4-keys-keyboard/">Source</a> */ fun interface FourKeysKeyboard { fun maxA(n: Int): Int } /** * Approach #1: Dynamic Programming. */ class FourKeysKeyboardDP : FourKeysKeyboard { override fun maxA(n: Int): Int { val best = IntArray(n + 1) for (k in 1..n) { best[k] = best[k - 1] + 1 for (x in 0 until k - 1) best[k] = max(best[k], best[x] * (k - x - 1)) } return best[n] } } /** * Approach #3: Mathematical. */ class FourKeysKeyboardMath : FourKeysKeyboard { override fun maxA(n: Int): Int { val q = if (n > MAX) (n - N_MAX) / MULTIPLY_LIMIT else 0 return best[n - MULTIPLY_LIMIT * q] shl 2 * q } companion object { private val best = intArrayOf( 0, 1, 2, 3, 4, 5, 6, 9, 12, 16, 20, 27, 36, 48, 64, 81, ) private const val MAX = 15 private const val N_MAX = 11 private const val MULTIPLY_LIMIT = 5 } }
4
null
0
19
325f2bb712514d1f7993ff7fa6d81ee45d2e6322
1,703
kotlab
Apache License 2.0
src/frontendMain/kotlin/me/frost/huebert/components/LightTable.kt
Frostmaid
448,289,261
false
null
package me.frost.huebert.components import io.kvision.core.Container import io.kvision.tabulator.ColumnDefinition import io.kvision.tabulator.Layout import io.kvision.tabulator.TabulatorOptions import io.kvision.tabulator.tabulator import me.frost.huebert.Light fun Container.lightTable(state: List<Light>) { tabulator( data = state, dataUpdateOnEdit = true, options = TabulatorOptions( layout = Layout.FITCOLUMNS, columns = listOf( ColumnDefinition(title = "Name", field = "metadata.name"), ColumnDefinition(title = "Type", field = "metadata.archetype"), dimmingLight(), switchLight() ) ) ) }
0
Kotlin
0
0
38c246960fccf7a766d2e075f7192304937da6df
738
HueWeb
MIT License
ethers-providers/src/main/kotlin/io/ethers/providers/middleware/EthApi.kt
Kr1ptal
712,963,462
false
null
package io.ethers.providers.middleware import io.ethers.core.types.AccountOverride import io.ethers.core.types.Address import io.ethers.core.types.BlockId import io.ethers.core.types.BlockOverride import io.ethers.core.types.BlockWithHashes import io.ethers.core.types.BlockWithTransactions import io.ethers.core.types.Bytes import io.ethers.core.types.CallRequest import io.ethers.core.types.FeeHistory import io.ethers.core.types.Hash import io.ethers.core.types.Log import io.ethers.core.types.LogFilter import io.ethers.core.types.RPCTransaction import io.ethers.core.types.SyncStatus import io.ethers.core.types.TransactionReceipt import io.ethers.core.types.transaction.TransactionSigned import io.ethers.core.types.transaction.TransactionUnsigned import io.ethers.providers.RpcError import io.ethers.providers.types.FilterPoller import io.ethers.providers.types.PendingTransaction import io.ethers.providers.types.RpcRequest import io.ethers.providers.types.RpcSubscribe import java.math.BigInteger import java.util.Optional interface EthApi { /** * EVM chain id. */ val chainId: Long /** * Get latest block number. */ fun getBlockNumber(): RpcRequest<Long, RpcError> /** * Get [address] balance at [hash]. */ fun getBalance(address: Address, hash: Hash) = getBalance(address, BlockId.Hash(hash)) /** * Get [address] balance at [number]. */ fun getBalance(address: Address, number: Long) = getBalance(address, BlockId.Number(number)) /** * Get [address] balance at [blockId]. */ fun getBalance(address: Address, blockId: BlockId): RpcRequest<BigInteger, RpcError> /** * Get block header by [hash]. */ fun getBlockHeader(hash: Hash) = getBlockHeader(BlockId.Hash(hash)) /** * Get block header by [number]. */ fun getBlockHeader(number: Long) = getBlockHeader(BlockId.Number(number)) /** * Get block header by [blockId]. */ fun getBlockHeader(blockId: BlockId): RpcRequest<BlockWithHashes, RpcError> /** * Get block by [hash] with transaction hashes. */ fun getBlockWithHashes(hash: Hash) = getBlockWithHashes(BlockId.Hash(hash)) /** * Get block by [number] with transaction hashes. */ fun getBlockWithHashes(number: Long) = getBlockWithHashes(BlockId.Number(number)) /** * Get block by [blockId] with transaction hashes. */ fun getBlockWithHashes(blockId: BlockId): RpcRequest<BlockWithHashes, RpcError> /** * Get block by [hash] with full transaction objects. */ fun getBlockWithTransactions(hash: Hash) = getBlockWithTransactions(BlockId.Hash(hash)) /** * Get block by [number] with full transaction objects. */ fun getBlockWithTransactions(number: Long) = getBlockWithTransactions(BlockId.Number(number)) /** * Get block by [blockId] with full transaction objects. */ fun getBlockWithTransactions(blockId: BlockId): RpcRequest<BlockWithTransactions, RpcError> /** * Get uncle block header by [hash] and [index]. */ fun getUncleBlockHeader(hash: Hash, index: Long) = getUncleBlockHeader(BlockId.Hash(hash), index) /** * Get uncle block header by [number] and [index]. */ fun getUncleBlockHeader(number: Long, index: Long) = getUncleBlockHeader(BlockId.Number(number), index) /** * Get uncle block header by [blockId] and [index]. */ fun getUncleBlockHeader(blockId: BlockId, index: Long): RpcRequest<BlockWithHashes, RpcError> /** * Get uncle blocks count by [hash]. */ fun getUncleBlocksCount(hash: Hash) = getUncleBlocksCount(BlockId.Hash(hash)) /** * Get uncle blocks count by [number]. */ fun getUncleBlocksCount(number: Long) = getUncleBlocksCount(BlockId.Number(number)) /** * Get uncle blocks count by [blockId]. */ fun getUncleBlocksCount(blockId: BlockId): RpcRequest<Long, RpcError> /** * Get code stored at given [address] in the state for given block [hash]. */ fun getCode(address: Address, hash: Hash) = getCode(address, BlockId.Hash(hash)) /** * Get code stored at given [address] in the state for given block [number]. */ fun getCode(address: Address, number: Long) = getCode(address, BlockId.Number(number)) /** * Get code stored at given [address] in the state for given [blockId]. */ fun getCode(address: Address, blockId: BlockId): RpcRequest<Bytes, RpcError> /** * Get storage value stored at given [address] and [key] in the state for given block [hash]. */ fun getStorage(address: Address, key: Hash, hash: Hash) = getStorage(address, key, BlockId.Hash(hash)) /** * Get storage value stored at given [address] and [key] in the state for given block [number]. */ fun getStorage(address: Address, key: Hash, number: Long) = getStorage(address, key, BlockId.Number(number)) /** * Get storage value stored at given [address] and [key] in the state for given block [blockId]. */ fun getStorage(address: Address, key: Hash, blockId: BlockId): RpcRequest<Hash, RpcError> /** * Execute [call] on given [blockId]. */ fun call(call: CallRequest, blockId: BlockId) = call(call, blockId, null, null) /** * Execute [call] on given [blockId] with applied state overrides. */ fun call(call: CallRequest, blockId: BlockId, stateOverride: Map<Address, AccountOverride>) = call(call, blockId, stateOverride, null) /** * Execute [call] on given [blockId] with applied block overrides. */ fun call(call: CallRequest, blockId: BlockId, blockOverride: BlockOverride) = call(call, blockId, null, blockOverride) /** * Execute [call] on given [blockId] with applied state and block overrides. */ fun call( call: CallRequest, blockId: BlockId, stateOverride: Map<Address, AccountOverride>? = null, blockOverride: BlockOverride? = null, ): RpcRequest<Bytes, RpcError> /** * Estimate gas required to execute [call] on given block [hash]. */ fun estimateGas(call: CallRequest, hash: Hash) = estimateGas(call, BlockId.Hash(hash)) /** * Estimate gas required to execute [call] on given block [number]. */ fun estimateGas(call: CallRequest, number: Long) = estimateGas(call, BlockId.Number(number)) /** * Estimate gas required to execute [call] on given [blockId]. */ fun estimateGas(call: CallRequest, blockId: BlockId): RpcRequest<BigInteger, RpcError> /** * Create access list for a given transaction [call] on a given block [hash]. */ fun createAccessList(call: CallRequest, hash: Hash) = createAccessList(call, BlockId.Hash(hash)) /** * Create access list for a given transaction [call] on a given block [number]. */ fun createAccessList(call: CallRequest, number: Long) = createAccessList(call, BlockId.Number(number)) /** * Create access list for a given transaction [call] on a given block [blockId]. */ fun createAccessList(call: CallRequest, blockId: BlockId): RpcRequest<*, RpcError> /** * Get gas price suggestion for legacy transaction. */ fun getGasPrice(): RpcRequest<BigInteger, RpcError> /** * Returns the base fee per blob gas in wei. * */ fun getBlobBaseFee(): RpcRequest<BigInteger, RpcError> /** * Get gas tip cap suggestion for dynamic fee transaction. */ fun getMaxPriorityFeePerGas(): RpcRequest<BigInteger, RpcError> /** * Get gas fee history for block range between [lastBlockNumber] and ([lastBlockNumber] - [blockCount] + 1). */ fun getFeeHistory(blockCount: Long, lastBlockNumber: Long) = getFeeHistory(blockCount, lastBlockNumber, emptyList()) /** * Get gas fee history for block range between [lastBlockNumber] and ([lastBlockNumber] - [blockCount] + 1). * * @param [rewardPercentiles] a monotonically increasing list of percentile values to sample from each block's * effective priority fees per gas in ascending order, weighted by gas used. */ fun getFeeHistory( blockCount: Long, lastBlockNumber: Long, rewardPercentiles: List<BigInteger> = emptyList(), ): RpcRequest<FeeHistory, RpcError> /** * Check if node is syncing with the network. */ fun isNodeSyncing(): RpcRequest<SyncStatus, RpcError> /** * Get transaction count in a block by [number]. */ fun getBlockTransactionCount(number: Long) = getBlockTransactionCount(BlockId.Number(number)) /** * Get transaction count in a block by [hash]. */ fun getBlockTransactionCount(hash: Hash) = getBlockTransactionCount(BlockId.Hash(hash)) /** * Get transaction count in a block by [blockId]. */ fun getBlockTransactionCount(blockId: BlockId): RpcRequest<Long, RpcError> /** * Get transaction at [index] in a given block [number]. */ fun getTransactionByBlockAndIndex(number: Long, index: Long) = getTransactionByBlockAndIndex(BlockId.Number(number), index) /** * Get transaction at [index] in a given block [hash]. */ fun getTransactionByBlockAndIndex(hash: Hash, index: Long) = getTransactionByBlockAndIndex(BlockId.Hash(hash), index) /** * Get transaction at [index] in a given block [blockId]. */ fun getTransactionByBlockAndIndex(blockId: BlockId, index: Long): RpcRequest<RPCTransaction, RpcError> /** * Get RLP encoded transaction at [index] in a given block [number]. */ fun getRawTransactionByBlockAndIndex(number: Long, index: Long) = getRawTransactionByBlockAndIndex(BlockId.Number(number), index) /** * Get RLP encoded transaction at [index] in a given block [hash]. */ fun getRawTransactionByBlockAndIndex(hash: Hash, index: Long) = getRawTransactionByBlockAndIndex(BlockId.Hash(hash), index) /** * Get RLP encoded transaction at [index] in a given block [blockId]. */ fun getRawTransactionByBlockAndIndex(blockId: BlockId, index: Long): RpcRequest<Bytes, RpcError> /** * Count the transactions sent by [address] up to and including the current block [number]. */ fun getTransactionCount(address: Address, number: Long) = getTransactionCount(address, BlockId.Number(number)) /** * Count the transactions sent by [address] up to and including the current block [hash]. */ fun getTransactionCount(address: Address, hash: Hash) = getTransactionCount(address, BlockId.Hash(hash)) /** * Count the transactions sent by [address] up to and including the current block [blockId]. */ fun getTransactionCount(address: Address, blockId: BlockId): RpcRequest<Long, RpcError> /** * Get transaction by [hash], returning empty [Optional] if none exists. */ fun getTransactionByHash(hash: Hash): RpcRequest<Optional<RPCTransaction>, RpcError> /** * Get transaction receipt by [hash], returning empty [Optional] if none exists. */ fun getTransactionReceipt(hash: Hash): RpcRequest<Optional<TransactionReceipt>, RpcError> /** * RLP encode and submit [signedTransaction]. */ fun sendRawTransaction(signedTransaction: TransactionSigned) = sendRawTransaction(signedTransaction.toRlp()) /** * Submit signed transaction bytes. */ fun sendRawTransaction(signedTransaction: ByteArray): RpcRequest<PendingTransaction, RpcError> /** * Fill the defaults (nonce, gas, gasPrice or 1559 fields) and return unsigned transaction for further * processing (signing + submission). */ fun fillTransaction(call: CallRequest): RpcRequest<TransactionUnsigned, RpcError> /** * Get logs by block [blockHash]. */ fun getLogs(blockHash: Hash): RpcRequest<List<Log>, RpcError> = getLogs(BlockId.Hash(blockHash)) /** * Get logs by block [blockNumber]. */ fun getLogs(blockNumber: Long): RpcRequest<List<Log>, RpcError> = getLogs(BlockId.Number(blockNumber)) /** * Get logs by block [blockId]. */ fun getLogs(blockId: BlockId): RpcRequest<List<Log>, RpcError> { val filter = when (blockId) { is BlockId.Hash -> LogFilter().atBlock(blockId) is BlockId.Name -> LogFilter().blockRange(blockId, blockId) is BlockId.Number -> LogFilter().blockRange(blockId, blockId) } return getLogs(filter) } /** * Get logs matching [filter]. */ fun getLogs(filter: LogFilter): RpcRequest<List<Log>, RpcError> /** * Watch for logs matching [filter]. Compared to [subscribeLogs], this function installs a filter and * intermittently polls it for new logs. It can be used to achieve streaming-like behavior if the provider * does not support subscriptions. * */ fun watchLogs(filter: LogFilter): RpcRequest<FilterPoller<Log>, RpcError> /** * Watch for new blocks. Compared to [subscribeNewHeads], this function installs a filter and intermittently * polls it for new logs. It can be used to achieve streaming-like behavior if the provider does not support * subscriptions. * */ fun watchNewBlocks(): RpcRequest<FilterPoller<Hash>, RpcError> /** * Watch for new pending transaction hashes. Compared to [subscribeNewPendingTransactionHashes], this function * installs a filter and intermittently polls it for new logs. It can be used to achieve streaming-like behavior * if the provider does not support subscriptions. * */ fun watchNewPendingTransactionHashes(): RpcRequest<FilterPoller<Hash>, RpcError> /** * Watch for new pending transactions. Compared to [subscribeNewPendingTransactions], this function installs * a filter and intermittently polls it for new logs. It can be used to achieve streaming-like behavior if the * provider does not support subscriptions. * */ fun watchNewPendingTransactions(): RpcRequest<FilterPoller<RPCTransaction>, RpcError> /** * Subscribe to logs matching [filter]. This function should be used instead of [watchLogs] if the * provider supports subscriptions. * */ fun subscribeLogs(filter: LogFilter): RpcSubscribe<Log, RpcError> /** * Subscribe to new block heads. This function should be used instead of [watchNewBlocks] if the * provider supports subscriptions. * */ fun subscribeNewHeads(): RpcSubscribe<BlockWithHashes, RpcError> /** * Subscribe to new pending transactions. This function should be used instead of [watchNewPendingTransactions] * if the provider supports subscriptions. * */ fun subscribeNewPendingTransactions(): RpcSubscribe<RPCTransaction, RpcError> /** * Subscribe to new pending transaction hashes. This function should be used instead of [watchNewPendingTransactions] * if the provider supports subscriptions. * */ fun subscribeNewPendingTransactionHashes(): RpcSubscribe<Hash, RpcError> }
13
null
1
9
85f3824fde9caaeeee91986ca177d005f7a225bb
15,184
ethers-kt
Apache License 2.0
app/src/main/java/com/william/easykt/widget/ClockView.kt
WeiLianYang
255,907,870
false
{"Kotlin": 714308, "Java": 30421}
/* * Copyright WeiLianYang * * 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.william.easykt.widget import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.Animation import android.view.animation.LinearInterpolator import com.william.base_component.extension.logD import com.william.base_component.extension.logV import com.william.easykt.R import java.util.* /** * 自定义闹钟视图 */ class ClockView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { /** 闹钟遮罩位图 */ private var clockMaskBitmap: Bitmap? = null /** 闹钟位图 */ private var clockBitmap: Bitmap? = null /** 画笔 */ private var paint: Paint? = null /** 画笔混合模式 */ private var xfermode: Xfermode? = null /** 闹钟矩形 */ private var clockRect: RectF? = null /** 闹钟视图旋转角度 */ private var angle = 0f /** 动画对象 */ private var animator: ValueAnimator? = null /** 初始角度 */ private var initAngle = 0f /** 时间对象 */ private var calendar: Calendar? = null /** 时间字体大小 */ private var textSize = 0 /** 时间字体颜色 */ private var textColor = 0 /** 时间文本起始 x 坐标 */ private var timeTextStartX = 0 /** 时间文本起始 y 坐标 */ private var timeTextStartY = 0 init { val typedArray = context.obtainStyledAttributes( attrs, R.styleable.ClockView ) textSize = typedArray.getDimensionPixelSize( R.styleable.ClockView_clockTextSize, 14 ) textColor = typedArray.getColor( R.styleable.ClockView_clockTextColor, Color.RED ) typedArray.recycle() init() } private fun init() { clockMaskBitmap = BitmapFactory.decodeResource(resources, R.drawable.clock_mask) clockBitmap = BitmapFactory.decodeResource(resources, R.drawable.clock) xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) paint = Paint(Paint.ANTI_ALIAS_FLAG) clockRect = RectF() val defaultText = "00:00:00" val timeTextRect = Rect() paint?.textSize = textSize.toFloat() paint?.getTextBounds(defaultText, 0, defaultText.length, timeTextRect) "timeTextRect: $timeTextRect".logD() timeTextStartX = (clockBitmap?.width ?: 0) / 2 timeTextStartY = (clockBitmap?.height ?: 0) / 2 - timeTextRect.centerY() calendar = Calendar.getInstance() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) { setMeasuredDimension(clockBitmap?.width ?: 0, clockBitmap?.height ?: 0) } else if (widthMode == MeasureSpec.AT_MOST) { setMeasuredDimension(clockBitmap?.width ?: 0, heightSize) } else if (heightMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSize, clockBitmap?.height ?: 0) } else { setMeasuredDimension(widthMeasureSpec, heightMeasureSpec) } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) clockRect?.set( 0f, 0f, clockBitmap?.width?.toFloat() ?: 0f, clockBitmap?.height?.toFloat() ?: 0f ) @Suppress("DEPRECATION") canvas.saveLayer(clockRect, paint, Canvas.ALL_SAVE_FLAG) canvas.drawBitmap(clockBitmap!!, 0f, 0f, paint) paint?.xfermode = xfermode //旋转画布 canvas.rotate( angle, (clockBitmap?.width ?: 0) / 2f, (clockBitmap?.height ?: 0) / 2f ) canvas.drawBitmap(clockMaskBitmap!!, 0f, 0f, paint) paint?.xfermode = null canvas.restore() updateTimeText(canvas) } /** 更新时间 */ private fun updateTimeText(canvas: Canvas) { val currentTimeMillis = System.currentTimeMillis() calendar?.timeInMillis = currentTimeMillis // 格式化时间 @SuppressLint("DefaultLocale") val timeStr = String.format( "%02d:%02d:%02d", calendar?.get(Calendar.HOUR_OF_DAY), calendar?.get(Calendar.MINUTE), calendar?.get(Calendar.SECOND) ) paint?.color = textColor paint?.textAlign = Paint.Align.CENTER canvas.drawText( timeStr, timeTextStartX.toFloat(), timeTextStartY.toFloat(), paint!! ) } /** 执行动画 */ fun performAnimation() { if (animator?.isRunning == true) { return } animator = ValueAnimator.ofFloat(0f, 360f).apply { addUpdateListener { animation: ValueAnimator -> angle = animation.animatedValue as Float + initAngle invalidate() } addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { calendar?.timeInMillis = System.currentTimeMillis() initAngle = (calendar?.get(Calendar.SECOND) ?: 0) * (360 / 60f) // 每秒6度 } }) duration = MINUTE.toLong() interpolator = LinearInterpolator() repeatCount = Animation.INFINITE start() } } companion object { const val MINUTE = 60 * 1000 } override fun onDetachedFromWindow() { super.onDetachedFromWindow() animator?.cancel() "clock view detached from window".logV() } }
0
Kotlin
6
21
6e33d7c32945a261117a7de8f2a388a5187637c5
6,450
EasyKotlin
Apache License 2.0
app/src/main/java/com/baruckis/kriptofolio/binding/BindingAdapters.kt
baruckis
121,292,770
false
null
/* * Copyright (C) 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.ascendio.mvvm.util.binding import android.databinding.BindingAdapter import android.view.View /** * Data Binding adapters specific to the app. */ object BindingAdapters { @JvmStatic @BindingAdapter("visibleGone") fun showHide(view: View, show: Boolean) { view.visibility = if (show) View.VISIBLE else View.GONE } }
6
null
9
80
4f727edbe3cc13d832b183d95834696a13c2b552
952
Kriptofolio
Apache License 2.0
src/main/kotlin/com/moqi/kotlin/ch02/2.3.2_2_GetWarmth.kt
HiAwesome
317,410,821
false
{"Maven POM": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 7, "Java Properties": 1, "Kotlin": 104}
package com.moqi.kotlin.ch02 /** * 使用 When 处理枚举类型 * * @author moqi On 12/2/20 16:00 */ enum class Color4 { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET } fun getWarmth(color: Color4) = when(color) { Color4.RED, Color4.ORANGE, Color4.YELLOW -> "warm" Color4.GREEN -> "neutral" Color4.BLUE, Color4.INDIGO, Color4.VIOLET -> "cold" } fun main() { println("getWarmth(Color4.INDIGO) = ${getWarmth(Color4.INDIGO)}") }
0
Kotlin
0
0
2228e08f304f06020917b7bea98f32b83ec22f69
442
kotlin-demo
Apache License 2.0
android/src/main/java/com/komoju/android/sdk/ui/screens/webview/WebChromeClient.kt
degica
851,401,843
false
{"Kotlin": 266785, "JavaScript": 1844}
package com.komoju.android.sdk.ui.screens.webview import android.webkit.ConsoleMessage import com.kevinnzou.web.AccompanistWebChromeClient internal class WebChromeClient : AccompanistWebChromeClient() { override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean = true }
0
Kotlin
0
4
28e708a0a4c253537509001ef5823172c5a02a55
289
komoju-mobile-sdk
MIT License
src/main/kotlin/com/chattriggers/ctjs/api/inventory/action/Action.kt
ChatTriggers
635,543,231
false
{"Kotlin": 680597, "JavaScript": 62357, "Java": 58141}
package com.chattriggers.ctjs.api.inventory.action import com.chattriggers.ctjs.api.client.Client import com.chattriggers.ctjs.api.client.Player import com.chattriggers.ctjs.api.inventory.Inventory import net.minecraft.screen.slot.SlotActionType abstract class Action(var slot: Int, var windowId: Int) { fun setSlot(slot: Int) = apply { this.slot = slot } fun setWindowId(windowId: Int) = apply { this.windowId = windowId } internal abstract fun complete() protected fun doClick(button: Int, mode: SlotActionType) { Client.getMinecraft().interactionManager?.clickSlot( windowId, slot, button, mode, Player.toMC(), ) } companion object { /** * Creates a new action. * The Inventory must be a container, see [Inventory.isContainer]. * The slot can be -999 for outside of the gui * * @param inventory the inventory to complete the action on * @param slot the slot to complete the action on * @param typeString the type of action to do (CLICK, DRAG, DROP, KEY) * @return the new action */ @JvmStatic fun of(inventory: Inventory, slot: Int, typeString: String) = when (Type.valueOf(typeString.uppercase())) { Type.CLICK -> ClickAction(slot, inventory.getWindowId()) Type.DRAG -> DragAction(slot, inventory.getWindowId()) Type.KEY -> KeyAction(slot, inventory.getWindowId()) Type.DROP -> DropAction(slot, inventory.getWindowId()) } } enum class Type { CLICK, DRAG, KEY, DROP } }
5
Kotlin
8
21
3921da9991ac09b872db63a1f4fd5e5cc928c032
1,717
ctjs
MIT License
src/main/kotlin/frc/team449/robot2024/auto/routines/World3.kt
blair-robot-project
736,410,238
false
{"Kotlin": 313771}
package frc.team449.robot2024.auto.routines import edu.wpi.first.wpilibj2.command.InstantCommand import edu.wpi.first.wpilibj2.command.WaitCommand import frc.team449.control.auto.ChoreoRoutine import frc.team449.control.auto.ChoreoRoutineStructure import frc.team449.control.auto.ChoreoTrajectory import frc.team449.robot2024.Robot import frc.team449.robot2024.auto.AutoUtil class FourPiece( robot: Robot, isRed: Boolean ) : ChoreoRoutineStructure { override val routine = ChoreoRoutine( drive = robot.drive, parallelEventMap = hashMapOf( 0 to AutoUtil.autoIntake(robot), 1 to AutoUtil.autoIntake(robot), 2 to AutoUtil.autoIntake(robot), 3 to AutoUtil.autoIntake(robot), ), stopEventMap = hashMapOf( 0 to AutoUtil.autoShoot(robot), 1 to AutoUtil.autoShoot(robot), 2 to AutoUtil.autoShoot(robot) .andThen( InstantCommand({ robot.drive.stop() }), robot.undertaker.stop(), robot.feeder.stop(), WaitCommand(0.050), robot.shooter.forceStop(), robot.pivot.moveStow(), ) ), debug = false, timeout = 0.0 ) override val trajectory: MutableList<ChoreoTrajectory> = if (isRed) { AutoUtil.transformForRed( ChoreoTrajectory.createTrajectory("4_Piece") ) } else { ChoreoTrajectory.createTrajectory("4_Piece") } }
0
Kotlin
1
6
3433d9c7da844b98aad062bd3e9215156658e2c5
1,446
robot2024
MIT License
core/src/test/java/com/kevinmost/koolbelt/util/AddOnlyMapTest.kt
kevinmost
57,383,899
false
null
package com.kevinmost.kotlin_toolbelt.util import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class AddOnlyMapTest { @Test fun `test plus-equals pair`() { var map = addOnlyMapOf("Foo" to 1) assertEquals(1, map.size) assertEquals(1, map["Foo"]) assertEquals(null, map["Bar"]) map += "Bar" to 2 assertEquals(2, map.size) assertEquals(1, map["Foo"]) assertEquals(2, map["Bar"]) } @Test fun `test plus-equals overwrite`() { var map = addOnlyMapOf("Foo" to listOf(1), "Bar" to listOf(2)) map += "Foo" to listOf(3) map["Foo"]!!.let { assertTrue(it.contains(3)) assertTrue(!it.contains(1)) } } @Test fun `test plus-equals map`() { var m1 = addOnlyMapOf("Foo" to 1, "Bar" to 2) val m2 = addOnlyMapOf("Baz" to 3) m1 += m2 assertEquals(3, m1.size) assertEquals(1, m1["Foo"]) assertEquals(2, m1["Bar"]) assertEquals(3, m1["Baz"]) } @Test fun `test set`() { val map = addOnlyMapOf("Foo" to 1) assertEquals(1, map["Foo"]) map["Foo"] = 2 assertEquals(2, map["Foo"]) assertEquals(1, map.size) } @Test fun `test plus pair`() { val combined = addOnlyMapOf("Foo" to 1) + ("Bar" to 2) + ("Baz" to 3) assertEquals(3, combined.size) assertEquals(1, combined["Foo"]) assertEquals(2, combined["Bar"]) assertEquals(3, combined["Baz"]) } @Test fun `test plus map`() { val combined = addOnlyMapOf("Foo" to 1) + addOnlyMapOf("Bar" to 2) + addOnlyMapOf("Baz" to 3) assertEquals(3, combined.size) assertEquals(1, combined["Foo"]) assertEquals(2, combined["Bar"]) assertEquals(3, combined["Baz"]) } }
0
null
2
3
2a35ac39f57810f7fbc044e780b9a838562e4554
1,702
koolbelt
Apache License 2.0
app/src/androidTest/java/com/cheise_proj/translator_ui_challenge/AddLanguageActivityTest.kt
alvinmarshall
253,371,012
false
{"Kotlin": 47011}
package com.cheise_proj.translator_ui_challenge import android.view.View import android.view.ViewGroup import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.rule.ActivityTestRule import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf import org.hamcrest.TypeSafeMatcher import org.hamcrest.core.IsInstanceOf import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class AddLanguageActivityTest { @Rule @JvmField var mActivityTestRule = ActivityTestRule(MainActivity::class.java) @Test fun addLanguageActivityTest() { val floatingActionButton = onView( allOf( withId(R.id.fab_add), childAtPosition( childAtPosition( withId(android.R.id.content), 0 ), 1 ), isDisplayed() ) ) floatingActionButton.perform(click()) val textView = onView( allOf( withId(R.id.tv_header), withText("ADD YOUR LANGUAGE"), childAtPosition( allOf( withId(R.id.root), childAtPosition( IsInstanceOf.instanceOf(android.widget.ScrollView::class.java), 0 ) ), 0 ), isDisplayed() ) ) textView.check(matches(withText("ADD YOUR LANGUAGE"))) val button = onView( allOf( withId(R.id.btn_save), childAtPosition( allOf( withId(R.id.root), childAtPosition( IsInstanceOf.instanceOf(android.widget.ScrollView::class.java), 0 ) ), 3 ), isDisplayed() ) ) button.check(matches(isDisplayed())) } private fun childAtPosition( parentMatcher: Matcher<View>, position: Int ): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("Child at position $position in parent ") parentMatcher.describeTo(description) } public override fun matchesSafely(view: View): Boolean { val parent = view.parent return parent is ViewGroup && parentMatcher.matches(parent) && view == parent.getChildAt(position) } } } }
0
Kotlin
0
0
83e205191c22aff1162c8a470e28dc1587ef5537
3,133
Translator-UI-Challenge
MIT License
src/main/kotlin/org/flowutils/MathUtils.kt
zzorn
34,295,078
false
null
package org.flowutils /** * */ /** * Tau is 2 Pi, see http://www.tauday.com */ public val Tau: Double = Math.PI * 2 /** * Floating point version of Tau. */ public val TauF: Float = Tau.toFloat() /** * Interpolate between the start and end values (and beyond). * @param t 0 corresponds to start, 1 to end. * * * @return interpolated value */ public fun mix(t: Float, start: Float, end: Float): Float = start + t * (end - start) /** * Interpolate between the start and end values (and beyond). * @param t 0 corresponds to start, 1 to end. * * * @return interpolated value */ public fun mix(t: Double, start: Double, end: Double): Double = start + t * (end - start)
0
Kotlin
0
0
1c729a7f323172402c783d08502984cf54c196bf
688
flowutils-kotlin
Apache License 2.0
opendc-experiments/opendc-experiments-greenifier/src/main/kotlin/org/opendc/experiments/greenifier/topology/ClusterSpecReader.kt
atlarge-research
79,902,234
false
null
/* * Copyright (c) 2021 AtLarge Research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opendc.experiments.rsuv.topology import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.MappingIterator import com.fasterxml.jackson.databind.ObjectReader import com.fasterxml.jackson.dataformat.csv.CsvMapper import com.fasterxml.jackson.dataformat.csv.CsvSchema import java.io.File import java.io.InputStream /** * A helper class for reading a cluster specification file. */ class ClusterSpecReader { /** * The [CsvMapper] to map the environment file to an object. */ private val mapper = CsvMapper() /** * The [ObjectReader] to convert the lines into objects. */ private val reader: ObjectReader = mapper.readerFor(Entry::class.java).with(schema) /** * Read the specified [file]. */ fun read(file: File): List<ClusterSpec> { return reader.readValues<Entry>(file).use { read(it) } } /** * Read the specified [input]. */ fun read(input: InputStream): List<ClusterSpec> { return reader.readValues<Entry>(input).use { read(it) } } /** * Convert the specified [MappingIterator] into a list of [ClusterSpec]s. */ private fun read(it: MappingIterator<Entry>): List<ClusterSpec> { val result = mutableListOf<ClusterSpec>() for (entry in it) { val def = ClusterSpec( entry.id, entry.name, entry.cpuCount, entry.cpuSpeed * 1000, // Convert to MHz entry.memCapacity * 1000, // Convert to MiB entry.nicCountPerHost, entry.bandWidthPerNic, entry.hostCount ) result.add(def) } return result } private open class Entry( @JsonProperty("ClusterID") val id: String, @JsonProperty("ClusterName") val name: String, @JsonProperty("Cores") val cpuCount: Int, @JsonProperty("Speed") val cpuSpeed: Double, @JsonProperty("Memory") val memCapacity: Double, @JsonProperty("NicCountPerHost") val nicCountPerHost: Int, @JsonProperty("BandwidthPerNic") val bandWidthPerNic: Double, @JsonProperty("numberOfHosts") val hostCount: Int ) companion object { /** * The [CsvSchema] that is used to parse the trace. */ private val schema = CsvSchema.builder() .addColumn("ClusterID", CsvSchema.ColumnType.STRING) .addColumn("ClusterName", CsvSchema.ColumnType.STRING) .addColumn("Cores", CsvSchema.ColumnType.NUMBER) .addColumn("Speed", CsvSchema.ColumnType.NUMBER) .addColumn("Memory", CsvSchema.ColumnType.NUMBER) .addColumn("NicCountPerHost", CsvSchema.ColumnType.NUMBER) .addColumn("BandwidthPerNic", CsvSchema.ColumnType.NUMBER) .addColumn("numberOfHosts", CsvSchema.ColumnType.NUMBER) .setAllowComments(true) .setColumnSeparator(';') .setUseHeader(true) .build() } }
9
null
41
64
616017ba78a0882fe38b9b171b2b0f68e593cd8d
4,255
opendc
MIT License
notification-infrastructure/src/main/kotlin/io/github/v1servicenotification/domain/notification/presentation/QueueController.kt
team-xquare
443,712,278
false
null
package io.github.v1servicenotification.domain.notification.presentation import io.github.v1servicenotification.detail.api.NotificationDetailApi import io.github.v1servicenotification.domain.notification.presentation.dto.Group import io.github.v1servicenotification.domain.notification.presentation.dto.Personal import org.springframework.cloud.aws.messaging.listener.SqsMessageDeletionPolicy import org.springframework.cloud.aws.messaging.listener.annotation.SqsListener import org.springframework.messaging.handler.annotation.Payload import org.springframework.stereotype.Component import javax.validation.Valid @Component class QueueController( private val notificationDetailApi: NotificationDetailApi ) { @SqsListener(value = ["group-notification.fifo"], deletionPolicy = SqsMessageDeletionPolicy.ALWAYS) fun groupNotification(@Payload @Valid group: Group) { notificationDetailApi.postGroupNotification(group.topic, group.content, group.threadId) } @SqsListener(value = ["notification.fifo"], deletionPolicy = SqsMessageDeletionPolicy.ALWAYS) fun notification(@Payload @Valid personal: Personal) { notificationDetailApi.postNotification(personal.userId, personal.topic, personal.content, personal.threadId) } }
2
Kotlin
0
8
d887a015adc21416dcd7d51e6676fbe318795381
1,263
v1-service-notification
MIT License
app/src/main/java/com/parsanatech/crazycoder/Adapters/contestInfoAdapter.kt
Yash-Parsana
605,085,323
false
{"Kotlin": 230490}
package com.parsanatech.crazycoder.Adapters import android.content.Context import android.content.Intent import android.provider.CalendarContract import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.parsanatech.crazycoder.LetUsChatActivity import com.parsanatech.crazycoder.R import com.parsanatech.crazycoder.models.contestModel import java.lang.Exception import java.util.* import kotlin.collections.ArrayList class contestInfoAdapter(private val listner:ImplementReminder): RecyclerView.Adapter<ContestViewholder>() { val lst=ArrayList<contestModel>() var context:Context?=null fun dataupdated(list:ArrayList<contestModel>) { lst.clear() lst.addAll(list) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContestViewholder { context=parent.context val xmlToview=LayoutInflater.from(context).inflate(R.layout.contest_layout,parent,false) val finalHolder=ContestViewholder(xmlToview) return finalHolder } override fun onBindViewHolder(holder: ContestViewholder, position: Int) { val currcontest=lst.get(position) holder.contestname.text=currcontest.name holder.startTime.text=currcontest.startTime holder.endTime.text=currcontest.endTime try { holder.reminder.setOnClickListener { listner.clickedOnReminder(currcontest) } } catch (e:Exception) { Log.e("Error in setting clicke listner on reminder",e.toString()) } } override fun getItemCount(): Int { return lst.size } } class ContestViewholder(xmlView:View):RecyclerView.ViewHolder(xmlView) { val contestname=xmlView.findViewById<TextView>(R.id.contestname) val startTime=xmlView.findViewById<TextView>(R.id.starttime) val endTime=xmlView.findViewById<TextView>(R.id.endtime) val reminder=xmlView.findViewById<ImageView>(R.id.reminder) } interface ImplementReminder{ fun clickedOnReminder(contestModel: contestModel) }
5
Kotlin
34
25
18a30228d43c6fd8e6841008ca4c98913e530337
2,275
CrazyCoderApp
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/cloudfront/ResponseHeadersStrictTransportSecurity.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 140726596}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.cloudfront import io.cloudshiftdev.awscdk.Duration import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Boolean import kotlin.Unit /** * Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the * header’s value. * * Example: * * ``` * // Using an existing managed response headers policy * S3Origin bucketOrigin; * Distribution.Builder.create(this, "myDistManagedPolicy") * .defaultBehavior(BehaviorOptions.builder() * .origin(bucketOrigin) * .responseHeadersPolicy(ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS) * .build()) * .build(); * // Creating a custom response headers policy -- all parameters optional * ResponseHeadersPolicy myResponseHeadersPolicy = ResponseHeadersPolicy.Builder.create(this, * "ResponseHeadersPolicy") * .responseHeadersPolicyName("MyPolicy") * .comment("A default policy") * .corsBehavior(ResponseHeadersCorsBehavior.builder() * .accessControlAllowCredentials(false) * .accessControlAllowHeaders(List.of("X-Custom-Header-1", "X-Custom-Header-2")) * .accessControlAllowMethods(List.of("GET", "POST")) * .accessControlAllowOrigins(List.of("*")) * .accessControlExposeHeaders(List.of("X-Custom-Header-1", "X-Custom-Header-2")) * .accessControlMaxAge(Duration.seconds(600)) * .originOverride(true) * .build()) * .customHeadersBehavior(ResponseCustomHeadersBehavior.builder() * .customHeaders(List.of(ResponseCustomHeader.builder().header("X-Amz-Date").value("some-value").override(true).build(), * ResponseCustomHeader.builder().header("X-Amz-Security-Token").value("some-value").override(false).build())) * .build()) * .securityHeadersBehavior(ResponseSecurityHeadersBehavior.builder() * .contentSecurityPolicy(ResponseHeadersContentSecurityPolicy.builder().contentSecurityPolicy("default-src * https:;").override(true).build()) * .contentTypeOptions(ResponseHeadersContentTypeOptions.builder().override(true).build()) * .frameOptions(ResponseHeadersFrameOptions.builder().frameOption(HeadersFrameOption.DENY).override(true).build()) * .referrerPolicy(ResponseHeadersReferrerPolicy.builder().referrerPolicy(HeadersReferrerPolicy.NO_REFERRER).override(true).build()) * .strictTransportSecurity(ResponseHeadersStrictTransportSecurity.builder().accessControlMaxAge(Duration.seconds(600)).includeSubdomains(true).override(true).build()) * .xssProtection(ResponseHeadersXSSProtection.builder().protection(true).modeBlock(false).reportUri("https://example.com/csp-report").override(true).build()) * .build()) * .removeHeaders(List.of("Server")) * .serverTimingSamplingRate(50) * .build(); * Distribution.Builder.create(this, "myDistCustomPolicy") * .defaultBehavior(BehaviorOptions.builder() * .origin(bucketOrigin) * .responseHeadersPolicy(myResponseHeadersPolicy) * .build()) * .build(); * ``` */ public interface ResponseHeadersStrictTransportSecurity { /** * A number that CloudFront uses as the value for the max-age directive in the * Strict-Transport-Security HTTP response header. */ public fun accessControlMaxAge(): Duration /** * A Boolean that determines whether CloudFront includes the includeSubDomains directive in the * Strict-Transport-Security HTTP response header. * * Default: false */ public fun includeSubdomains(): Boolean? = unwrap(this).getIncludeSubdomains() /** * A Boolean that determines whether CloudFront overrides the Strict-Transport-Security HTTP * response header received from the origin with the one specified in this response headers policy. */ public fun `override`(): Boolean /** * A Boolean that determines whether CloudFront includes the preload directive in the * Strict-Transport-Security HTTP response header. * * Default: false */ public fun preload(): Boolean? = unwrap(this).getPreload() /** * A builder for [ResponseHeadersStrictTransportSecurity] */ @CdkDslMarker public interface Builder { /** * @param accessControlMaxAge A number that CloudFront uses as the value for the max-age * directive in the Strict-Transport-Security HTTP response header. */ public fun accessControlMaxAge(accessControlMaxAge: Duration) /** * @param includeSubdomains A Boolean that determines whether CloudFront includes the * includeSubDomains directive in the Strict-Transport-Security HTTP response header. */ public fun includeSubdomains(includeSubdomains: Boolean) /** * @param override A Boolean that determines whether CloudFront overrides the * Strict-Transport-Security HTTP response header received from the origin with the one specified * in this response headers policy. */ public fun `override`(`override`: Boolean) /** * @param preload A Boolean that determines whether CloudFront includes the preload directive in * the Strict-Transport-Security HTTP response header. */ public fun preload(preload: Boolean) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity.Builder = software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity.builder() /** * @param accessControlMaxAge A number that CloudFront uses as the value for the max-age * directive in the Strict-Transport-Security HTTP response header. */ override fun accessControlMaxAge(accessControlMaxAge: Duration) { cdkBuilder.accessControlMaxAge(accessControlMaxAge.let(Duration.Companion::unwrap)) } /** * @param includeSubdomains A Boolean that determines whether CloudFront includes the * includeSubDomains directive in the Strict-Transport-Security HTTP response header. */ override fun includeSubdomains(includeSubdomains: Boolean) { cdkBuilder.includeSubdomains(includeSubdomains) } /** * @param override A Boolean that determines whether CloudFront overrides the * Strict-Transport-Security HTTP response header received from the origin with the one specified * in this response headers policy. */ override fun `override`(`override`: Boolean) { cdkBuilder.`override`(`override`) } /** * @param preload A Boolean that determines whether CloudFront includes the preload directive in * the Strict-Transport-Security HTTP response header. */ override fun preload(preload: Boolean) { cdkBuilder.preload(preload) } public fun build(): software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity, ) : CdkObject(cdkObject), ResponseHeadersStrictTransportSecurity { /** * A number that CloudFront uses as the value for the max-age directive in the * Strict-Transport-Security HTTP response header. */ override fun accessControlMaxAge(): Duration = unwrap(this).getAccessControlMaxAge().let(Duration::wrap) /** * A Boolean that determines whether CloudFront includes the includeSubDomains directive in the * Strict-Transport-Security HTTP response header. * * Default: false */ override fun includeSubdomains(): Boolean? = unwrap(this).getIncludeSubdomains() /** * A Boolean that determines whether CloudFront overrides the Strict-Transport-Security HTTP * response header received from the origin with the one specified in this response headers policy. */ override fun `override`(): Boolean = unwrap(this).getOverride() /** * A Boolean that determines whether CloudFront includes the preload directive in the * Strict-Transport-Security HTTP response header. * * Default: false */ override fun preload(): Boolean? = unwrap(this).getPreload() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): ResponseHeadersStrictTransportSecurity { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity): ResponseHeadersStrictTransportSecurity = CdkObjectWrappers.wrap(cdkObject) as? ResponseHeadersStrictTransportSecurity ?: Wrapper(cdkObject) internal fun unwrap(wrapped: ResponseHeadersStrictTransportSecurity): software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.cloudfront.ResponseHeadersStrictTransportSecurity } }
1
Kotlin
0
4
a18731816a3ec710bc89fb8767d2ab71cec558a6
9,108
kotlin-cdk-wrapper
Apache License 2.0
utils/epic-games-notifier/src/main/kotlin/dev/schlaubi/epic_games_notifier/GameRenderer.kt
DRSchlaubi
409,332,765
false
null
package dev.schlaubi.epic_games_notifier import dev.kord.common.DiscordTimestampStyle import dev.kord.common.toMessageFormat import dev.kord.rest.builder.message.EmbedBuilder import dev.schlaubi.mikbot.plugin.api.util.embed import io.ktor.http.* fun Game.toEmbed(): EmbedBuilder = embed { title = [email protected] description = [email protected] url = if (offerType == "BUNDLE") { "https://www.epicgames.com/store/${Config.COUNTRY_CODE.lowercase()}/bundles/$productSlug" } else { "https://www.epicgames.com/store/${Config.COUNTRY_CODE.lowercase()}/p/$urlSlug" } field { name = "Original Price" value = price.totalPrice.fmtPrice.originalPrice } field { name = "Available Until" value = promotions!!.promotionalOffers.flatMap { it.promotionalOffers }.first().endDate .toMessageFormat(DiscordTimestampStyle.LongDate) } image = (keyImages.firstOrNull { it.type == "OfferImageWide" } ?: keyImages.first()).url.encodeURLQueryComponent() val thumbnail = keyImages.firstOrNull { it.type == "Thumbnail" }?.url if (thumbnail != null) { thumbnail { url = thumbnail.encodeURLQueryComponent() } } }
23
Kotlin
11
31
ada5a2d41fa4f9aa4f6b387eaee5ba200d7e6e11
1,240
mikbot
MIT License
app/src/main/java/gmikhail/notes/viewmodel/EditViewModel.kt
gmikhail
607,787,948
false
null
package gmikhail.notes.viewmodel import androidx.lifecycle.* private const val MAX_UNDO = 1024 internal const val NEW_NOTE_ID = -1 class EditViewModel( private var _noteId: Int ) : ViewModel() { val noteId: Int get() = _noteId private val history = mutableListOf<HistoryRecord>() private var index = 0 private var inProgress = false private var _textState = MutableLiveData<HistoryRecord>() val textState: LiveData<HistoryRecord> = _textState private var _canUndo = MutableLiveData(false) val canUndo: LiveData<Boolean> = _canUndo private var _canRedo = MutableLiveData(false) val canRedo: LiveData<Boolean> = _canRedo fun updateNewNoteId(id: Int){ if(_noteId == NEW_NOTE_ID) _noteId = id } fun addToHistory(record: HistoryRecord){ if(inProgress) return if(history.isNotEmpty() && history.last().text == record.text) return history.add(record) if (history.lastIndex > MAX_UNDO) { history.removeAt(0) } index = history.lastIndex _textState.value = record updateCanUndoOrRedo() } fun undo(){ if(_canUndo.value == true){ inProgress = true index-- _textState.value = history[index] inProgress = false updateCanUndoOrRedo() } } fun redo(){ if(_canRedo.value == true){ inProgress = true index++ _textState.value = history[index] inProgress = false updateCanUndoOrRedo() } } private fun updateCanUndoOrRedo(){ _canUndo.value = history.isNotEmpty() && index - 1 in history.indices _canRedo.value = history.isNotEmpty() && index + 1 in history.indices } companion object { @Suppress("UNCHECKED_CAST") fun provideFactory(noteId: Int?): ViewModelProvider.Factory { return object : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { return EditViewModel(noteId ?: NEW_NOTE_ID) as T } } } } } data class HistoryRecord(val text: String, val cursorPosition: Int)
0
Kotlin
0
2
e21038cce8dc8800346d8597d604345303962875
2,277
android-notes
MIT License
2022/kotlin2022/src/test/kotlin/T13-Coroutine_Cancelation.kt
kyoya-p
253,926,918
false
null
import kotlinx.coroutines.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import kotlin.time.ExperimentalTime @ExperimentalTime @Suppress("NonAsciiCharacters") class `T13-Coroutine_Cancelation` { @Test fun `t01-コルーチンのキャンセル`(): Unit = runBlocking { var counter = 0 val job = async { // 100msに1ずつカウントアップ assertThrows<CancellationException> { // cancel()された場合例外が発生する。必要ならcatchして終了処理 while (isActive) { // while(true)の代わりにwhile(isActive)でループ delay(100) // suspend関数の入口(コンテキストスイッチ)でcancel()される yield() // 呼ぶべきsuspend関数がない場合は適切にyield()でコンテキストスイッチを発生させる counter++ } } } delay(350) // カウントが3に上がったころに.. job.cancel() // ..中断 delay(300) assert(counter == 3) // cancel()後のawait()は例外を発生させる assertThrows<CancellationException> { job.await() //例外 } } @Test // 親コルーチンがキャンセルされたら子コルーチンもキャンセルされる fun `t02-launchされたコルーチン`(): Unit = runBlocking { var res = "" val j = launch { launch { delay(100); res += "2" } launch { delay(50); res += "1" } delay(30) res += "0" } delay(70) j.cancel() delay(70) println(res) assert(res == "01") } @Test // コンテキストを共有する子コルーチンがまとめてキャンセルされる // launch{}とかはデフォルトで親のコンテキストを共有する fun `t03-コルーチンのコンテキスト`(): Unit = runBlocking { val jobHandlerEven = Job() val jobHandlerOdd = Job() var res = "" suspend fun f(i: Int) { delay(i * 10L) res += "$i" } for (i in 0..9) { if (i % 2 == 0) launch(jobHandlerEven) { f(i) } else launch(jobHandlerOdd) { f(i) } } delay(45) jobHandlerOdd.cancel() // 奇数番目のjobをまとめてキャンセル delay(100) println(res) assert(res == "0123468") } }
16
null
1
2
37d1f1df3e512b968c3677239316130f21d4836f
2,013
samples
Apache License 2.0
kotpass/src/main/kotlin/app/keemobile/kotpass/database/modifiers/Credentials.kt
keemobile
384,214,968
false
null
package app.keemobile.kotpass.database.modifiers import app.keemobile.kotpass.database.Credentials import app.keemobile.kotpass.database.KeePassDatabase import app.keemobile.kotpass.models.Meta import java.time.Instant /** * Modifies [Credentials] field in [KeePassDatabase] with result of [block] lambda. * If new [Credentials.passphrase] supplied modifies [Meta.masterKeyChanged] field. */ inline fun KeePassDatabase.modifyCredentials( crossinline block: Credentials.() -> Credentials ): KeePassDatabase { val newCredentials = block(credentials) val isModified = !credentials.passphrase?.getHash() .contentEquals(newCredentials.passphrase?.getHash()) val newDatabase = when (this) { is KeePassDatabase.Ver3x -> copy(credentials = newCredentials) is KeePassDatabase.Ver4x -> copy(credentials = newCredentials) } return if (isModified) { newDatabase.modifyMeta { copy(masterKeyChanged = Instant.now()) } } else { newDatabase } }
3
Kotlin
1
9
0e123c087c6ec516492f33c0140497debfb3ba15
1,027
kotpass
MIT License
app/src/main/java/com/finderbar/jovian/viewmodels/discuss/DiscussVoteVM.kt
finderbar
705,707,975
false
{"Kotlin": 665596, "Java": 45822}
package com.finderbar.jovian.viewmodels.discuss import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.support.v4.content.ContextCompat import android.view.View import com.apollographql.apollo.ApolloMutationCall import com.finderbar.jovian.R import com.finderbar.jovian.apolloClient import com.finderbar.jovian.enqueue import com.finderbar.jovian.models.Command import com.finderbar.jovian.models.ErrorMessage import com.finderbar.jovian.models.InputVote import kotlinx.android.synthetic.main.item_discuss_question.view.* import mutation.SaveAnswerVoteMutation import mutation.SaveQuestionFavoriteMutation import mutation.SaveQuestionViewMutation import mutation.SaveQuestionVoteMutation import type.VoteStatus class DiscussVoteVM: ViewModel() { var errorMessage: MutableLiveData<ErrorMessage> = MutableLiveData() var result: MutableLiveData<Command> = MutableLiveData() private var saveVoteQuestion: ApolloMutationCall<SaveQuestionVoteMutation.Data>? = null private var saveVoteAnswer: ApolloMutationCall<SaveAnswerVoteMutation.Data>? = null private var saveFavoriteQuestion: ApolloMutationCall<SaveQuestionFavoriteMutation.Data>? = null private var saveQuestionView: ApolloMutationCall<SaveQuestionViewMutation.Data>? = null fun questionVote(holder: View, _id: String, vote: InputVote) { saveVoteQuestion?.cancel() saveVoteQuestion = apolloClient.mutate(SaveQuestionVoteMutation.builder()._id(_id).vote(vote.get()).build()) saveVoteQuestion?.enqueue({ val error = it.data()?.createQuestionVote()?.error(); if(error != null) { errorMessage.postValue(error.status()?.let { it1 -> error.statusCode()?.toLong()?.let { it2 -> ErrorMessage(it1, it2, error.message()!!) } }) } else { val datum = it.data()?.createQuestionVote()?.command() result.postValue(Command(datum?.id()!!, datum?.status()!!, datum.modifyFlag()!!, datum.statusCode()!!, datum.message()!!)) var totalCount: Int; if(vote.status == VoteStatus.UP) { var helper = holder.up_vote_helper if (helper.text == "0") { holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.colorPrimary)) holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) + 1 helper.text = "1" } else { holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) - 1 helper.text = "0" } } else { var helper = holder.down_vote_helper if (helper.text == "0") { holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.colorPrimary)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) - 1 helper.text = "1" } else { holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) + 1 helper.text = "0" } } holder.txt_vote_count.text = totalCount.toString() } }, {errorMessage.postValue(ErrorMessage("fail", 500, it.message!!))}) } fun questionFavorite(holder: View, _id: String, userId: String) { saveFavoriteQuestion?.cancel() saveFavoriteQuestion = apolloClient.mutate(SaveQuestionFavoriteMutation.builder()._id(_id).userId(userId).build()) saveFavoriteQuestion?.enqueue({ val datum = it.data()?.createQuestionFavorite()?.command() result.postValue(Command(datum?.id()!!, datum?.status()!!, datum.modifyFlag()!!, datum.statusCode()!!, datum.message()!!)) var helper = holder.favorite_helper if (helper.text == "0") { holder.favorite.icon.color(ContextCompat.getColor(holder.context, R.color.pf_gold)) helper.text = "1" } else { holder.favorite.icon.color(ContextCompat.getColor(holder.context, R.color.pf_white)) helper.text = "0" } }, {errorMessage.postValue(ErrorMessage("fail", 500, it.message!!))}) } fun questionView(holder: View, _id: String, userId: String) { saveQuestionView?.cancel() saveQuestionView = apolloClient.mutate(SaveQuestionViewMutation.builder()._id(_id).userId(userId).build()) saveQuestionView?.enqueue({ val datum = it.data()?.createQuestionView()?.command() result.postValue(Command(datum?.id()!!, datum?.status()!!, datum.modifyFlag()!!, datum.statusCode()!!, datum.message()!!)) }, {errorMessage.postValue(ErrorMessage("fail", 500, it.message!!))}) } fun answerVote(holder: View, _id: String, vote: InputVote) { saveVoteAnswer?.cancel() saveVoteAnswer = apolloClient.mutate(SaveAnswerVoteMutation.builder()._id(_id).vote(vote.get()).build()) saveVoteAnswer?.enqueue({ val error = it.data()?.createAnswerVote()?.error(); if(error != null) { errorMessage.postValue(error.status()?.let { it1 -> error.statusCode()?.toLong()?.let { it2 -> ErrorMessage(it1, it2, error.message()!!) } }) } else { val datum = it.data()?.createAnswerVote()?.command() result.postValue(Command(datum?.id()!!, datum?.status()!!, datum.modifyFlag()!!, datum.statusCode()!!, datum.message()!!)) var totalCount: Int; if(vote.status == VoteStatus.UP) { var helper = holder.up_vote_helper if (helper.text == "0") { holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.colorPrimary)) holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_grey)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) + 1 helper.text = "1"; } else { totalCount = Integer.parseInt(holder.txt_vote_count.text as String) - 1 holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_grey)) holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_grey)) helper.text = "0"; } } else { var helper = holder.down_vote_helper if (helper.text == "0") { holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.colorPrimary)) holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_grey)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) - 1 helper.text = "1"; } else { holder.down_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_grey)) holder.up_vote.icon.color(ContextCompat.getColor(holder.context, R.color.pf_grey)) totalCount = Integer.parseInt(holder.txt_vote_count.text as String) + 1 helper.text = "0"; } } holder.txt_vote_count.text = totalCount.toString() } }, {errorMessage.postValue(ErrorMessage("fail", 500, it.message!!))}) } override fun onCleared() { super.onCleared() saveVoteQuestion?.cancel() saveVoteAnswer?.cancel() saveFavoriteQuestion?.cancel() } }
0
Kotlin
0
0
63bf5531f367d1892d77151c1baa50789f814b07
8,479
finderbar-app
MIT License
app/src/main/java/com/android/airmart/viewmodel/PostProductViewModel.kt
air-mrt
180,135,046
false
null
package com.android.airmart.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.airmart.data.api.model.ProductResponse import com.android.airmart.data.entity.Product import com.android.airmart.repository.ProductRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Response import java.net.ConnectException class PostProductViewModel (private val productRepository: ProductRepository) : ViewModel(){ private val _postResponse = MutableLiveData<Response<ProductResponse>>() val postResponse: LiveData<Response<ProductResponse>> get() = _postResponse fun postProduct(file: MultipartBody.Part?, productJson: RequestBody, token:String) = viewModelScope.launch { try{ _postResponse.postValue(productRepository.postProductAPI(file,productJson,token)) } catch (e:ConnectException){ this.coroutineContext.cancel() } } }
0
Kotlin
0
0
b41e65489d3285c9c3f3638eee4e40231a4f2b11
1,161
android-app
MIT License
app/src/main/java/com/example/pokescanner/screens/HomeScreen.kt
lostdanielfound
744,651,808
false
{"Kotlin": 50445}
package com.example.pokescanner.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun HomeScreen(modifier: Modifier = Modifier) { //Column( ////Camera view here //) Box( contentAlignment = Alignment.Center, modifier = modifier ) { Text("HomeScreen") } }
0
Kotlin
0
0
833e5408fdfa8e6ca8f7387f444e5a8f82b6758e
580
PokeScanner
MIT License
powdroid/src/main/java/com/tubbert/powdroid/events/TaskScheduler.kt
paulotubbert
109,696,340
false
null
package com.tubbert.powdroid.events import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit /** * */ object TaskScheduler { fun createSingleTaskScheduler( delayMs: Long, subscribeScheduler: Scheduler = AndroidSchedulers.mainThread(), observeScheduler: Scheduler = AndroidSchedulers.mainThread()) : Observable<Unit> { return Observable.just(Unit).delay(delayMs, TimeUnit.MILLISECONDS) .subscribeOn(subscribeScheduler) .observeOn(observeScheduler) } }
0
Kotlin
0
0
6cc16a405e0ce53b904abee5a72f694ac5138b3a
652
PowDroid
Apache License 2.0
src/main/kotlin/com/github/surdus/http/content/multipart/MultipartContent.kt
surdus
116,360,441
false
null
package com.github.surdus.http.content.multipart import com.github.surdus.http.client.toContentBody import com.github.surdus.http.content.Content import org.apache.http.HttpEntity import org.apache.http.entity.mime.MultipartEntityBuilder import java.io.InputStream class MultipartContent(fill: MultipartContent.() -> Unit): Content { val parts = mutableMapOf<String, MultipartContentPart>() init { this.fill() } fun part(name: String, part: MultipartContentPart) { parts[name] = part } override fun toHttpEntity(): HttpEntity { return MultipartEntityBuilder.create().also { parts.forEach { name, part -> it.addPart(name, toContentBody(part)) } }.build() } } interface MultipartContentPart class StringContentPart(val data: String): MultipartContentPart class StreamContentPart(val inputStream: InputStream, val fileName: String? = null, val size: Long?): MultipartContentPart
0
Kotlin
0
0
ccc2b577a4d7b3418b9325e9e103e28a348d3316
1,032
kt-http-client
Apache License 2.0
plot-base/src/commonMain/kotlin/org/jetbrains/letsPlot/core/interact/feedback/WheelZoomFeedback.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2024. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.core.interact.feedback import org.jetbrains.letsPlot.commons.geometry.DoubleRectangle import org.jetbrains.letsPlot.commons.registration.Disposable import org.jetbrains.letsPlot.core.interact.InteractionContext import org.jetbrains.letsPlot.core.interact.InteractionUtil import org.jetbrains.letsPlot.core.interact.ToolFeedback import org.jetbrains.letsPlot.core.interact.mouse.MouseWheelInteraction import kotlin.math.abs class WheelZoomFeedback( private val onCompleted: (targetId: String?, dataBounds: DoubleRectangle) -> Unit ) : ToolFeedback { override fun start(ctx: InteractionContext): Disposable { val interaction = MouseWheelInteraction(ctx) interaction.loop( onZoomed = { (target, zoomOrigin, zoomDelta) -> val zoomStep = if (abs(zoomDelta) > 0.3) { // assume this is a wheel scroll - triggered less often, so we can use a fixed step 0.08 } else { // assume this is a touchpad zoom - triggered more often, so decrease the step to prevent too fast zoom. // Use zoomDelta to follow gesture inertia. abs(zoomDelta) / 10 } val factor = if (zoomDelta < 0) { 1 - zoomStep // zoom in, reduce viewport } else { 1 + zoomStep // zoom out, enlarge viewport } val viewport = InteractionUtil.viewportFromScale(target.geomBounds, factor, zoomOrigin) val (dataBounds, _) = target.applyViewport(viewport, ctx) onCompleted(target.id, dataBounds) } ) return object : Disposable { override fun dispose() { interaction.dispose() } } } }
152
null
51
1,561
c8db300544974ddd35a82a90072772b788600ac6
2,009
lets-plot
MIT License
plugins/markdown/src/org/intellij/plugins/markdown/injection/MarkdownCodeFenceUtils.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.injection import com.intellij.lang.ASTNode import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.templateLanguages.OuterLanguageElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFenceImpl import org.intellij.plugins.markdown.lang.psi.util.hasType import org.intellij.plugins.markdown.lang.psi.util.parents import org.intellij.plugins.markdown.util.MarkdownPsiUtil import org.jetbrains.annotations.ApiStatus /** * Utility functions used to work with Markdown Code Fences */ object MarkdownCodeFenceUtils { /** Check if [node] is of CODE_FENCE type */ fun isCodeFence(node: ASTNode) = node.hasType(MarkdownTokenTypeSets.CODE_FENCE) /** Check if [node] inside CODE_FENCE */ fun inCodeFence(node: ASTNode) = node.parents(withSelf = false).any { it.hasType(MarkdownTokenTypeSets.CODE_FENCE) } /** * Consider using [MarkdownCodeFence.obtainFenceContent] since it caches its result. * * Get content of code fence as list of [PsiElement] * * @param withWhitespaces defines if whitespaces (including blockquote chars `>`) should be * included in returned list. Otherwise, only new-line would be added. * * @return non-empty list of elements or null */ @JvmStatic @ApiStatus.ScheduledForRemoval @Deprecated("Use getContent(MarkdownCodeFence) instead.") fun getContent(host: MarkdownCodeFenceImpl, withWhitespaces: Boolean): List<PsiElement>? { val children = host.firstChild?.siblings(forward = true, withSelf = true) ?: return null var elements = children.filter { (it !is OuterLanguageElement && (it.node.elementType == MarkdownTokenTypes.CODE_FENCE_CONTENT || (MarkdownPsiUtil.WhiteSpaces.isNewLine(it)) //WHITE_SPACES may also include `>` || (withWhitespaces && MarkdownTokenTypeSets.WHITE_SPACES.contains(it.elementType)) ) ) }.toList() //drop new line right after code fence lang definition if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.first())) { elements = elements.drop(1) } //drop new right before code fence end if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.last())) { elements = elements.dropLast(1) } return elements.takeIf { it.isNotEmpty() } } /** * Consider using [MarkdownCodeFence.obtainFenceContent], since it caches its result. */ @JvmStatic fun getContent(host: MarkdownCodeFence, withWhitespaces: Boolean): List<PsiElement>? { @Suppress("DEPRECATION") return getContent(host as MarkdownCodeFenceImpl, withWhitespaces) } /** * Check that code fence is reasonably formatted to accept injections * * Basically, it means that it has start and end code fence and at least * one line (even empty) of text. */ @JvmStatic @ApiStatus.ScheduledForRemoval @Deprecated("Use isAbleToAcceptInjections(MarkdownCodeFence) instead.") fun isAbleToAcceptInjections(host: MarkdownCodeFenceImpl): Boolean { if (host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_END) } || host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_START) }) { return false } val newlines = host.children.count { MarkdownPsiUtil.WhiteSpaces.isNewLine(it) } return newlines >= 2 } @JvmStatic fun isAbleToAcceptInjections(host: MarkdownCodeFence): Boolean { @Suppress("DEPRECATION") return isAbleToAcceptInjections(host as MarkdownCodeFenceImpl) } /** * Get valid empty range (in terms of Injection) for this code fence. * * Note, that this function should be used only if [getContent] * returns null */ @JvmStatic @ApiStatus.ScheduledForRemoval @Deprecated("Use getEmptyRange(MarkdownCodeFence) instead.") fun getEmptyRange(host: MarkdownCodeFenceImpl): TextRange { val start = host.children.find { it.hasType(MarkdownTokenTypes.FENCE_LANG) } ?: host.children.find { it.hasType(MarkdownTokenTypes.CODE_FENCE_START) } return TextRange.from(start!!.startOffsetInParent + start.textLength + 1, 0) } fun getEmptyRange(host: MarkdownCodeFence): TextRange { @Suppress("DEPRECATION") return getEmptyRange(host as MarkdownCodeFenceImpl) } /** * Get code fence if [element] is part of it. * * Would also work for injected elements. */ fun getCodeFence(element: PsiElement): MarkdownCodeFence? { return InjectedLanguageManager.getInstance(element.project).getInjectionHost(element) as? MarkdownCodeFence? ?: PsiTreeUtil.getParentOfType(element, MarkdownCodeFence::class.java) } /** * Get indent for this code fence. * * If code-fence is blockquoted indent may include `>` char. * Note that indent should be used only for non top-level fences, * top-level fences should use indentation from formatter. */ @JvmStatic fun getIndent(element: MarkdownCodeFence): String? { val document = PsiDocumentManager.getInstance(element.project).getDocument(element.containingFile) ?: return null val offset = element.textOffset val lineStartOffset = document.getLineStartOffset(document.getLineNumber(offset)) return document.getText(TextRange.create(lineStartOffset, offset)).replace("[^> ]".toRegex(), " ") } }
284
null
5162
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
5,907
intellij-community
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo012.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * 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.matrix.android.sdk.internal.database.migration import io.realm.DynamicRealm import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesContent import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntityFields import org.matrix.android.sdk.internal.database.model.EventEntityFields import org.matrix.android.sdk.internal.database.model.RoomSummaryEntityFields import org.matrix.android.sdk.internal.database.model.SpaceChildSummaryEntityFields import org.matrix.android.sdk.internal.di.MoshiProvider import org.matrix.android.sdk.internal.util.database.RealmMigrator internal class MigrateSessionTo012(realm: DynamicRealm) : RealmMigrator(realm, 12) { override fun doMigrate(realm: DynamicRealm) { val joinRulesContentAdapter = MoshiProvider.providesMoshi().adapter(RoomJoinRulesContent::class.java) realm.schema.get("RoomSummaryEntity") ?.addField(RoomSummaryEntityFields.JOIN_RULES_STR, String::class.java) ?.transform { obj -> val joinRulesEvent = realm.where("CurrentStateEventEntity") .equalTo(CurrentStateEventEntityFields.ROOM_ID, obj.getString(RoomSummaryEntityFields.ROOM_ID)) .equalTo(CurrentStateEventEntityFields.TYPE, EventType.STATE_ROOM_JOIN_RULES) .findFirst() val roomJoinRules = joinRulesEvent?.getObject(CurrentStateEventEntityFields.ROOT.`$`) ?.getString(EventEntityFields.CONTENT)?.let { joinRulesContentAdapter.fromJson(it)?.joinRules } obj.setString(RoomSummaryEntityFields.JOIN_RULES_STR, roomJoinRules?.name) } realm.schema.get("SpaceChildSummaryEntity") ?.addField(SpaceChildSummaryEntityFields.SUGGESTED, Boolean::class.java) ?.setNullable(SpaceChildSummaryEntityFields.SUGGESTED, true) } }
75
null
6
9
70e4c3c6026f9722444ec60ec142f3a4eef2e089
2,690
tchap-android
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/HeartBrokenOutlined.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/HeartBrokenOutlined") @file:JsNonModule package mui.icons.material @JsName("default") external val HeartBrokenOutlined: SvgIconComponent
12
Kotlin
5
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
220
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/example/sumador/ui/SummaryScreen.kt
JR1331
719,062,627
false
{"Kotlin": 34352}
/* * Copyright (C) 2023 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.sumador.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Divider import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.example.cupcake.R import com.example.sumador.data.OrderUiState /** * This composable expects [orderUiState] that represents the order state, [onCancelButtonClicked] * lambda that triggers canceling the order and passes the final order to [onSendButtonClicked] * lambda */ @Composable fun OrderSummaryScreen( orderUiState: OrderUiState, number1: Int, number2: Int, onCancelButtonClicked: () -> Unit, modifier: Modifier = Modifier ) { val items = listOf( Pair("Number 1", number1), Pair("Number 2", number2), Pair("Sum", (number1 + number2).toString()) // Agrega esta línea para mostrar la suma ) val numberPairs = rememberSaveable { mutableListOf<Pair<String, String>>() } // Añade las parejas de números a la lista numberPairs.add(Pair("Number 1", number1.toString())) numberPairs.add(Pair("Number 2", number2.toString())) LazyColumn( modifier = modifier, verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { items.forEach { item -> item { Text(item.first.uppercase()) Text(text = item.second.toString(), fontWeight = FontWeight.Bold) Divider(thickness = dimensionResource(R.dimen.thickness_divider)) } } // Muestra las parejas de números en el historial numberPairs.forEach { pair -> item { Row { Text("${pair.first}: ${pair.second}") } } } item { Spacer(modifier = Modifier.height(16.dp)) } item { Spacer(modifier = Modifier.height(16.dp)) } item { OutlinedButton( modifier = Modifier.fillMaxWidth(), onClick = onCancelButtonClicked ) { Text(stringResource(R.string.cancel)) } } } }
0
Kotlin
0
0
eec91a0e740907d3dcb3824bae79711b97c31235
3,390
Sumador
Apache License 2.0
examples/purchase-tester/src/main/java/com/revenuecat/purchasetester/ConfigureFragment.kt
RevenueCat
127,346,826
false
null
package com.revenuecat.purchasetester import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.revenuecat.purchases.LogLevel import com.revenuecat.purchases.Purchases import com.revenuecat.purchases.PurchasesConfiguration import com.revenuecat.purchases.amazon.AmazonConfiguration import com.revenuecat.purchases_sample.BuildConfig import com.revenuecat.purchases_sample.R import com.revenuecat.purchases_sample.databinding.FragmentConfigureBinding import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import java.net.MalformedURLException import java.net.URL class ConfigureFragment : Fragment() { lateinit var binding: FragmentConfigureBinding private lateinit var dataStoreUtils: DataStoreUtils override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { dataStoreUtils = DataStoreUtils(requireActivity().applicationContext.configurationDataStore) binding = FragmentConfigureBinding.inflate(inflater) binding.verificationOptionsInput.adapter = ArrayAdapter( requireContext(), android.R.layout.simple_spinner_item, // Trusted entitlements: Commented out until ready to be made public // EntitlementVerificationMode.values() emptyList<String>(), ) setupSupportedStoresRadioButtons() lifecycleScope.launch { dataStoreUtils.getSdkConfig().onEach { sdkConfiguration -> binding.apiKeyInput.setText(sdkConfiguration.apiKey) binding.proxyUrlInput.setText(sdkConfiguration.proxyUrl) val storeToCheckId = if (sdkConfiguration.useAmazon) { R.id.amazon_store_radio_id } else R.id.google_store_radio_id binding.storeRadioGroup.check(storeToCheckId) }.collect() } @Suppress("EmptyFunctionBlock") binding.proxyUrlInput.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { try { if (!s.isNullOrEmpty()) { val url = URL(s.toString()) Purchases.proxyURL = url } else { Purchases.proxyURL = null } } catch (e: MalformedURLException) { Purchases.proxyURL = null } } override fun afterTextChanged(s: Editable?) {} }) binding.continueButton.setOnClickListener { if (!validateInputs()) return@setOnClickListener binding.continueButton.isEnabled = false lifecycleScope.launch { configureSDK() navigateToLoginFragment() } } binding.logsButton.setOnClickListener { navigateToLogsFragment() } binding.proxyButton.setOnClickListener { navigateToProxyFragment() } binding.amazonStoreRadioId.setOnCheckedChangeListener { _, isChecked -> // Disable observer mode options if Amazon binding.observerModeCheckbox.isEnabled = !isChecked // Toggle observer mode off only if Amazon is checked if (isChecked) { binding.observerModeCheckbox.isChecked = false } } return binding.root } private suspend fun configureSDK() { val apiKey = binding.apiKeyInput.text.toString() val proxyUrl = binding.proxyUrlInput.text?.toString() ?: "" // Trusted entitlements: Commented out until ready to be made public // val verificationModeIndex = binding.verificationOptionsInput.selectedItemPosition // Trusted entitlements: Commented out until ready to be made public // val entitlementVerificationMode = EntitlementVerificationMode.values()[verificationModeIndex] val useAmazonStore = binding.storeRadioGroup.checkedRadioButtonId == R.id.amazon_store_radio_id val useObserverMode = binding.observerModeCheckbox.isChecked val application = (requireActivity().application as MainApplication) if (proxyUrl.isNotEmpty()) Purchases.proxyURL = URL(proxyUrl) Purchases.logLevel = LogLevel.VERBOSE val configurationBuilder = if (useAmazonStore) { AmazonConfiguration.Builder(application, apiKey) } else PurchasesConfiguration.Builder(application, apiKey) val configuration = configurationBuilder .diagnosticsEnabled(true) // Trusted entitlements: Commented out until ready to be made public // .entitlementVerificationMode(entitlementVerificationMode) .observerMode(useObserverMode) .build() Purchases.configure(configuration) if (useObserverMode) { ObserverModeBillingClient.start(application, application.logHandler) } // set attributes to store additional, structured information for a user in RevenueCat. // More info: https://docs.revenuecat.com/docs/user-attributes Purchases.sharedInstance.setAttributes(mapOf("favorite_cat" to "garfield")) Purchases.sharedInstance.updatedCustomerInfoListener = application dataStoreUtils.saveSdkConfig(SdkConfiguration(apiKey, proxyUrl, useAmazonStore)) } private fun setupSupportedStoresRadioButtons() { val supportedStores = BuildConfig.SUPPORTED_STORES.split(",") if (!supportedStores.contains("google")) { binding.googleStoreRadioId.isEnabled = false binding.googleUnavailableTextView.visibility = View.VISIBLE } if (!supportedStores.contains("amazon")) { binding.amazonStoreRadioId.isEnabled = false binding.amazonUnavailableTextView.visibility = View.VISIBLE } } private fun navigateToLoginFragment() { val directions = ConfigureFragmentDirections.actionConfigureFragmentToLoginFragment() findNavController().navigate(directions) } private fun navigateToLogsFragment() { val directions = ConfigureFragmentDirections.actionConfigureFragmentToLogsFragment() findNavController().navigate(directions) } private fun navigateToProxyFragment() { val directions = ConfigureFragmentDirections.actionConfigureFragmentToProxySettingsBottomSheetFragment() findNavController().navigate(directions) } private fun validateInputs(): Boolean { return validateApiKey() && validateProxyURL() } private fun validateApiKey(): Boolean { val errorMessages = mutableListOf<String>() if (binding.apiKeyInput.text?.isNotEmpty() != true) errorMessages.add("API Key is empty") if (errorMessages.isNotEmpty()) showError("API Key errors: $errorMessages") return errorMessages.isEmpty() } private fun validateProxyURL(): Boolean { val proxyURLString = binding.proxyUrlInput.text?.toString() if (proxyURLString?.isEmpty() != false) return true val errorMessages = mutableListOf<String>() try { URL(proxyURLString) } catch (e: MalformedURLException) { errorMessages.add("Invalid proxy URL. Could not convert to URL.") } if (errorMessages.isNotEmpty()) showError("Proxy URL errors: $errorMessages") return errorMessages.isEmpty() } private fun showError(msg: String) { context?.let { MaterialAlertDialogBuilder(it) .setMessage(msg) .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() } .show() } } }
30
null
52
253
dad31133777389a224e9a570daec17f5c4c795ca
8,350
purchases-android
MIT License
feature-staking-impl/src/main/java/jp/co/soramitsu/feature_staking_impl/domain/rewards/RewardCalculator.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.feature_staking_impl.domain.rewards import jp.co.soramitsu.common.utils.fractionToPercentage import jp.co.soramitsu.common.utils.median import jp.co.soramitsu.common.utils.sumByBigInteger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.math.BigDecimal import java.math.BigInteger import kotlin.math.pow private const val PARACHAINS_ENABLED = false private const val MINIMUM_INFLATION = 0.025 private val INFLATION_IDEAL = if (PARACHAINS_ENABLED) 0.2 else 0.1 private val STAKED_PORTION_IDEAL = if (PARACHAINS_ENABLED) 0.5 else 0.75 private val INTEREST_IDEAL = INFLATION_IDEAL / STAKED_PORTION_IDEAL private const val DECAY_RATE = 0.05 const val DAYS_IN_YEAR = 365 class PeriodReturns( val gainAmount: BigDecimal, val gainPercentage: BigDecimal ) class RewardCalculator( val validators: List<RewardCalculationTarget>, val totalIssuance: BigInteger ) { private val totalStaked = validators.sumByBigInteger(RewardCalculationTarget::totalStake).toDouble() private val stakedPortion = totalStaked / totalIssuance.toDouble() private val yearlyInflation = calculateYearlyInflation() private val averageValidatorStake = totalStaked / validators.size private val averageValidatorRewardPercentage = yearlyInflation / stakedPortion private val apyByValidator = validators.associateBy( keySelector = RewardCalculationTarget::accountIdHex, valueTransform = ::calculateValidatorAPY ) private val expectedAPY = calculateExpectedAPY() private fun calculateExpectedAPY(): Double { val medianCommission = validators.map { it.commission.toDouble() }.median() return averageValidatorRewardPercentage * (1 - medianCommission) } private fun calculateValidatorAPY(validator: RewardCalculationTarget): Double { val yearlyRewardPercentage = averageValidatorRewardPercentage * averageValidatorStake / validator.totalStake.toDouble() return yearlyRewardPercentage * (1 - validator.commission.toDouble()) } private fun calculateYearlyInflation(): Double { return MINIMUM_INFLATION + if (stakedPortion in 0.0..STAKED_PORTION_IDEAL) { stakedPortion * (INTEREST_IDEAL - MINIMUM_INFLATION / STAKED_PORTION_IDEAL) } else { (INTEREST_IDEAL * STAKED_PORTION_IDEAL - MINIMUM_INFLATION) * 2.0.pow((STAKED_PORTION_IDEAL - stakedPortion) / DECAY_RATE) } } private val maxAPY = apyByValidator.values.maxOrNull() ?: 0.0 suspend fun calculateMaxAPY() = calculateReturns(amount = BigDecimal.ONE, DAYS_IN_YEAR, isCompound = true).gainPercentage fun calculateAvgAPY() = expectedAPY.toBigDecimal().fractionToPercentage() fun getApyFor(targetIdHex: String): BigDecimal { val apy = apyByValidator[targetIdHex] ?: expectedAPY return apy.toBigDecimal() } suspend fun calculateReturns( amount: BigDecimal, days: Int, isCompound: Boolean ) = withContext(Dispatchers.Default) { val dailyPercentage = maxAPY / DAYS_IN_YEAR calculateReward(amount.toDouble(), days, dailyPercentage, isCompound) } suspend fun calculateReturns( amount: Double, days: Int, isCompound: Boolean, targetIdHex: String ) = withContext(Dispatchers.Default) { val validatorAPY = apyByValidator[targetIdHex] ?: error("Validator with $targetIdHex was not found") val dailyPercentage = validatorAPY / DAYS_IN_YEAR calculateReward(amount, days, dailyPercentage, isCompound) } private fun calculateReward( amount: Double, days: Int, dailyPercentage: Double, isCompound: Boolean ): PeriodReturns { val gainAmount = if (isCompound) { calculateCompoundReward(amount, days, dailyPercentage) } else { calculateSimpleReward(amount, days, dailyPercentage) }.toBigDecimal() val gainPercentage = if (amount == 0.0) { BigDecimal.ZERO } else { (gainAmount / amount.toBigDecimal()).fractionToPercentage() } return PeriodReturns( gainAmount = gainAmount, gainPercentage = gainPercentage ) } private fun calculateSimpleReward(amount: Double, days: Int, dailyPercentage: Double): Double { return amount * dailyPercentage * days } private fun calculateCompoundReward(amount: Double, days: Int, dailyPercentage: Double): Double { return amount * ((1 + dailyPercentage).pow(days)) - amount } }
2
null
15
55
756c1fea772274ad421de1b215a12bf4e2798d12
4,625
fearless-Android
Apache License 2.0
komapper-jdbc/src/main/kotlin/org/komapper/jdbc/dsl/runner/SelectJdbcRunner.kt
komapper
349,909,214
false
null
package org.komapper.jdbc.dsl.runner import kotlinx.coroutines.flow.Flow import org.komapper.core.DatabaseConfig import org.komapper.core.Statement import org.komapper.core.dsl.context.SelectContext import org.komapper.core.dsl.runner.SelectRunner import org.komapper.jdbc.JdbcDatabaseConfig import org.komapper.jdbc.JdbcDialect import org.komapper.jdbc.JdbcExecutor import java.sql.ResultSet internal class SelectJdbcRunner<T, R>( private val context: SelectContext<*, *, *>, private val transform: (JdbcDialect, ResultSet) -> T, private val collect: suspend (Flow<T>) -> R ) : JdbcRunner<R> { private val runner: SelectRunner = SelectRunner(context) override fun run(config: JdbcDatabaseConfig): R { val statement = runner.buildStatement(config) val executor = JdbcExecutor(config, context.options) return executor.executeQuery(statement, transform, collect) } override fun dryRun(config: DatabaseConfig): Statement { return runner.dryRun(config) } }
1
Kotlin
0
20
2a8827d7c410a5366d875578a635b02dc176e989
1,026
komapper
Apache License 2.0
app/src/main/java/kr/sjh/myschedule/ui/theme/Theme.kt
junghoonshin3
674,523,154
false
null
package com.example.pogoda.presentation.ui.theme import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable @Composable fun WeatherAppTheme(content: @Composable () -> Unit) { MaterialTheme( typography = Typography, shapes = Shapes, content = content ) }
1
null
0
1
f7504195a56c5eb2a30bbc2a6c5ad11b1161ad5e
318
MySchedule
MIT License
library/core/engine/src/main/kotlin/de/lise/fluxflow/engine/workflow/WorkflowStarterServiceImpl.kt
lisegmbh
740,936,659
false
{"Kotlin": 732949}
package de.lise.fluxflow.engine.workflow import de.lise.fluxflow.api.ReferredWorkflowObject import de.lise.fluxflow.api.continuation.Continuation import de.lise.fluxflow.api.event.EventService import de.lise.fluxflow.api.workflow.Workflow import de.lise.fluxflow.api.workflow.WorkflowIdentifier import de.lise.fluxflow.api.workflow.WorkflowStarterService import de.lise.fluxflow.engine.continuation.ContinuationService import de.lise.fluxflow.engine.event.workflow.WorkflowCreatedEvent import de.lise.fluxflow.persistence.workflow.WorkflowPersistence class WorkflowStarterServiceImpl( private val persistence: WorkflowPersistence, private val activationService: WorkflowActivationService, private val continuationService: ContinuationService, private val eventService: EventService ) : WorkflowStarterService { fun <TWorkflowModel> create( workflowModel: TWorkflowModel, forcedId: WorkflowIdentifier? ): Workflow<TWorkflowModel> { val data = persistence.create(workflowModel, forcedId) val workflow = activationService.activate<TWorkflowModel>(data) eventService.publish(WorkflowCreatedEvent(workflow)) return workflow } override fun <TWorkflowModel, TContinuation> start( workflowModel: TWorkflowModel, continuation: Continuation<TContinuation>, originatingObject: ReferredWorkflowObject<*>?, forcedId: WorkflowIdentifier? ): Workflow<TWorkflowModel> { val createdWorkflow = create(workflowModel, forcedId) continuationService.execute(createdWorkflow, originatingObject, continuation) return createdWorkflow } }
21
Kotlin
0
7
1ad9ce84c8aa3d87d6b7114125962db5b30801c9
1,660
fluxflow
Apache License 2.0
library/src/main/java/com/kroegerama/imgpicker/BottomSheetImagePicker.kt
kroegerama
179,953,462
false
null
package com.kroegerama.imgpicker import android.annotation.SuppressLint import android.app.Activity.RESULT_OK import android.app.Dialog import android.content.Intent import android.content.pm.PackageManager import android.database.Cursor import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.DimenRes import androidx.annotation.PluralsRes import androidx.annotation.StringRes import androidx.core.content.FileProvider import androidx.core.view.isVisible import androidx.fragment.app.FragmentManager import androidx.loader.app.LoaderManager import androidx.loader.content.CursorLoader import androidx.loader.content.Loader import androidx.recyclerview.widget.SimpleItemAnimator import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.kroegerama.kaiteki.recyclerview.layout.AutofitLayoutManager import kotlinx.android.synthetic.main.bottomsheet_image_picker.* import java.io.File import java.text.SimpleDateFormat import java.util.* class BottomSheetImagePicker internal constructor() : BottomSheetDialogFragment(), LoaderManager.LoaderCallbacks<Cursor> { private var currentPhotoUri: Uri? = null private var isMultiSelect = false private var multiSelectMin = 1 private var multiSelectMax = Int.MAX_VALUE private var providerAuthority = "" private var requestTag = "" private var showCameraTile = false private var showCameraButton = true private var showGalleryTile = false private var showGalleryButton = true @StringRes private var resTitleSingle = R.string.imagePickerSingle @PluralsRes private var resTitleMulti = R.plurals.imagePickerMulti @PluralsRes private var resTitleMultiMore = R.plurals.imagePickerMultiMore @StringRes private var resTitleMultiLimit = R.string.imagePickerMultiLimit @DimenRes private var peekHeight = R.dimen.imagePickerPeekHeight @DimenRes private var columnSizeRes = R.dimen.imagePickerColumnSize @StringRes private var loadingRes = R.string.imagePickerLoading @StringRes private var emptyRes = R.string.imagePickerEmpty private var onImagesSelectedListener: OnImagesSelectedListener? = null private lateinit var bottomSheetBehavior: BottomSheetBehavior<*> private val adapter by lazy { ImageTileAdapter(isMultiSelect, showCameraTile, showGalleryTile, ::tileClick, ::selectionCountChanged) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) loadArguments() if (requireContext().hasReadStoragePermission) { LoaderManager.getInstance(this).initLoader(LOADER_ID, null, this) } else { requestReadStoragePermission(REQUEST_PERMISSION_READ_STORAGE) } if (savedInstanceState != null) { currentPhotoUri = savedInstanceState.getParcelable(STATE_CURRENT_URI) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.bottomsheet_image_picker, container, false).also { (parentFragment as? OnImagesSelectedListener)?.let { onImagesSelectedListener = it } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) tvHeader.setOnClickListener { if (bottomSheetBehavior.state != BottomSheetBehavior.STATE_EXPANDED) { bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED } else { recycler.smoothScrollToPosition(0) } } if (showGalleryButton) { btnGallery.isVisible = true btnGallery.setOnClickListener { launchGallery() } } if (showCameraButton) { btnCamera.isVisible = true btnCamera.setOnClickListener { launchCamera() } } tvHeader.setText(resTitleSingle) tvEmpty.setText(loadingRes) if (isMultiSelect) { btnCamera.isVisible = false btnGallery.isVisible = false btnDone.isVisible = true btnDone.setOnClickListener { onImagesSelectedListener?.onImagesSelected(adapter.getSelectedImages(), requestTag) dismissAllowingStateLoss() } btnClearSelection.isVisible = true btnClearSelection.setOnClickListener { adapter.clear() } } recycler.layoutManager = AutofitLayoutManager(requireContext(), columnSizeRes) (recycler.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false recycler.adapter = adapter val oldSelection = savedInstanceState?.getIntArray(STATE_SELECTION) if (oldSelection != null) { adapter.selection = oldSelection.toHashSet() } selectionCountChanged(adapter.selection.size) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = super.onCreateDialog(savedInstanceState).apply { setOnShowListener { val bottomSheet = findViewById<View>(R.id.design_bottom_sheet) bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet) bottomSheetBehavior.peekHeight = resources.getDimensionPixelSize(peekHeight) bottomSheetBehavior.setBottomSheetCallback(bottomSheetCallback) } } fun setOnImageSelectedListener(listener: OnImagesSelectedListener) { this.onImagesSelectedListener = listener } private val bottomSheetCallback by lazy { object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(bottomSheet: View, slideOffset: Float) { view?.alpha = if (slideOffset < 0f) 1f + slideOffset else 1f } override fun onStateChanged(bottomSheet: View, newState: Int) { if (newState == BottomSheetBehavior.STATE_HIDDEN) { dismissAllowingStateLoss() } } } } private fun tileClick(tile: ClickedTile) { when (tile) { is ClickedTile.CameraTile -> { launchCamera() } is ClickedTile.GalleryTile -> { launchGallery() } is ClickedTile.ImageTile -> { onImagesSelectedListener?.onImagesSelected(listOf(tile.uri), requestTag) dismissAllowingStateLoss() } } } private fun selectionCountChanged(count: Int) { if (!isMultiSelect) return when { count < multiSelectMin -> { val delta = multiSelectMin - count tvHeader.text = resources.getQuantityString(resTitleMultiMore, delta, delta) } count > multiSelectMax -> tvHeader.text = getString(resTitleMultiLimit, multiSelectMax) else -> tvHeader.text = resources.getQuantityString(resTitleMulti, count, count) } btnDone.isEnabled = count in multiSelectMin..multiSelectMax btnDone.animate().alpha(if (btnDone.isEnabled) 1f else .2f) btnClearSelection.isEnabled = count > 0 btnClearSelection.animate().alpha(if (btnClearSelection.isEnabled) 1f else .2f) } private fun launchCamera() { if (!requireContext().hasWriteStoragePermission) { requestWriteStoragePermission(REQUEST_PERMISSION_WRITE_STORAGE) return } val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (intent.resolveActivity(requireContext().packageManager) == null) return val photoFile = try { createImageFile() } catch (e: Exception) { if (BuildConfig.DEBUG) Log.w(TAG, "could not create temp file", e) return } val photoUri = FileProvider.getUriForFile(requireContext(), providerAuthority, photoFile) intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri) requireContext().packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .forEach { info -> val packageName = info.activityInfo.packageName requireContext().grantUriPermission( packageName, photoUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION ) } startActivityForResult(intent, REQUEST_PHOTO) } private fun launchGallery() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, REQUEST_GALLERY) } @SuppressLint("SimpleDateFormat") private fun createImageFile(): File { val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().time) val imageFileName = "IMG_" + timeStamp + "_" val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) storageDir.mkdirs() val image = File.createTempFile(imageFileName, ".jpg", storageDir) val success = image.delete() //no need to create empty file; camera app will create it on success if (!success && BuildConfig.DEBUG) { Log.d(TAG, "Failed to delete temp file: $image") } // Save a file: path for use with ACTION_VIEW intents currentPhotoUri = Uri.fromFile(image) return image } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { REQUEST_PERMISSION_READ_STORAGE -> if (grantResults.isPermissionGranted) LoaderManager.getInstance(this).initLoader(LOADER_ID, null, this) else dismissAllowingStateLoss() REQUEST_PERMISSION_WRITE_STORAGE -> if (grantResults.isPermissionGranted) launchCamera() else Toast.makeText( requireContext(), R.string.toastImagePickerNoWritePermission, Toast.LENGTH_LONG ).show() } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode != RESULT_OK) { super.onActivityResult(requestCode, resultCode, data) return } when (requestCode) { REQUEST_PHOTO -> { notifyGallery() currentPhotoUri?.let { uri -> onImagesSelectedListener?.onImagesSelected(listOf(uri), requestTag) } dismissAllowingStateLoss() return } REQUEST_GALLERY -> { data?.data?.let { uri -> onImagesSelectedListener?.onImagesSelected(listOf(uri), requestTag) } dismissAllowingStateLoss() return } } super.onActivityResult(requestCode, resultCode, data) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(STATE_CURRENT_URI, currentPhotoUri) outState.putIntArray(STATE_SELECTION, adapter.selection.toIntArray()) } private fun notifyGallery() { context?.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).apply { data = currentPhotoUri }) } private fun loadArguments() { val args = arguments ?: return isMultiSelect = args.getBoolean(KEY_MULTI_SELECT, isMultiSelect) multiSelectMin = args.getInt(KEY_MULTI_SELECT_MIN, multiSelectMin) multiSelectMax = args.getInt(KEY_MULTI_SELECT_MAX, multiSelectMax) providerAuthority = args.getString(KEY_PROVIDER, this::class.java.canonicalName) showCameraTile = args.getBoolean(KEY_SHOW_CAMERA_TILE, showCameraTile) showCameraButton = args.getBoolean(KEY_SHOW_CAMERA_BTN, showCameraButton) showGalleryTile = args.getBoolean(KEY_SHOW_GALLERY_TILE, showGalleryTile) showGalleryButton = args.getBoolean(KEY_SHOW_GALLERY_BTN, showGalleryButton) columnSizeRes = args.getInt(KEY_COLUMN_SIZE_RES, columnSizeRes) requestTag = args.getString(KEY_REQUEST_TAG, requestTag) resTitleSingle = args.getInt(KEY_TITLE_RES_SINGLE, resTitleSingle) resTitleMulti = args.getInt(KEY_TITLE_RES_MULTI, resTitleMulti) resTitleMultiMore = args.getInt(KEY_TITLE_RES_MULTI_MORE, resTitleMultiMore) resTitleMultiLimit = args.getInt(KEY_TITLE_RES_MULTI_LIMIT, resTitleMultiLimit) peekHeight = args.getInt(KEY_PEEK_HEIGHT, peekHeight) emptyRes = args.getInt(KEY_TEXT_EMPTY, emptyRes) loadingRes = args.getInt(KEY_TEXT_LOADING, loadingRes) } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { if (id != LOADER_ID) throw IllegalStateException("illegal loader id: $id") val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val projection = arrayOf(MediaStore.Images.Media.DATA) val sortOrder = MediaStore.Images.Media.DATE_ADDED + " DESC" return CursorLoader(requireContext(), uri, projection, null, null, sortOrder) } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) { progress.isVisible = false tvEmpty.setText(emptyRes) data ?: return val columnIndex = data.getColumnIndex(MediaStore.Images.Media.DATA) val items = ArrayList<Uri>() while (items.size < MAX_CURSOR_IMAGES && data.moveToNext()) { val str = data.getString(columnIndex) items.add(Uri.fromFile(File(str))) } data.moveToFirst() adapter.imageList = items tvEmpty.isVisible = items.size == 0 } override fun onLoaderReset(loader: Loader<Cursor>) { adapter.imageList = emptyList() } interface OnImagesSelectedListener { fun onImagesSelected(uris: List<Uri>, tag: String?) } companion object { private const val TAG = "BottomSheetImagePicker" private const val LOADER_ID = 0x1337 private const val REQUEST_PERMISSION_READ_STORAGE = 0x2000 private const val REQUEST_PERMISSION_WRITE_STORAGE = 0x2001 private const val REQUEST_PHOTO = 0x3000 private const val REQUEST_GALLERY = 0x3001 private const val KEY_PROVIDER = "provider" private const val KEY_REQUEST_TAG = "requestTag" private const val KEY_MULTI_SELECT = "multiSelect" private const val KEY_MULTI_SELECT_MIN = "multiSelectMin" private const val KEY_MULTI_SELECT_MAX = "multiSelectMax" private const val KEY_SHOW_CAMERA_TILE = "showCameraTile" private const val KEY_SHOW_CAMERA_BTN = "showCameraButton" private const val KEY_SHOW_GALLERY_TILE = "showGalleryTile" private const val KEY_SHOW_GALLERY_BTN = "showGalleryButton" private const val KEY_COLUMN_SIZE_RES = "columnCount" private const val KEY_TITLE_RES_SINGLE = "titleResSingle" private const val KEY_TITLE_RES_MULTI = "titleResMulti" private const val KEY_TITLE_RES_MULTI_MORE = "titleResMultiMore" private const val KEY_TITLE_RES_MULTI_LIMIT = "titleResMultiLimit" private const val KEY_TEXT_EMPTY = "emptyText" private const val KEY_TEXT_LOADING = "loadingText" private const val KEY_PEEK_HEIGHT = "peekHeight" private const val STATE_CURRENT_URI = "stateUri" private const val STATE_SELECTION = "stateSelection" private const val MAX_CURSOR_IMAGES = 512 } class Builder(provider: String) { private val args = Bundle().apply { putString(KEY_PROVIDER, provider) } private var listener: OnImagesSelectedListener? = null fun requestTag(requestTag: String) = args.run { putString(KEY_REQUEST_TAG, requestTag) this@Builder } fun multiSelect(min: Int = 1, max: Int = Int.MAX_VALUE) = args.run { putBoolean(KEY_MULTI_SELECT, true) putInt(KEY_MULTI_SELECT_MIN, min) putInt(KEY_MULTI_SELECT_MAX, max) this@Builder } fun columnSize(@DimenRes columnSizeRes: Int) = args.run { putInt(KEY_COLUMN_SIZE_RES, columnSizeRes) this@Builder } fun cameraButton(type: ButtonType) = args.run { putBoolean(KEY_SHOW_CAMERA_BTN, type == ButtonType.Button) putBoolean(KEY_SHOW_CAMERA_TILE, type == ButtonType.Tile) this@Builder } fun galleryButton(type: ButtonType) = args.run { putBoolean(KEY_SHOW_GALLERY_BTN, type == ButtonType.Button) putBoolean(KEY_SHOW_GALLERY_TILE, type == ButtonType.Tile) this@Builder } fun singleSelectTitle(@StringRes titleRes: Int) = args.run { putInt(KEY_TITLE_RES_SINGLE, titleRes) this@Builder } fun peekHeight(@DimenRes peekHeightRes: Int) = args.run { putInt(KEY_PEEK_HEIGHT, peekHeightRes) this@Builder } fun emptyText(@StringRes emptyRes: Int) = args.run { putInt(KEY_TEXT_EMPTY, emptyRes) this@Builder } fun loadingText(@StringRes loadingRes: Int) = args.run { putInt(KEY_TEXT_LOADING, loadingRes) this@Builder } fun multiSelectTitles( @PluralsRes titleCount: Int, @PluralsRes titleNeedMore: Int, @StringRes titleLimit: Int ) = args.run { putInt(KEY_TITLE_RES_MULTI, titleCount) putInt(KEY_TITLE_RES_MULTI_MORE, titleNeedMore) putInt(KEY_TITLE_RES_MULTI_LIMIT, titleLimit) this@Builder } fun onImagesSelected(listener: OnImagesSelectedListener) : Builder { this.listener = listener return this } fun build() = BottomSheetImagePicker().apply { [email protected]?.let { setOnImageSelectedListener(it) } arguments = args } fun show(fm: FragmentManager, tag: String? = null) = build().show(fm, tag) } } enum class ButtonType { None, Button, Tile }
12
null
45
328
0264ac750f4a4c3be48df97e849087bb2846e3e6
18,803
bottomsheet-imagepicker
Apache License 2.0
app/src/main/java/br/com/william/fernandes/srp/LavaLoucas.kt
williamjosefernandes
608,693,253
false
null
package br.com.william.fernandes.srp import android.util.Log class LavaLoucas { var loucaLavada = false fun lavarLouca() { loucaLavada = true } }
0
Kotlin
0
0
59e490b1b75f00869bab5d4b8dc28ec975e4abb5
170
Single-Responsibility-Principle
Apache License 2.0
ripple-core/src/test/java/com/ripple/core/coretypes/STObjectFormatterTest.kt
sublimator
16,341,429
true
{"Java": 717983, "Kotlin": 80834, "Python": 874, "Shell": 248}
package com.ripple.core.coretypes import com.ripple.core.fields.Field import com.ripple.core.serialized.enums.LedgerEntryType import com.ripple.core.serialized.enums.TransactionType import com.ripple.core.types.known.sle.LedgerEntry import com.ripple.core.types.known.sle.entries.DepositPreauthLe import com.ripple.core.types.known.sle.entries.DirectoryNode import com.ripple.core.types.known.tx.Transaction import com.ripple.core.types.known.tx.result.AffectedNode import com.ripple.core.types.known.tx.result.TransactionMeta import org.intellij.lang.annotations.Language import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class STObjectFormatterTest { @Test fun testLedgerEntryTypes() { LedgerEntryType.values().forEach { let -> val so = STObject() so.put(Field.LedgerEntryType, let) val leSo = STObjectFormatter.format(so) assertTrue(leSo is LedgerEntry) val klassName = leSo.javaClass.simpleName when (leSo) { is DirectoryNode -> assertTrue(klassName.endsWith("Directory")) is DepositPreauthLe -> assertEquals(let.toString() + "Le", klassName) else -> assertEquals(let.toString(), klassName) } val le = leSo as LedgerEntry assertEquals(let, le.ledgerEntryType()) } } @Test fun testTransactionTypes() { TransactionType.values().forEach { tt -> val so = STObject() so.put(Field.TransactionType, tt) println("$tt") val txSo = STObjectFormatter.format(so) assertTrue(txSo is Transaction) assertEquals(tt.toString(), txSo.javaClass.simpleName) val tx = txSo as Transaction assertEquals(tt, tx.transactionType()) } } @Test fun testTransactionMeta() { @Language("JSON") val metaJson = """ { "AffectedNodes": [ { "ModifiedNode": { "FinalFields": { "Account": "<KEY>", "Balance": "1632282339", "Flags": 0, "OwnerCount": 19, "Sequence": 1771490 }, "LedgerEntryType": "AccountRoot", "LedgerIndex": "56091AD066271ED03B106812AD376D48F126803665E3ECBFDBBB7A3FFEB474B2", "PreviousFields": { "Balance": "1632282349", "OwnerCount": 18, "Sequence": 1771489 }, "PreviousTxnID": "7A6E920AA4EFBA202699437539D176D842904B8402A25D344A25C4D24234CFC4", "PreviousTxnLgrSeq": 7501325 } }, { "CreatedNode": { "LedgerEntryType": "DirectoryNode", "LedgerIndex": "6F86B77ADAC326EA25C597BAD08C447FA568D28A2504883F530520669E693000", "NewFields": { "ExchangeRate": "530520669E693000", "RootIndex": "6F86B77ADAC326EA25C597BAD08C447FA568D28A2504883F530520669E693000", "TakerGetsCurrency": "0000000000000000000000004C54430000000000", "TakerGetsIssuer": "92D705968936C419CE614BF264B5EEB1CEA47FF4", "TakerPaysCurrency": "0000000000000000000000004254430000000000", "TakerPaysIssuer": "92D705968936C419CE614BF264B5EEB1CEA47FF4" } } }, { "CreatedNode": { "LedgerEntryType": "Offer", "LedgerIndex": "A32C940A8962A0FB6EA8CDF0DD9F4CE629DEF8EA360E099F8C634AAE351E6607", "NewFields": { "Account": "<KEY>", "BookDirectory": "6F86B77ADAC326EA25C597BAD08C447FA568D28A2504883F530520669E693000", "OwnerNode": "000000000000405C", "Sequence": 1771489, "TakerGets": { "currency": "LTC", "issuer": "<KEY>", "value": "15.92" }, "TakerPays": { "currency": "BTC", "issuer": "<KEY>", "value": "0.2297256" } } } }, { "ModifiedNode": { "FinalFields": { "Flags": 0, "IndexPrevious": "0000000000000000", "Owner": "rMWUykAmNQDaM9poSes8VLDZDDKEbmo7MX", "RootIndex": "2114A41BB356843CE99B2858892C8F1FEF634B09F09AF2EB3E8C9AA7FD0E3A1A" }, "LedgerEntryType": "DirectoryNode", "LedgerIndex": "D6540D658870F60843ECF33A4F903665EE5B212479EB20E1E43E3744A95194AC" } } ], "TransactionIndex": 2, "TransactionResult": "tesSUCCESS" } """ val meta = STObject.fromJSON(metaJson) assertTrue(meta is TransactionMeta) assertTrue(meta[STArray.AffectedNodes][0] is AffectedNode) } }
17
Java
7
7
909f983d9cfb379591d3b1abf6622840e4ffd2d1
5,044
ripple-lib-java
ISC License
app/src/main/java/com/curso/free/data/model/Preference.kt
OmAr-Kader
714,504,783
false
{"Kotlin": 534140}
package com.curso.free.data.model class Preference( @io.realm.kotlin.types.annotations.PrimaryKey var _id: org.mongodb.kbson.ObjectId = org.mongodb.kbson.ObjectId.invoke(), @io.realm.kotlin.types.annotations.Index var ketString: String, var value: String, ) : io.realm.kotlin.types.RealmObject { constructor() : this(org.mongodb.kbson.ObjectId.invoke(), "", "") constructor(ketString: String, value: String) : this(org.mongodb.kbson.ObjectId.invoke(), ketString, value) }
0
Kotlin
0
0
24761de20fb70c2225674c5051d8846df490bc50
502
Curso
MIT License
camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/cameracontrollers/CameraXDeviceStateCallback.kt
RikkaW
389,105,112
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.antelope.cameracontrollers import android.hardware.camera2.CameraDevice import androidx.camera.integration.antelope.CameraParams import androidx.camera.integration.antelope.MainActivity import androidx.camera.integration.antelope.TestConfig import androidx.camera.integration.antelope.TestType import androidx.camera.integration.antelope.testEnded /** Callbacks that track the state of the camera device using the Camera X API. */ class CameraXDeviceStateCallback( internal var params: CameraParams, internal var activity: MainActivity, internal var testConfig: TestConfig ) : CameraDevice.StateCallback() { /** Camera device has opened successfully, record timing and initiate the preview stream. */ override fun onOpened(cameraDevice: CameraDevice) { MainActivity.logd( "In CameraXStateCallback onOpened: " + cameraDevice.id + " current test: " + testConfig.currentRunningTest.toString() ) params.timer.openEnd = System.currentTimeMillis() params.isOpen = true params.device = cameraDevice when (testConfig.currentRunningTest) { TestType.INIT -> { // Camera opened, we're done testConfig.testFinished = true closeCameraX(activity, params, testConfig) } else -> { params.timer.previewStart = System.currentTimeMillis() } } } /** * Camera device has been closed, recording close timing. * * If this is a switch test, swizzle camera ids and move to the next step of the test. */ override fun onClosed(camera: CameraDevice) { MainActivity.logd("In CameraXStateCallback onClosed.") if (testConfig.testFinished) { params.timer.cameraCloseEnd = System.currentTimeMillis() testConfig.testFinished = false testEnded(activity, params, testConfig) return } if ( (testConfig.currentRunningTest == TestType.SWITCH_CAMERA) || (testConfig.currentRunningTest == TestType.MULTI_SWITCH) ) { // First camera closed, now start the second if (testConfig.switchTestCurrentCamera == testConfig.switchTestCameras.get(0)) { testConfig.switchTestCurrentCamera = testConfig.switchTestCameras.get(1) cameraXOpenCamera(activity, params, testConfig) } // Second camera closed, now start the first else if (testConfig.switchTestCurrentCamera == testConfig.switchTestCameras.get(1)) { testConfig.switchTestCurrentCamera = testConfig.switchTestCameras.get(0) testConfig.testFinished = true cameraXOpenCamera(activity, params, testConfig) } } } /** Camera has been disconnected. Whatever was happening, it won't work now. */ override fun onDisconnected(cameraDevice: CameraDevice) { MainActivity.logd("In CameraXStateCallback onDisconnected: " + params.id) testConfig.testFinished = false // Whatever we are doing will fail now, try to exit closeCameraX(activity, params, testConfig) } /** Camera device has thrown an error. Try to recover or fail gracefully. */ override fun onError(cameraDevice: CameraDevice, error: Int) { MainActivity.logd( "In CameraXStateCallback onError: " + cameraDevice.id + " and error: " + error ) when (error) { CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE -> { // Let's try to close an open camera and re-open this one MainActivity.logd("In CameraXStateCallback too many cameras open, closing one...") closeACamera(activity, testConfig) cameraXOpenCamera(activity, params, testConfig) } CameraDevice.StateCallback.ERROR_CAMERA_DEVICE -> { MainActivity.logd("Fatal camerax error, close and try to re-initialize...") closeCameraX(activity, params, testConfig) cameraXOpenCamera(activity, params, testConfig) } CameraDevice.StateCallback.ERROR_CAMERA_IN_USE -> { MainActivity.logd("This camera is already open... doing nothing") } else -> { testConfig.testFinished = false // Whatever we are doing will fail now, try to exit closeCameraX(activity, params, testConfig) } } } }
8
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
5,251
androidx
Apache License 2.0
app/src/main/java/com/example/launchcontrol/generals/utils/GetStringResource.kt
Icaro-G-Silva
344,936,988
false
null
package com.example.launchcontrol.generals.utils import android.content.Context open class GetStringResource(private val context: Context) { fun getStringRes(resource: Int): String { return context.getString(resource) } }
0
Kotlin
0
0
1710da30a6d6bf2ec7e05827fdb4ca49fae48434
239
SpaceDroid
MIT License
src/test/kotlin/com/gmail/blueboxware/libgdxplugin/skin/TestReferences.kt
BlueBoxWare
64,067,118
false
null
package com.gmail.blueboxware.libgdxplugin.skin import com.gmail.blueboxware.libgdxplugin.LibGDXCodeInsightFixtureTestCase import com.gmail.blueboxware.libgdxplugin.filetypes.atlas.psi.AtlasRegion import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinClassName import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinPropertyName import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinResource import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinStringLiteral import com.gmail.blueboxware.libgdxplugin.filetypes.skin.references.SkinJavaClassReference import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.getRealClassNamesAsString import com.gmail.blueboxware.libgdxplugin.testname import com.gmail.blueboxware.libgdxplugin.utils.* import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiFile /* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class TestReferences: LibGDXCodeInsightFixtureTestCase() { fun testResourceReference1() { doTestResourceReference("white", COLOR_CLASS_NAME) } fun testResourceReference2() { doTestResourceReference("white", BITMAPFONT_CLASS_NAME) } fun testResourceReference3() { doTestResourceReference("blue", COLOR_CLASS_NAME) } fun testResourceReference4() { doTestResourceReference("blue", "com.example.MyTestClass") } fun testResourceReference5() { doTestResourceReference("blue", COLOR_CLASS_NAME) } fun testResourceReference6() { doTestResourceReference("ddd", "com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle") } fun testResourceReference7() { doTestResourceReference(null, "com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable") } fun testResourceReference8() { doTestResourceReference("d1", "com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle") } fun testResourceReferenceWithTaggedClasses1() { doTestResourceReference("bar", "com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable") } fun testResourceReferenceWithTaggedClasses2() { doTestResourceReference("foo", "com.example.MyTestClass") } fun testResourceReferenceWithTaggedClasses3() { doTestResourceReference("bar", "com.example.MyTestClass") } fun testResourceReferenceWithTaggedClasses4() { doTestResourceReference("bar", "com.example.MyTestClass") } fun testResourceReferenceWithTaggedClasses5() { doTestResourceReference("foo", "com.example.MyTestClass") } fun testResourceReferenceWithTaggedClasses6() { doTestResourceReference("bar", "com.example.KTestClass") } fun testResourceReferenceWithTaggedClasses7() { doTestResourceReference("foo", "com.example.KTestClass") } fun testParentResourceReferenceFromSuperClass1() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle") } fun testParentResourceReferenceFromSuperClassWithKotlin1() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle") } fun testParentResourceReferenceFromSuperClassWithKotlin2() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle") } fun testParentResourceReferenceFromSuperClassWithKotlin3() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle") } fun testParentResourceReferenceFromSuperClassWithKotlin4() { doTestResourceReference(null, null) } fun testParentResourceReferenceFromSuperClassWithKotlin5() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle") } fun testResourceAliasReference1() { doTestResourceReference("yellow", COLOR_CLASS_NAME) } fun testResourceAliasReference2() { doTestResourceReference("yellow", "com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle") } fun testResourceAliasReference3() { doTestResourceReference("dark-gray", COLOR_CLASS_NAME) } fun testResourceAliasReferenceFTF1() { addFreeType() doTestResourceReference("foo", FREETYPE_GENERATOR_CLASS_NAME) } fun testResourceAliasReferenceFTF2() { addFreeType() doTestResourceReference("ttf", FREETYPE_GENERATOR_CLASS_NAME) } fun testResourceAliasReferenceWithTaggedClasses1() { doTestResourceReference("foo", "com.example.MyTestClass") } fun testResourceAliasReferenceWithTaggedClasses2() { doTestResourceReference("foo", "com.example.KTestClass") } fun testResourceAliasReferenceWithTaggedClasses3() { doTestResourceReference("foo", "com.example.KTestClass") } fun testResourceAliasReferenceWithTaggedClasses4() { doTestResourceReference("foo", "com.example.KTestClass") } fun testResourceAliasReferenceWithTaggedClasses5() { doTestResourceReference("red", COLOR_CLASS_NAME) } fun testResourceAliasReferenceWithTaggedClasses6() { doTestResourceReference("red", COLOR_CLASS_NAME) } fun testResourceAliasReferenceWithTaggedClasses7() { doTestResourceReference("foo", "com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable") } fun testResourceAliasReferenceWithTaggedClasses8() { doTestResourceReference("foo", "com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable") } fun testResourceAliasReferenceWithTaggedClasses9() { addFreeType() doTestResourceReference("foo", "com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator") } fun testResourceReferenceTintedDrawable() { doTestResourceReference("round-down", "com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable") } fun testResourceReferenceTintedDrawableWithTaggedClasses() { doTestResourceReference("round-down", "com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable") } fun testParentReference() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle") } fun testParentReferencePre199() { removeDummyLibGDX199() doTestResourceReference(null, null) } fun testParentReferenceTagged() { doTestResourceReference("main", "com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle") } fun testJavaClassReference1() { doTestJavaClassReference("com.example.MyTestClass") } fun testJavaClassReference2() { doTestJavaClassReference("com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle") } fun testJavaClassReference3() { configureByFile("javaClassReference3.skin") val element: SkinClassName? = file.findElementAt(myFixture.caretOffset)?.parent?.parent as? SkinClassName assertNotNull(element) assertTrue(element!!.multiResolve().isEmpty()) } fun testTaggedClassReference1() { doTestJavaClassReference("com.example.MyTestClass") } fun testTaggedClassReference2() { doTestJavaClassReference("com.example.KTestClass") } fun testBitmapFontReference() { copyFileToProject("bitmap.fnt") doTestFileReference(SkinStringLiteral::class.java, "bitmap.fnt") } fun testBitmapFontReferenceWithTaggedClasses1() { copyFileToProject("bitmap.fnt") doTestFileReference(SkinStringLiteral::class.java, "bitmap.fnt") } fun testBitmapFontReferenceWithTaggedClasses2() { copyFileToProject("bitmap.fnt") doTestFileReference(SkinStringLiteral::class.java, "bitmap.fnt") } fun testFieldReference1() { doTestFieldReference() } fun testFieldReference2() { doTestFieldReference() } fun testFieldReference3() { doTestFieldReference("com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle::disabledFontColor") } fun testFieldReference4() { doTestFieldReference() } fun testFieldReference5() { doTestFieldReference("com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle::checked") } fun testFieldReference6() { doTestFieldReference("com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle::checkedOffsetX") } fun testFieldReferenceFTF() { addFreeType() doTestFieldReference("$FREETYPE_FONT_PARAMETER_CLASS_NAME::mono") } fun testFTFGeneratorEnumReference() { addFreeType() configureByFile("FTFGeneratorEnumReference.skin") val elementAtCaret = file.findElementAt(myFixture.caretOffset) val sourceElement = elementAtCaret?.firstParent<SkinStringLiteral>() assertNotNull(sourceElement) val field = sourceElement?.reference?.resolve() as PsiField assertEquals(FREETYPE_HINTING_CLASS_NAME, field.containingClass?.qualifiedName) assertEquals("AutoMedium", field.text) } fun testTaggedClassFieldReference1() { doTestFieldReference("com.example.MyTestClass::name") } fun testTaggedClassFieldReference2() { doTestFieldReference("com.example.MyTestClass::testClass") } fun testFieldReferenceKotlin1() { doTestFieldReference("com.example.KTestClass::labelStyles") } fun testFieldReferenceKotlin2() { doTestFieldReference("com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle::background") } fun testFieldReferenceKotlin3() { doTestFieldReference("com.badlogic.gdx.graphics.Color::a") } fun testDrawableReference1() { doTestDrawableReference() } fun testDrawableReference2() { doTestDrawableReference() } fun testDrawableReference3() { doTestDrawableReference() } fun testDrawableReferenceWithTaggedClasses1() { doTestDrawableReference() } fun testDrawableReferenceWithTaggedClasses2() { doTestDrawableReference() } private fun doTestFieldReference(expectedFieldName: String? = null) { configureByFile(testname() + ".skin") val elementAtCaret = file.findElementAt(myFixture.caretOffset) val sourceElement = elementAtCaret?.firstParent<SkinPropertyName>() assertNotNull(sourceElement) val field = sourceElement?.reference?.resolve() as? PsiField assertNotNull(field) val expectedName = expectedFieldName ?: sourceElement?.property?.containingObject?.resolveToTypeString() + "::" + field?.name assertEquals(expectedName, field!!.containingClass?.qualifiedName + "::" + field.name) } private fun doTestFileReference(sourceElementClass: Class<*>, expectedFileName: String) { configureByFile(testname() + ".skin") val elementAtCaret = file.findElementAt(myFixture.caretOffset) val sourceElement = elementAtCaret?.firstParent { sourceElementClass.isInstance(it) } assertNotNull(sourceElement) val file = sourceElement?.reference?.resolve() as? PsiFile assertNotNull(file) assertEquals(expectedFileName, file?.name) } private fun doTestResourceReference(resourceName: String?, resourceType: String?) { configureByFile(testname() + ".skin") val element = file.findElementAt(myFixture.caretOffset)?.parent assertNotNull(element) val resource = element?.reference?.resolve() as? SkinResource if (resourceName != null) { assertNotNull(resource) assertEquals(resourceName, resource?.name) assertTrue(resource?.classSpecification?.getRealClassNamesAsString()?.contains(resourceType) == true) } else { assertNull(resource) } } private fun doTestJavaClassReference(className: String) { configureByFile(testname() + ".skin") val element: SkinClassName? = file.findElementAt(myFixture.caretOffset)?.parent?.parent as? SkinClassName assertNotNull(element) val clazz = (element?.reference as? SkinJavaClassReference)?.multiResolve(false)?.firstOrNull()?.element as? PsiClass assertNotNull(clazz) assertEquals(className, clazz?.qualifiedName) } private fun doTestDrawableReference() { copyFileToProject(testname() + ".atlas") configureByFile(testname() + ".skin") val element = file.findElementAt(myFixture.caretOffset)?.firstParent<SkinStringLiteral>()!! val reference = element.reference ?: throw AssertionError() val target = reference.resolve() as AtlasRegion assertEquals(element.value, target.name) } override fun setUp() { super.setUp() addLibGDX() addAnnotations() addDummyLibGDX199() copyFileToProject("com/example/MyTestClass.java", "com/example/MyTestClass.java") val testName = testname() if (testName.contains("Kotlin", ignoreCase = true) || testName.contains("tagged", ignoreCase = true)) { addKotlin() copyFileToProject("com/example/KTestClass.kt", "com/example/KTestClass.kt") } } override fun getBasePath() = "/filetypes/skin/references/" }
2
null
9
145
bcb911e0c3f3e9319bc8ee2d5b6b554c6090fd6c
12,936
LibGDXPlugin
Apache License 2.0
mineinabyss-features/src/main/kotlin/com/mineinabyss/features/guilds/menus/GuildJoinRequestScreen.kt
MineInAbyss
115,279,675
false
null
package com.mineinabyss.features.guilds.menus import androidx.compose.runtime.Composable import com.mineinabyss.features.abyss import com.mineinabyss.features.guilds.database.GuildJoinType import com.mineinabyss.features.guilds.database.GuildMessageQueue import com.mineinabyss.features.guilds.extensions.* import com.mineinabyss.features.helpers.Text import com.mineinabyss.features.helpers.head import com.mineinabyss.features.helpers.ui.composables.Button import com.mineinabyss.guiy.components.Item import com.mineinabyss.guiy.modifiers.Modifier import com.mineinabyss.guiy.modifiers.at import com.mineinabyss.guiy.modifiers.size import com.mineinabyss.idofront.messaging.error import com.mineinabyss.idofront.messaging.info import com.mineinabyss.idofront.textcomponents.miniMsg import org.bukkit.OfflinePlayer import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.transactions.transaction @Composable fun GuildUIScope.GuildJoinRequestScreen(from: OfflinePlayer) { PlayerLabel(Modifier.at(4, 0), from) AcceptGuildRequestButton(Modifier.at(1, 1), from) DeclineGuildRequestButton(Modifier.at(5, 1), from) BackButton(Modifier.at(4, 4)) } @Composable fun PlayerLabel(modifier: Modifier, newMember: OfflinePlayer) = Button(modifier = modifier) { Item(newMember.head("<yellow><i>${newMember.name}".miniMsg(), isCenterOfInv = true, isLarge = true)) } @Composable fun GuildUIScope.AcceptGuildRequestButton(modifier: Modifier, newMember: OfflinePlayer) = Button( onClick = { if (player.getGuildJoinType() == GuildJoinType.INVITE) { player.error("Your guild is in 'INVITE-only' mode.") player.error("Change it to 'ANY' or 'REQUEST-only' mode to accept requests.") return@Button } player.addMemberToGuild(newMember) newMember.removeGuildQueueEntries(GuildJoinType.REQUEST) if (player.getGuildMemberCount() < guildLevel * 5) { newMember.removeGuildQueueEntries(GuildJoinType.REQUEST) } nav.back() }, modifier = modifier ) { Text("<green>Accept GuildJoin-REQUEST".miniMsg(), modifier = Modifier.size(3, 3)) } @Composable fun GuildUIScope.DeclineGuildRequestButton(modifier: Modifier, newMember: OfflinePlayer) = Button( modifier = modifier, onClick = { guildName?.removeGuildQueueEntries(newMember, GuildJoinType.REQUEST) player.info("<yellow><b>❌ <yellow>You denied the join-request from ${newMember.name}") val requestDeniedMessage = "<red>Your request to join <i>${guildName} has been denied!" if (newMember.isOnline) newMember.player?.error(requestDeniedMessage) else { transaction(abyss.db) { GuildMessageQueue.insert { it[content] = requestDeniedMessage it[playerUUID] = newMember.uniqueId } } } nav.back() if (player.getNumberOfGuildRequests() == 0) nav.back() } ) { Text("<red>Decline GuildJoin-REQUEST".miniMsg(), modifier = Modifier.size(3, 3)) } @Composable fun GuildUIScope.DeclineAllGuildRequestsButton(modifier: Modifier) = Button( modifier = modifier, onClick = { player.removeGuildQueueEntries(GuildJoinType.REQUEST, true) player.info("<yellow><b>❌ <yellow>You denied all join-requests for your guild!") nav.back() } ) { Text("<red>Decline All Requests".miniMsg()) }
16
null
27
99
35b12abf13867de5a00acfc4804b1797751b842e
3,480
MineInAbyss
MIT License
src/main/kotlin/com/github/plplmax/simulator/restaurant/RestaurantStateOf.kt
plplmax
538,049,460
false
{"Kotlin": 26178}
package com.github.plplmax.simulator.restaurant import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.toDuration data class RestaurantStateOf( override var customersInterval: MutableState<Duration> = mutableStateOf((5).toDuration(DurationUnit.SECONDS)), override var cookInterval: MutableState<Duration> = mutableStateOf((5).toDuration(DurationUnit.SECONDS)), override var started: MutableState<Boolean> = mutableStateOf(false) ) : RestaurantState { }
0
Kotlin
0
1
8950a388d99b1c7ddb67b459a15cbfbee79a2ec1
583
fast-food-simulator
MIT License
idea-plugin/src/main/kotlin/org/jetbrains/compose/desktop/idea/preview/PreviewRunConfigurationProducer.kt
pratyushkhare1
355,441,829
true
{"Kotlin": 243021, "Dockerfile": 4946, "Shell": 3654, "PowerShell": 1708}
/* * Copyright 2020-2021 JetBrains s.r.o. and respective authors and developers. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.compose.desktop.idea.preview import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.LazyRunConfigurationProducer import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.plugins.gradle.service.execution.GradleExternalTaskConfigurationType import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration /** * Producer of [ComposePreviewRunConfiguration] for `@Composable` functions annotated with [PREVIEW_ANNOTATION_FQN]. The configuration * created is initially named after the `@Composable` function, and its fully qualified name is properly set in the configuration. * * The [ConfigurationContext] where the [ComposePreviewRunConfiguration] is created from can be any descendant of the `@Composable` function * in the PSI tree, such as its annotations, function name or even the keyword "fun". */ class PreviewRunConfigurationProducer : LazyRunConfigurationProducer<GradleRunConfiguration>() { override fun getConfigurationFactory(): ConfigurationFactory = GradleExternalTaskConfigurationType.getInstance().factory override fun isConfigurationFromContext( configuration: GradleRunConfiguration, context: ConfigurationContext ): Boolean { val composeFunction = context.containingComposePreviewFunction() ?: return false return configuration.run { name == composeFunction.name!! && settings.externalProjectPath == context.modulePath() && settings.scriptParameters.contains( previewTargetGradleArg(composeFunction.composePreviewFunctionFqn()) ) } } override fun setupConfigurationFromContext( configuration: GradleRunConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement> ): Boolean { val composeFunction = context.containingComposePreviewFunction() ?: return false configuration.apply { name = composeFunction.name!! settings.taskNames.add("runComposeDesktopPreview") settings.externalProjectPath = ExternalSystemApiUtil.getExternalProjectPath(context.location?.module) settings.scriptParameters = listOf( previewTargetGradleArg(composeFunction.composePreviewFunctionFqn()) ).joinToString(" ") } return true } } private fun ConfigurationContext.modulePath(): String? = ExternalSystemApiUtil.getExternalProjectPath(location?.module) private fun previewTargetGradleArg(target: String): String = "-Pcompose.desktop.preview.target=$target" private fun KtNamedFunction.composePreviewFunctionFqn() = "${getClassName()}.${name}" private fun ConfigurationContext.containingComposePreviewFunction() = psiLocation?.let { location -> location.getNonStrictParentOfType<KtNamedFunction>()?.takeIf { it.isValidComposePreview() } }
0
null
0
0
05b9e962e506733636c8f9a74f8a5313d59c4797
3,413
compose-jb
Apache License 2.0
app/src/main/java/com/slobodanantonijevic/simpleopenweatherkt/di/AppModule.kt
slobodanantonijevic
184,257,150
false
null
/* * Copyright (C) 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.slobodanantonijevic.simpleopenweatherkt.di import android.app.Application import android.content.Context import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import androidx.room.Room import com.slobodanantonijevic.simpleopenweatherkt.api.OpenWeatherApi import com.slobodanantonijevic.simpleopenweatherkt.api.OpenWeatherApi.Companion.BASE_URL import com.slobodanantonijevic.simpleopenweatherkt.db.CurrentWeatherDao import com.slobodanantonijevic.simpleopenweatherkt.db.ForecastDao import com.slobodanantonijevic.simpleopenweatherkt.db.WeatherDb import com.slobodanantonijevic.simpleopenweatherkt.db.WeatherDb.Companion.DB_NAME import com.slobodanantonijevic.simpleopenweatherkt.util.SharedPrefManager import com.slobodanantonijevic.simpleopenweatherkt.util.SharedPrefManager.Companion.BASIC_CONFIG_FILE import com.slobodanantonijevic.simpleopenweatherkt.util.TimeFormatter import dagger.Module import dagger.Provides import io.reactivex.schedulers.Schedulers import org.threeten.bp.ZoneId import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton /** * Module to provide the Dagger all the necessary elements for our data flow * Such as Retrofit built client to fetch the fresh data, and Room DB and DAOs for data persistence */ @Module(includes = [ViewModelModule::class]) class AppModule { @Singleton @Provides fun provideWeatherApi() : OpenWeatherApi { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .build() .create(OpenWeatherApi::class.java); } @Singleton @Provides fun provideDb(app: Application): WeatherDb { return Room.databaseBuilder(app, WeatherDb::class.java, DB_NAME).build() } @Singleton @Provides fun provideCurrentWeatherDao(db: WeatherDb): CurrentWeatherDao { return db.currentWeatherDao() } @Singleton @Provides fun provideForecastDao(db: WeatherDb): ForecastDao { return db.forecastDao() } }
0
Kotlin
0
0
bf54e2de1d2a394415082996ee9421c4285430c9
2,874
SimpleOpenWeatherKT
Apache License 2.0
src/main/java/com/mvv/gui/words/word.kt
odisseylm
679,732,600
false
{"Kotlin": 917098, "CSS": 25257, "Java": 6651}
package com.mvv.gui.words import com.mvv.gui.javafx.CacheableObservableValue import com.mvv.gui.javafx.mapCached import javafx.beans.property.ObjectProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.beans.property.StringProperty import javafx.beans.value.ObservableValue import javafx.scene.paint.Color //private val log = mu.KotlinLogging.logger {} interface BaseWordExtractor { fun extractBaseWord(phrase: String): String } interface CardWordEntry { val baseWordExtractor: BaseWordExtractor? val fromProperty: StringProperty val fromWithPrepositionProperty: StringProperty val baseWordOfFromProperty: CacheableObservableValue<String> val baseWordAndFromProperty: CacheableObservableValue<BaseAndFrom> val fromWordCountProperty: ObservableValue<Int> val toProperty: StringProperty val transcriptionProperty: StringProperty val translationCountProperty: ObservableValue<Int> val examplesProperty: StringProperty val exampleCountProperty: ObservableValue<Int> val exampleNewCardCandidateCountProperty: ObservableValue<Int> val statusesProperty: ObjectProperty<Set<WordCardStatus>> val predefinedSetsProperty: ObjectProperty<Set<PredefinedSet>> val sourcePositionsProperty: ObjectProperty<List<Int>> val sourceSentencesProperty: StringProperty // for showing in tooltip. It is filled during word cards analysis. //@Transient val missedBaseWordsProperty: ObjectProperty<List<String>> fun copy(): CardWordEntry // TODO: why do I need it?? Try to remove this param. fun copy(baseWordExtractor: BaseWordExtractor?): CardWordEntry } fun CardWordEntry( from: String, to: String, // val features: Set<CardWordEntryFeatures> = emptySet(), baseWordExtractor: BaseWordExtractor? = null, ): CardWordEntry { return CardWordEntryImpl(baseWordExtractor).also { it.from = from it.to = to } } fun CardWordEntry.copyBasePropsTo(to: CardWordEntry) { to.from = this.from to.to = this.to to.fromWithPreposition = this.fromWithPreposition to.transcription = this.transcription to.examples = this.examples to.statuses = this.statuses to.predefinedSets = this.predefinedSets to.sourcePositions = this.sourcePositions to.sourceSentences = this.sourceSentences to.missedBaseWords = this.missedBaseWords } private class CardWordEntryImpl ( // val features: Set<CardWordEntryFeatures> = emptySet(), override val baseWordExtractor: BaseWordExtractor? = null, ) : CardWordEntry { override val fromProperty = SimpleStringProperty(this, "from", "") override val fromWithPrepositionProperty = SimpleStringProperty(this, "fromWithPreposition", "") override val baseWordOfFromProperty: CacheableObservableValue<String> = fromProperty.let { fromProp -> fromProp.mapCached { baseWordExtractor?.extractBaseWord(it) ?: it } } // Synthetic property for sorting because there is no way to pass Comparator<Card> for specific table column (we can use only Comparator<String>). override val baseWordAndFromProperty: CacheableObservableValue<BaseAndFrom> = baseWordOfFromProperty.mapCached { baseOfFrom -> BaseAndFrom(baseOfFrom, fromProperty.value) } override val fromWordCountProperty = fromProperty.mapCached { it.trim().split(" ", "\t", "\n").size } override val toProperty = SimpleStringProperty(this, "to", "") override val transcriptionProperty = SimpleStringProperty(this, "transcription", "") override val translationCountProperty: ObservableValue<Int> = toProperty.mapCached { it?.translationCount ?: 0 } override val examplesProperty = SimpleStringProperty(this, "examples", "") override val exampleCountProperty = examplesProperty.mapCached { it.examplesCount } override val exampleNewCardCandidateCountProperty = examplesProperty.mapCached { it.exampleNewCardCandidateCount } override val statusesProperty = SimpleObjectProperty<Set<WordCardStatus>>(this, "statuses", emptySet()) override val predefinedSetsProperty = SimpleObjectProperty<Set<PredefinedSet>>(this, "predefinedSets", emptySet()) override val sourcePositionsProperty = SimpleObjectProperty<List<Int>>(this, "sourcePositions", emptyList()) override val sourceSentencesProperty = SimpleStringProperty(this, "sourceSentences", "") // for showing in tooltip. It is filled during word cards analysis. @Transient override val missedBaseWordsProperty = SimpleObjectProperty<List<String>>(this, "missedBaseWords", emptyList()) override fun toString(): String = "CardWordEntry(from='$from', to='${to.take(20)}...', statuses=$statuses," + " translationCount=$translationCount, transcription='$transcription', examples='${examples.take(10)}...')" override fun copy(): CardWordEntry = copy(null) override fun copy(baseWordExtractor: BaseWordExtractor?): CardWordEntry = CardWordEntryImpl(baseWordExtractor ?: this.baseWordExtractor) .also { this.copyBasePropsTo(it) } } val cardWordEntryComparator: Comparator<CardWordEntry> = Comparator.comparing({ it.from }, String.CASE_INSENSITIVE_ORDER) class BaseAndFrom (val base: String, val from: String) : Comparable<BaseAndFrom> { override fun compareTo(other: BaseAndFrom): Int { val baseComparing = this.base.compareTo(other.base) if (baseComparing == 0) { return when (base) { this.from -> -1 // to show pure word before other ('wear' before 'in wear') other.from -> 1 // to show pure word before other ('wear' before 'in wear') else -> this.from.compareTo(other.from) } } return baseComparing } } enum class TranslationCountStatus(val color: Color) { Ok(Color.TRANSPARENT), NotBad(Color.valueOf("#fffac5")), Warn(Color.valueOf("#ffdcc0")), ToMany(Color.valueOf("#ffbbbb")), ; val cssClass: String get() = "TranslationCountStatus-${this.name}" companion object { val allCssClasses = TranslationCountStatus.values().map { it.cssClass } } } enum class WordCardStatus ( val isWarning: Boolean, val toolTipF: (CardWordEntry)->String, ) { // *************************** Low priority warnings *************************************************************** // /** * If current word has ending/suffix 'ed', 'ing', 'es', 's' does not have * but the whole set does not have base word without such ending/suffix. * * It is not comfortable to learn such word if you do not know base word. */ NoBaseWordInSet(true, { "Words set does not have base word(s) '${it.missedBaseWords.joinToString("|")}'.\n" + "It is advised to add these base word(s) to the set." }), // T O D O: do not save warnings to file since they are recalculated, only save 'ignore' flags TooManyExampleNewCardCandidates(true, { "There are too many examples similar to learning cards for '${it.from}' (${it.exampleNewCardCandidateCount})." + " Please convert them to separate cards."}), // *************************** High priority warnings ************************************************************** // TranslationIsNotPrepared(true, {"The from/translation for '${it.from}' is not prepared for learning. " + "Please remove unneeded symbols (like [, 1., 2., 1), 2) so on) and unpaired brackets '()'."}), Duplicates(true, { "Duplicate. Please remove duplicates." }), NoTranslation(true, {"No translation for '${it.from}'."}), // *************************** Ignore flags ************************************************************************ // /** * Marker to stop validation on NoBaseWordInSet. */ BaseWordDoesNotExist(false, {""}), IgnoreExampleCardCandidates(false, {""}), ; val cssClass: String get() = "WordCardStatus-${this.name}" companion object { val allCssClasses = WordCardStatus.values().map { it.cssClass } } } enum class PredefinedSet (val humanName: String) { DifficultToListen("Difficult To Listen"), DifficultSense("Difficult Sense"), }
0
Kotlin
0
0
f90861cbea00dd535e86e05dbc411cde129936c3
8,325
learn-words
Creative Commons Attribution 3.0 Unported
plugins/kotlin/idea/tests/testData/quickfix/surroundWithNullCheck/assignment.kt
ingokegel
72,937,917
false
null
// "Surround with null check" "true" fun foo(s: String?) { var ss: String = "" ss = <caret>s } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.SurroundWithNullCheckFix
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
185
intellij-community
Apache License 2.0
app/src/main/java/com/christianbahl/swapico/planets/model/PlanetsResponse.kt
Bodo1981
44,470,954
false
null
package com.christianbahl.swapico.planets.model import com.christianbahl.swapico.model.IListData import com.google.gson.annotations.SerializedName /** * @author <NAME> */ class PlanetsResponse(override val name: String, val diameter: String, @SerializedName("rotation_period") val rotationPeriod: String, val gender: String, @SerializedName("orbital_period") val orbitalPeriod: String, val gravity: String, val population: String, val climate: String, val terrain: String, @SerializedName("surface_water") val surfaceWater: String, val residents: List<String>, val films: List<String>, override val url: String, val created: String, val edited: String) : IListData { override val displayData: Map<String, String>? get() = mapOf("Title" to name, "Diameter" to diameter, "Rotation period" to rotationPeriod, "Gender" to gender, "Orbital period" to orbitalPeriod, "Gravity" to gravity, "Population" to population, "Climate" to climate, "Terrain" to terrain, "Surface water" to surfaceWater) }
1
null
1
1
0d029b8064c941766eafb7bb7000c8289a4c96ec
1,332
swapi.co
Apache License 2.0
shared/src/test/java/com/google/samples/apps/iosched/test/util/FakeAppDatabase.kt
google
18,347,476
false
null
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.test.util import androidx.room.DatabaseConfiguration import androidx.room.InvalidationTracker import androidx.sqlite.db.SupportSQLiteOpenHelper import com.google.samples.apps.iosched.shared.data.db.AppDatabase import com.google.samples.apps.iosched.shared.data.db.CodelabFtsDao import com.google.samples.apps.iosched.shared.data.db.CodelabFtsEntity import com.google.samples.apps.iosched.shared.data.db.SessionFtsDao import com.google.samples.apps.iosched.shared.data.db.SessionFtsEntity import com.google.samples.apps.iosched.shared.data.db.SpeakerFtsDao import com.google.samples.apps.iosched.shared.data.db.SpeakerFtsEntity import com.google.samples.apps.iosched.test.data.TestData import com.nhaarman.mockito_kotlin.mock import org.mockito.Mockito class FakeAppDatabase : AppDatabase() { override fun sessionFtsDao(): SessionFtsDao { return Mockito.mock(SessionFtsDao::class.java) } override fun speakerFtsDao(): SpeakerFtsDao { return Mockito.mock(SpeakerFtsDao::class.java) } override fun codelabFtsDao(): CodelabFtsDao { return Mockito.mock(CodelabFtsDao::class.java) } override fun createOpenHelper(config: DatabaseConfiguration?): SupportSQLiteOpenHelper { return Mockito.mock(SupportSQLiteOpenHelper::class.java) } override fun createInvalidationTracker(): InvalidationTracker { return Mockito.mock(InvalidationTracker::class.java) } override fun clearAllTables() {} } /** * A fake [AppDatabase] used in `SearchUseCaseTest`. */ class FakeSearchAppDatabase : AppDatabase() { override fun sessionFtsDao(): SessionFtsDao { return object : SessionFtsDao { override fun insertAll(sessions: List<SessionFtsEntity>) { TODO("not implemented") } override fun searchAllSessions(query: String): List<String> { return when (query) { QUERY_TITLE.toLowerCase(), QUERY_TITLE_WITH_TOKEN -> listOf( TestData.session0.id ) QUERY_ABSTRACT.toLowerCase(), QUERY_ABSTRACT_WITH_TOKEN -> listOf( TestData.session0.id ) QUERY_WITH_NO_MATCH.toLowerCase() -> emptyList() else -> emptyList() } } } } override fun speakerFtsDao(): SpeakerFtsDao { return object : SpeakerFtsDao { override fun insertAll(speakers: List<SpeakerFtsEntity>) { TODO("not implemented") } override fun searchAllSpeakers(query: String): List<String> { return emptyList() } } } override fun codelabFtsDao(): CodelabFtsDao { return object : CodelabFtsDao { override fun insertAll(codelabs: List<CodelabFtsEntity>) { TODO("not implemented") } override fun searchAllCodelabs(query: String): List<String> { return emptyList() } } } override fun createOpenHelper(config: DatabaseConfiguration?): SupportSQLiteOpenHelper { TODO("not implemented") } override fun createInvalidationTracker(): InvalidationTracker { // No-op return mock {} } override fun clearAllTables() { TODO("not implemented") } companion object { const val QUERY_TITLE = "session 0" const val QUERY_ABSTRACT = "Awesome" const val QUERY_WITH_NO_MATCH = "Invalid search query" const val QUERY_ONLY_SPACES = " " const val QUERY_TITLE_WITH_TOKEN = "session* AND 0*" const val QUERY_ABSTRACT_WITH_TOKEN = "awesome*" } }
77
Kotlin
6259
21,755
738e1e008096fad5f36612325275e80c33dbe436
4,294
iosched
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Emptywallettick.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.twotone import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.TwotoneGroup public val TwotoneGroup.Emptywallettick: ImageVector get() { if (_emptywallettick != null) { return _emptywallettick!! } _emptywallettick = Builder(name = "Emptywallettick", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.04f, 13.55f) curveTo(17.62f, 13.96f, 17.38f, 14.55f, 17.44f, 15.18f) curveTo(17.53f, 16.26f, 18.52f, 17.05f, 19.6f, 17.05f) horizontalLineTo(21.5f) verticalLineTo(18.24f) curveTo(21.5f, 20.31f, 19.81f, 22.0f, 17.74f, 22.0f) horizontalLineTo(7.63f) curveTo(7.94f, 21.74f, 8.21f, 21.42f, 8.42f, 21.06f) curveTo(8.79f, 20.46f, 9.0f, 19.75f, 9.0f, 19.0f) curveTo(9.0f, 16.79f, 7.21f, 15.0f, 5.0f, 15.0f) curveTo(4.06f, 15.0f, 3.19f, 15.33f, 2.5f, 15.88f) verticalLineTo(11.51f) curveTo(2.5f, 9.44f, 4.19f, 7.75f, 6.26f, 7.75f) horizontalLineTo(17.74f) curveTo(19.81f, 7.75f, 21.5f, 9.44f, 21.5f, 11.51f) verticalLineTo(12.95f) horizontalLineTo(19.48f) curveTo(18.92f, 12.95f, 18.41f, 13.17f, 18.04f, 13.55f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(2.5f, 12.4098f) verticalLineTo(7.8399f) curveTo(2.5f, 6.6499f, 3.23f, 5.5898f, 4.34f, 5.1698f) lineTo(12.28f, 2.1698f) curveTo(13.52f, 1.6998f, 14.85f, 2.6198f, 14.85f, 3.9499f) verticalLineTo(7.7498f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(22.5608f, 13.9702f) verticalLineTo(16.0302f) curveTo(22.5608f, 16.5802f, 22.1208f, 17.0302f, 21.5608f, 17.0502f) horizontalLineTo(19.6008f) curveTo(18.5208f, 17.0502f, 17.5308f, 16.2602f, 17.4408f, 15.1802f) curveTo(17.3808f, 14.5502f, 17.6208f, 13.9602f, 18.0408f, 13.5502f) curveTo(18.4108f, 13.1702f, 18.9208f, 12.9502f, 19.4808f, 12.9502f) horizontalLineTo(21.5608f) curveTo(22.1208f, 12.9702f, 22.5608f, 13.4202f, 22.5608f, 13.9702f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0f, 12.0f) horizontalLineTo(14.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 19.0f) curveTo(9.0f, 19.75f, 8.79f, 20.46f, 8.42f, 21.06f) curveTo(8.21f, 21.42f, 7.94f, 21.74f, 7.63f, 22.0f) curveTo(6.93f, 22.63f, 6.01f, 23.0f, 5.0f, 23.0f) curveTo(3.54f, 23.0f, 2.27f, 22.22f, 1.58f, 21.06f) curveTo(1.21f, 20.46f, 1.0f, 19.75f, 1.0f, 19.0f) curveTo(1.0f, 17.74f, 1.58f, 16.61f, 2.5f, 15.88f) curveTo(3.19f, 15.33f, 4.06f, 15.0f, 5.0f, 15.0f) curveTo(7.21f, 15.0f, 9.0f, 16.79f, 9.0f, 19.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.4395f, 19.0f) lineTo(4.4294f, 19.99f) lineTo(6.5595f, 18.02f) } } .build() return _emptywallettick!! } private var _emptywallettick: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
5,721
VuesaxIcons
MIT License
kex-runner/src/test/kotlin/org/vorpal/research/kex/crash/DescriptorCrashReproductionLongTest.kt
vorpal-research
204,454,367
false
null
package org.vorpal.research.kex.crash import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.InternalSerializationApi import org.junit.Test import org.vorpal.research.kex.asm.analysis.crash.CrashReproductionChecker import org.vorpal.research.kex.test.crash.CrashTrigger import kotlin.time.ExperimentalTime @ExperimentalTime @ExperimentalSerializationApi @InternalSerializationApi @DelicateCoroutinesApi class DescriptorCrashReproductionLongTest : CrashReproductionTest( "descriptor-crash-reproduction", CrashReproductionChecker::runWithDescriptorPreconditions ) { @Test fun testNullPointerException() { val expectedStackTrace = produceStackTrace { CrashTrigger().triggerNullPtr() } assertCrash(expectedStackTrace) } // @Test // fun testAssertionError() { // val expectedStackTrace = produceStackTrace { CrashTrigger().triggerAssert() } // assertCrash(expectedStackTrace) // } // todo: fix flakiness // @Test // fun testArithmeticException() { // val expectedStackTrace = produceStackTrace { CrashTrigger().triggerException() } // assertCrash(expectedStackTrace) // } @Test fun testNegativeSizeArrayException() { val expectedStackTrace = produceStackTrace { CrashTrigger().triggerNegativeArray() } assertCrash(expectedStackTrace) } @Test fun testArrayIndexOOBException() { val expectedStackTrace = produceStackTrace { CrashTrigger().triggerArrayOOB() } assertCrash(expectedStackTrace) } }
9
null
20
28
459dd8cb1c5b1512b5a920260cd0ebe503861b3e
1,617
kex
Apache License 2.0
plugins/devkit/devkit-kotlin-tests/testData/inspections/missingApi/library/RecentKotlinUtils.kt
hkjang
201,411,886
false
{"Text": 3950, "XML": 4557, "Ant Build System": 13, "Shell": 472, "Markdown": 298, "Ignore List": 79, "Git Attributes": 9, "Batchfile": 30, "SVG": 1981, "Java": 63985, "C++": 15, "HTML": 2721, "Kotlin": 4326, "DTrace": 1, "Gradle": 70, "Java Properties": 94, "INI": 236, "JFlex": 27, "Objective-C": 19, "Groovy": 3306, "XSLT": 109, "JavaScript": 152, "CSS": 55, "JSON": 1053, "desktop": 1, "Python": 9878, "JAR Manifest": 11, "YAML": 374, "C#": 37, "Smalltalk": 17, "Diff": 126, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "CoffeeScript": 3, "JSON with Comments": 42, "Vue": 10, "OpenStep Property List": 41, "Protocol Buffer": 2, "fish": 1, "EditorConfig": 211, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "PHP": 43, "Ruby": 4, "XML Property List": 77, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "GraphQL": 18, "C": 42, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 6, "Microsoft Visual Studio Solution": 6, "VBScript": 1, "NSIS": 8, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "TOML": 1, "Dockerfile": 1, "Regular Expression": 3, "JSON5": 4}
package library fun recentTopLevelFunction() { } fun String.recentExtensionFunction() { } inline fun String.recentInlineExtensionFunction(functionalParameter: () -> String) { }
1
null
1
1
a79249276cf6b68a6376d1f12964572283301a01
179
intellij-community
Apache License 2.0
samples/tutorial/tutorial-3-complete/src/main/java/workflow/tutorial/TodoListLayoutRunner.kt
square
268,864,554
false
null
package workflow.tutorial import androidx.recyclerview.widget.LinearLayoutManager import com.squareup.workflow1.ui.LayoutRunner import com.squareup.workflow1.ui.LayoutRunner.Companion.bind import com.squareup.workflow1.ui.ViewEnvironment import com.squareup.workflow1.ui.ViewFactory import com.squareup.workflow1.ui.WorkflowUiExperimentalApi import com.squareup.workflow1.ui.backPressedHandler import workflow.tutorial.views.TodoListAdapter import workflow.tutorial.views.databinding.TodoListViewBinding @OptIn(WorkflowUiExperimentalApi::class) class TodoListLayoutRunner( private val todoListBinding: TodoListViewBinding ) : LayoutRunner<TodoListScreen> { private val adapter = TodoListAdapter() init { todoListBinding.todoList.layoutManager = LinearLayoutManager(todoListBinding.root.context) todoListBinding.todoList.adapter = adapter } override fun showRendering( rendering: TodoListScreen, viewEnvironment: ViewEnvironment ) { todoListBinding.root.backPressedHandler = rendering.onBack with(todoListBinding.todoListWelcome) { text = resources.getString(workflow.tutorial.views.R.string.todo_list_welcome, rendering.username) } adapter.todoList = rendering.todoTitles adapter.notifyDataSetChanged() } companion object : ViewFactory<TodoListScreen> by bind( TodoListViewBinding::inflate, ::TodoListLayoutRunner ) }
177
null
99
995
daf192e24d7b47943caf534e62e4b70d08028100
1,398
workflow-kotlin
Apache License 2.0
exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Constraints.kt
JetBrains
11,765,017
false
null
package org.jetbrains.exposed.sql import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.vendors.* import org.jetbrains.exposed.sql.vendors.currentDialectIfAvailable import org.jetbrains.exposed.sql.vendors.inProperCase import java.sql.DatabaseMetaData /** * Common interface for database objects that can be created, modified and dropped. */ interface DdlAware { /** Returns the list of DDL statements that create this object. */ fun createStatement(): List<String> /** Returns the list of DDL statements that modify this object. */ fun modifyStatement(): List<String> /** Returns the list of DDL statements that drops this object. */ fun dropStatement(): List<String> } /** * Represents reference constraint actions. * Read [Referential actions](https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-referential-actions) from MySQL docs * or on [StackOverflow](https://stackoverflow.com/a/6720458/813981) */ enum class ReferenceOption { CASCADE, SET_NULL, RESTRICT, NO_ACTION, SET_DEFAULT; override fun toString(): String = name.replace("_", " ") companion object { /** Returns the corresponding [ReferenceOption] for the specified [refOption] from JDBC. */ fun resolveRefOptionFromJdbc(refOption: Int): ReferenceOption = when (refOption) { DatabaseMetaData.importedKeyCascade -> CASCADE DatabaseMetaData.importedKeySetNull -> SET_NULL DatabaseMetaData.importedKeyRestrict -> RESTRICT DatabaseMetaData.importedKeyNoAction -> NO_ACTION DatabaseMetaData.importedKeySetDefault -> SET_DEFAULT else -> currentDialect.defaultReferenceOption } } } /** * Represents a foreign key constraint. */ data class ForeignKeyConstraint( val references: Map<Column<*>, Column<*>>, private val onUpdate: ReferenceOption?, private val onDelete: ReferenceOption?, private val name: String? ) : DdlAware { constructor( target: Column<*>, from: Column<*>, onUpdate: ReferenceOption?, onDelete: ReferenceOption?, name: String? ) : this(mapOf(from to target), onUpdate, onDelete, name) private val tx: Transaction get() = TransactionManager.current() val target: LinkedHashSet<Column<*>> = LinkedHashSet(references.values) val targetTable: Table = target.first().table /** Name of the child table. */ val targetTableName: String get() = tx.identity(targetTable) /** Names of the foreign key columns. */ private val targetColumns: String get() = target.joinToString { tx.identity(it) } val from: LinkedHashSet<Column<*>> = LinkedHashSet(references.keys) val fromTable: Table = from.first().table /** Name of the parent table. */ val fromTableName: String get() = tx.identity(fromTable) /** Names of the key columns from the parent table. */ private val fromColumns: String get() = from.joinToString { tx.identity(it) } /** Reference option when performing update operations. */ val updateRule: ReferenceOption? get() = onUpdate ?: currentDialectIfAvailable?.defaultReferenceOption /** Reference option when performing delete operations. */ val deleteRule: ReferenceOption? get() = onDelete ?: currentDialectIfAvailable?.defaultReferenceOption /** Custom foreign key name if was provided */ val customFkName: String? get() = name /** Name of this constraint. */ val fkName: String get() = tx.db.identifierManager.cutIfNecessaryAndQuote( name ?: ( "fk_${fromTable.tableNameWithoutSchemeSanitized}_${from.joinToString("_") { it.name }}__" + target.joinToString("_") { it.name } ) ).inProperCase() internal val foreignKeyPart: String get() = buildString { if (fkName.isNotBlank()) { append("CONSTRAINT $fkName ") } append("FOREIGN KEY ($fromColumns) REFERENCES $targetTableName($targetColumns)") if (deleteRule != ReferenceOption.NO_ACTION) { if (deleteRule == ReferenceOption.SET_DEFAULT) { when (currentDialect) { is MariaDBDialect -> exposedLogger.warn( "MariaDB doesn't support FOREIGN KEY with SET DEFAULT reference option with ON DELETE clause. " + "Please check your $fromTableName table." ) is MysqlDialect -> exposedLogger.warn( "MySQL doesn't support FOREIGN KEY with SET DEFAULT reference option with ON DELETE clause. " + "Please check your $fromTableName table." ) else -> append(" ON DELETE $deleteRule") } } else { append(" ON DELETE $deleteRule") } } if (updateRule != ReferenceOption.NO_ACTION) { if (currentDialect is OracleDialect || currentDialect.h2Mode == H2Dialect.H2CompatibilityMode.Oracle) { exposedLogger.warn("Oracle doesn't support FOREIGN KEY with ON UPDATE clause. Please check your $fromTableName table.") } else if (updateRule == ReferenceOption.SET_DEFAULT) { when (currentDialect) { is MariaDBDialect -> exposedLogger.warn( "MariaDB doesn't support FOREIGN KEY with SET DEFAULT reference option with ON UPDATE clause. " + "Please check your $fromTableName table." ) is MysqlDialect -> exposedLogger.warn( "MySQL doesn't support FOREIGN KEY with SET DEFAULT reference option with ON UPDATE clause. " + "Please check your $fromTableName table." ) else -> append(" ON UPDATE $updateRule") } } else { append(" ON UPDATE $updateRule") } } } override fun createStatement(): List<String> = listOf("ALTER TABLE $fromTableName ADD $foreignKeyPart") override fun modifyStatement(): List<String> = dropStatement() + createStatement() override fun dropStatement(): List<String> { val constraintType = when (currentDialect) { is MysqlDialect -> "FOREIGN KEY" else -> "CONSTRAINT" } return listOf("ALTER TABLE $fromTableName DROP $constraintType $fkName") } fun targetOf(from: Column<*>): Column<*>? = references[from] operator fun plus(other: ForeignKeyConstraint): ForeignKeyConstraint { return copy(references = references + other.references) } override fun toString() = "ForeignKeyConstraint(fkName='$fkName')" } /** * Represents a check constraint. */ data class CheckConstraint( /** Name of the table where the constraint is defined. */ val tableName: String, /** Name of the check constraint. */ val checkName: String, /** Boolean expression used for the check constraint. */ val checkOp: String ) : DdlAware { internal val checkPart = "CONSTRAINT $checkName CHECK ($checkOp)" private val DatabaseDialect.cannotAlterCheckConstraint: Boolean get() = this is SQLiteDialect || (this as? MysqlDialect)?.isMysql8 == false override fun createStatement(): List<String> { return if (currentDialect.cannotAlterCheckConstraint) { exposedLogger.warn("Creation of CHECK constraints is not currently supported by ${currentDialect.name}") listOf() } else { listOf("ALTER TABLE $tableName ADD $checkPart") } } override fun modifyStatement(): List<String> = dropStatement() + createStatement() override fun dropStatement(): List<String> { return if (currentDialect.cannotAlterCheckConstraint) { exposedLogger.warn("Deletion of CHECK constraints is not currently supported by ${currentDialect.name}") listOf() } else { listOf("ALTER TABLE $tableName DROP CONSTRAINT $checkName") } } companion object { internal fun from(table: Table, name: String, op: Op<Boolean>): CheckConstraint { require(name.isNotBlank()) { "Check constraint name cannot be blank" } val tr = TransactionManager.current() val identifierManager = tr.db.identifierManager val tableName = tr.identity(table) val checkOpSQL = op.toString().replace("$tableName.", "") return CheckConstraint(tableName, identifierManager.cutIfNecessaryAndQuote(name), checkOpSQL) } } } typealias FilterCondition = (SqlExpressionBuilder.() -> Op<Boolean>)? /** * Represents an index. */ data class Index( /** Columns that are part of the index. */ val columns: List<Column<*>>, /** Whether the index in unique or not. */ val unique: Boolean, /** Optional custom name for the index. */ val customName: String? = null, /** Optional custom index type (e.g, BTREE or HASH) */ val indexType: String? = null, /** Partial index filter condition */ val filterCondition: Op<Boolean>? = null, /** Functions that are part of the index. */ val functions: List<ExpressionWithColumnType<*>>? = null, /** Table where the functional index should be defined. */ val functionsTable: Table? = null ) : DdlAware { /** Table where the index is defined. */ val table: Table /** Name of the index. */ val indexName: String get() = customName ?: buildString { append(table.nameInDatabaseCase()) append('_') append(columns.joinToString("_") { it.name }.inProperCase()) functions?.let { f -> if (columns.isNotEmpty()) append('_') append(f.joinToString("_") { it.toString().substringBefore("(").lowercase() }.inProperCase()) } if (unique) { append("_unique".inProperCase()) } } init { require(columns.isNotEmpty() || functions?.isNotEmpty() == true) { "At least one column or function is required to create an index" } val columnsTable = if (columns.isNotEmpty()) { val table = columns.distinctBy { it.table }.singleOrNull()?.table requireNotNull(table) { "Columns from different tables can't persist in one index" } table } else null if (functions?.isNotEmpty() == true) { requireNotNull(functionsTable) { "functionsTable argument must also be provided if functions are defined to create an index" } } this.table = columnsTable ?: functionsTable!! } override fun createStatement(): List<String> = listOf(currentDialect.createIndex(this)) override fun modifyStatement(): List<String> = dropStatement() + createStatement() override fun dropStatement(): List<String> = listOf( currentDialect.dropIndex(table.nameInDatabaseCase(), indexName, unique, filterCondition != null || functions != null) ) /** Returns `true` if the [other] index has the same columns and uniqueness as this index, but a different name, `false` otherwise */ fun onlyNameDiffer(other: Index): Boolean = indexName != other.indexName && columns == other.columns && unique == other.unique override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Index) return false if (indexName != other.indexName) return false if (columns != other.columns) return false if (unique != other.unique) return false return true } override fun hashCode(): Int { var result = indexName.hashCode() result = 31 * result + columns.hashCode() result = 31 * result + unique.hashCode() return result } override fun toString(): String = "${if (unique) "Unique " else ""}Index '$indexName' for '${table.nameInDatabaseCase()}' on columns ${columns.joinToString()}" }
351
null
650
7,618
600ea0d6c12d5758608c709995af49c97923d546
12,394
Exposed
Apache License 2.0
platform/backend/core/src/main/kotlin/io/hamal/core/component/Retry.kt
hamal-io
622,870,037
false
{"Kotlin": 2114763, "C": 1398432, "TypeScript": 279976, "Lua": 100966, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 3406, "CMake": 2810, "CSS": 1626, "HTML": 1239, "Shell": 977}
package io.hamal.core.component import org.springframework.stereotype.Component import java.util.concurrent.ThreadLocalRandom import java.util.concurrent.atomic.AtomicReference import kotlin.math.min import kotlin.math.pow import kotlin.time.Duration fun interface DelayRetry { operator fun invoke(iteration: Int) } class DelayRetryExponentialTime( private val base: Duration, private val maxBackOffTime: Duration ) : DelayRetry { private val rand = ThreadLocalRandom.current() override operator fun invoke(iteration: Int) { val pow: Double = base.inWholeMilliseconds.toDouble().pow(iteration.toDouble()) val extraDelay = rand.nextInt(1000) Thread.sleep(min(pow * 1000 + extraDelay, maxBackOffTime.inWholeMilliseconds.toDouble()).toLong()) } } class DelayRetryFixedTime( private val delay: Duration ) : DelayRetry { override operator fun invoke(iteration: Int) { Thread.sleep(delay.inWholeMilliseconds) } } object DelayRetryNoDelay : DelayRetry { override fun invoke(iteration: Int) {} } @Component class Retry(private val delay: DelayRetry) { operator fun <T> invoke(maxAttempts: Int = 5, action: () -> T): T { require(maxAttempts >= 0) { "maxAttempts must not be negative" } val exceptionRef = AtomicReference<NoSuchElementException>(null) for (iteration in 0 until maxAttempts) { try { return action() } catch (e: java.util.NoSuchElementException) { exceptionRef.set(e) delay(iteration) } catch (t: Throwable) { throw t } } throw exceptionRef.get() } }
26
Kotlin
0
0
64288303fd12b334787c7bbb15afbaa99f716125
1,701
hamal
Creative Commons Zero v1.0 Universal
libs/sockets/src/unitTest/kotlin/batect/sockets/namedpipes/NamedPipeSocketFactorySpec.kt
batect
102,647,061
false
null
/* Copyright 2017-2021 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.sockets.namedpipes import batect.testutils.createForEachTest import batect.testutils.equalTo import batect.testutils.given import batect.testutils.on import batect.testutils.onlyOn import batect.testutils.runForEachTest import batect.testutils.withMessage import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.throws import jnr.ffi.Platform import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress import java.net.SocketTimeoutException import java.util.UUID import java.util.concurrent.TimeUnit object NamedPipeSocketFactorySpec : Spek({ onlyOn(setOf(Platform.OS.WINDOWS)) { describe("a named pipe socket factory") { val factory = NamedPipeSocketFactory() describe("creating a socket") { val socket by createForEachTest { factory.createSocket() } afterEachTest { socket.close() } fun connect(pipePath: String) { val port = 1234 val encodedPath = NamedPipeDns.encodePath(pipePath) val address = InetSocketAddress.createUnresolved(encodedPath, port) socket.connect(address) } on("using that socket to connect to a named pipe that exists") { val pipePath by createForEachTest { getTemporaryNamedPipePath() } val pipeServer by createForEachTest { NamedPipeTestServer(pipePath) } afterEachTest { pipeServer.close() } given("the server responds immediately with some data") { beforeEachTest { pipeServer.dataToSend = "Hello from the other side\n" connect(pipePath) socket.soTimeout = 1000 } val dataRead by runForEachTest { socket.getInputStream().bufferedReader().readLine() } it("connects to the socket and can receive data") { assertThat(dataRead, equalTo("Hello from the other side")) } } given("the server responds with some data after a delay") { beforeEachTest { pipeServer.sendDelay = 500 pipeServer.dataToSend = "Hello from the delayed side\n" connect(pipePath) socket.soTimeout = 1000 } val dataRead by runForEachTest { socket.getInputStream().bufferedReader().readLine() } it("connects to the socket and can receive data") { assertThat(dataRead, equalTo("Hello from the delayed side")) } } given("the client is configured with an infinite timeout") { beforeEachTest { pipeServer.sendDelay = 500 pipeServer.dataToSend = "Hello from the infinite side\n" connect(pipePath) socket.soTimeout = 0 } val dataRead by runForEachTest { socket.getInputStream().bufferedReader().readLine() } it("connects to the socket and can receive data") { assertThat(dataRead, equalTo("Hello from the infinite side")) } } given("the client sends some data") { beforeEachTest { pipeServer.dataToSend = "\n" pipeServer.expectData = true connect(pipePath) socket.getInputStream().bufferedReader().readLine() socket.getOutputStream().bufferedWriter().use { writer -> writer.write("Hello from the client") } if (!pipeServer.dataReceivedEvent.tryAcquire(5, TimeUnit.SECONDS)) { throw RuntimeException("Named pipe server never received data.") } } it("connects to the socket and can send data") { assertThat(pipeServer.dataReceived, equalTo("Hello from the client")) } } given("the server does not respond within the timeout period") { beforeEachTest { connect(pipePath) socket.soTimeout = 1 } it("throws an appropriate exception") { assertThat( { socket.getInputStream().bufferedReader().readLine() }, throws<SocketTimeoutException>(withMessage("Operation timed out after 1 ms.")) ) } } } on("using that socket to connect to a named pipe that doesn't exist") { val encodedPath = NamedPipeDns.encodePath("""\\.\pipe\does-not-exist""") val address = InetSocketAddress.createUnresolved(encodedPath, 1234) it("throws an appropriate exception") { assertThat( { socket.connect(address) }, throws<IOException>(withMessage("""Cannot connect to '\\.\pipe\does-not-exist': the named pipe does not exist""")) ) } } } on("creating a socket with a particular host and port") { it("throws an appropriate exception when using primitive values") { assertThat({ factory.createSocket("somehost", 123) }, throws<UnsupportedOperationException>()) } it("throws an appropriate exception when using non-primitive values") { assertThat( { factory.createSocket(InetAddress.getLocalHost(), 123) }, throws<UnsupportedOperationException>() ) } } on("creating a socket with both a local and remote host and port") { it("throws an appropriate exception when using primitive values") { assertThat( { factory.createSocket("somehost", 123, InetAddress.getLocalHost(), 123) }, throws<UnsupportedOperationException>() ) } it("throws an appropriate exception when using non-primitive values") { assertThat( { factory.createSocket( InetAddress.getLocalHost(), 123, InetAddress.getLocalHost(), 123 ) }, throws<UnsupportedOperationException>() ) } } } } }) private fun getTemporaryNamedPipePath(): String = """\\.\pipe\batect-${NamedPipeSocketFactorySpec::class.simpleName}-${UUID.randomUUID()}"""
12
null
47
620
1b6cb1d79d91a70a0cb038cc29b2db1c025fea9e
8,343
batect
Apache License 2.0
app/src/main/java/com/liuhe/widget/bean/Msg.kt
liuhedev
129,835,036
false
null
package com.liuhe.widget.bean /** * 消息体 * @author liuhe */ class Msg(var title: String, var unReadMsgCount: Int)
0
Kotlin
0
0
7bd0a910ec7ea07209f1107506a61e69a3beb5dd
117
WidgetPractice
Apache License 2.0
bukkit/elysium-core-bukkit/src/main/kotlin/com/seventh_root/elysium/core/bukkit/listener/PluginEnableListener.kt
liambaloh
72,128,706
true
{"Kotlin": 752068}
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seventh_root.elysium.core.bukkit.listener import com.seventh_root.elysium.core.bukkit.ElysiumCoreBukkit import com.seventh_root.elysium.core.bukkit.plugin.ElysiumBukkitPlugin import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.server.PluginEnableEvent class PluginEnableListener(private val plugin: ElysiumCoreBukkit): Listener { @EventHandler fun onPluginEnable(event: PluginEnableEvent) { if (event.plugin !== plugin) { if (event.plugin is ElysiumBukkitPlugin) { val elysiumBukkitPlugin = event.plugin as ElysiumBukkitPlugin plugin.initializePlugin(elysiumBukkitPlugin) } } } }
0
Kotlin
0
0
f3db81625f1c12c8a9fc2b88a3c6bd71c2559acc
1,313
elysium
Apache License 2.0
presentation/src/main/java/com/jyproject/presentation/ui/feature/home/composable/PlaceBlocks.kt
JunYeong0314
778,833,940
false
{"Kotlin": 208970}
package com.jyproject.presentation.ui.feature.home.composable import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Clear import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.jyproject.domain.models.Place import com.jyproject.presentation.R import com.jyproject.presentation.ui.feature.common.dialog.PlaceDeleteDialog import com.jyproject.presentation.ui.feature.home.HomeContract import com.jyproject.presentation.ui.util.modifierExtensions.singleClick.clickableSingle @Composable fun PlaceBlocks( state: HomeContract.State, onEventSend: (event: HomeContract.Event) -> Unit, onClickAddBtn: () -> Unit ) { Column( modifier = Modifier.padding(start = 12.dp), ) { Row( modifier = Modifier.fillMaxWidth() ) { Text( text = "추가한 장소", fontWeight = FontWeight.Bold, fontSize = 16.sp, ) Box( modifier = Modifier .fillMaxWidth() .clickableSingle { onClickAddBtn() }, contentAlignment = Alignment.CenterEnd ){ Icon( modifier = Modifier .size(28.dp) .padding(end = 6.dp), imageVector = Icons.Default.Add, contentDescription = "add", tint = Color.DarkGray ) } } Spacer(modifier = Modifier.size(8.dp)) if(state.placeList.isEmpty()){ EmptyPlaceList() }else{ LazyRow( modifier = Modifier ) { itemsIndexed(state.placeList){_, place: Place -> place.place?.let { placeValue-> PlaceBlock( place = placeValue, onEventSend = onEventSend, ) } Spacer(modifier = Modifier.size(8.dp)) } } } } } @Composable fun PlaceBlock( place: String, onEventSend: (event: HomeContract.Event) -> Unit, ) { var showDeleteDialog by remember { mutableStateOf(false) } if(showDeleteDialog) { PlaceDeleteDialog( onDismissRequest = { showDeleteDialog = false }, onConfirmation = { onEventSend(HomeContract.Event.DeletePlace(place)) showDeleteDialog = false } ) } Row( modifier = Modifier .background( color = colorResource(id = R.color.app_base), shape = RoundedCornerShape(20.dp) ) .padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Text( modifier = Modifier .clickableSingle { onEventSend(HomeContract.Event.NavigationToPlaceDetail(place)) } , text = place, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color.White ) Spacer(modifier = Modifier.size(4.dp)) Icon( modifier = Modifier .size(20.dp) .clickableSingle { showDeleteDialog = true }, imageVector = Icons.Filled.Clear, contentDescription = "clear", tint = Color.White ) } }
0
Kotlin
0
0
edb71cf4db51cee1593aa31c66c25d616492d24c
4,727
PlacePick
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonersearch/model/PrisonerAlert.kt
ministryofjustice
256,501,813
false
null
package uk.gov.justice.digital.hmpps.prisonersearch.model import io.swagger.v3.oas.annotations.media.Schema data class PrisonerAlert( @Schema(description = "Alert Type", example = "H") val alertType: String, @Schema(description = "Alert Code", example = "HA") val alertCode: String, @Schema(description = "Active", example = "true") val active: Boolean, @Schema(description = "Expired", example = "true") val expired: Boolean, )
2
null
3
5
a5b642d297b981f0db85e39df535861141b815d0
447
prisoner-offender-search
MIT License
idea/tests/testData/checker/MainWithWarningOnUnusedParam.kt
JetBrains
278,369,660
false
null
// FIR_IDENTICAL // LANGUAGE_VERSION: 1.4 fun main(<warning descr="[UNUSED_PARAMETER] Parameter 'args' is never used">args</warning>: Array<String>) { }
0
null
37
82
cc81d7505bc3e9ad503d706998ae8026c067e838
156
intellij-kotlin
Apache License 2.0
collector-media3-exoplayer/src/main/java/com/bitmovin/analytics/media3/exoplayer/features/Media3ExoPlayerHttpRequestTrackingAdapter.kt
bitmovin
120,633,749
false
{"Kotlin": 1363235, "Java": 25098, "Shell": 13133}
package com.bitmovin.analytics.media3.exoplayer.features import android.net.Uri import android.util.Log import androidx.media3.common.C import androidx.media3.common.Timeline import androidx.media3.common.util.UnstableApi import androidx.media3.common.util.Util.inferContentType import androidx.media3.datasource.HttpDataSource import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.analytics.AnalyticsListener import androidx.media3.exoplayer.hls.HlsManifest import androidx.media3.exoplayer.source.LoadEventInfo import androidx.media3.exoplayer.source.MediaLoadData import com.bitmovin.analytics.Observable import com.bitmovin.analytics.ObservableSupport import com.bitmovin.analytics.OnAnalyticsReleasingEventListener import com.bitmovin.analytics.features.httprequesttracking.HttpRequest import com.bitmovin.analytics.features.httprequesttracking.HttpRequestType import com.bitmovin.analytics.features.httprequesttracking.OnDownloadFinishedEventListener import com.bitmovin.analytics.features.httprequesttracking.OnDownloadFinishedEventObject import com.bitmovin.analytics.media3.exoplayer.Media3ExoplayerUtil import com.bitmovin.analytics.utils.Util import java.io.IOException @androidx.annotation.OptIn(UnstableApi::class) internal class Media3ExoPlayerHttpRequestTrackingAdapter(private val player: ExoPlayer, private val onAnalyticsReleasingObservable: Observable<OnAnalyticsReleasingEventListener>) : Observable<OnDownloadFinishedEventListener>, OnAnalyticsReleasingEventListener { private val observableSupport = ObservableSupport<OnDownloadFinishedEventListener>() private val analyticsListener = object : AnalyticsListener { override fun onLoadCompleted( eventTime: AnalyticsListener.EventTime, loadEventInfo: LoadEventInfo, mediaLoadData: MediaLoadData, ) { catchAndLogException("Exception occurred in onLoadCompleted") { val statusCode = loadEventInfo.extractStatusCode ?: 0 notifyObservable(eventTime, loadEventInfo, mediaLoadData, true, statusCode) } } override fun onLoadError( eventTime: AnalyticsListener.EventTime, loadEventInfo: LoadEventInfo, mediaLoadData: MediaLoadData, error: IOException, wasCanceled: Boolean, ) { catchAndLogException("Exception occurred in onLoadError") { val loadEventInfoStatusCode = loadEventInfo.extractStatusCode ?: 0 val errorResponseCode = (error as? HttpDataSource.InvalidResponseCodeException)?.responseCode notifyObservable( eventTime, loadEventInfo, mediaLoadData, false, errorResponseCode ?: loadEventInfoStatusCode, ) } } } init { wireEvents() } private fun notifyObservable(eventTime: AnalyticsListener.EventTime, loadEventInfo: LoadEventInfo, mediaLoadData: MediaLoadData, success: Boolean, statusCode: Int) { val httpRequest = mapLoadCompletedArgsToHttpRequest(eventTime, loadEventInfo, mediaLoadData, statusCode, success) observableSupport.notify { listener -> listener.onDownloadFinished(OnDownloadFinishedEventObject(httpRequest)) } } private fun wireEvents() { onAnalyticsReleasingObservable.subscribe(this) player.addAnalyticsListener(analyticsListener) } private fun unwireEvents() { onAnalyticsReleasingObservable.unsubscribe(this) // we need to run this on the application thread to prevent exoplayer from crashing // when calling the api from a non application thread // (this is potentially called from okhttp callback which is on a separate thread) Media3ExoplayerUtil.executeSyncOrAsyncOnLooperThread(player.applicationLooper) { try { player.removeAnalyticsListener(analyticsListener) } catch (e: Exception) { Log.e(TAG, e.toString()) } } } override fun subscribe(listener: OnDownloadFinishedEventListener) { observableSupport.subscribe(listener) } override fun unsubscribe(listener: OnDownloadFinishedEventListener) { observableSupport.unsubscribe(listener) } override fun onReleasing() { unwireEvents() } companion object { private val TAG = Media3ExoPlayerHttpRequestTrackingAdapter::class.java.name private fun catchAndLogException(msg: String, block: () -> Unit) { // As ExoPlayer sometimes has breaking changes, we want to make sure that an optional feature isn't breaking our collector try { block() } catch (e: Exception) { Log.e(TAG, msg, e) } } private val String.extractStatusCode: Int? get() { val tokens = this.split(' ') if (tokens.size > 1) { val statusCodeString = tokens[1] return statusCodeString.toIntOrNull() } return null } private const val PATTERN = """null=\[(.*?)\]""" private val regex = PATTERN.toRegex() internal val LoadEventInfo.extractStatusCode: Int? get() { // the null key contains the status code information // this solution is bit hacky since I couldn't find a way to extract the null key from the java hashmap directly // using toString and parsing the string works (might be an issue with kotlin/java interoperability) // toString returns a string in the following format: // {null=[HTTP/1.1 200 OK], Accept-Ranges=[bytes], Access-Control-Allow-Credentials=[false], Access-Control-Allow-Headers=[*], Access-Control-Allow-Methods=[GET,POST,HEAD], .... val matchResult = regex.find(this.responseHeaders.toString()) val statusCodeString = matchResult?.value return statusCodeString?.extractStatusCode } private fun mapManifestType(uri: Uri, eventTime: AnalyticsListener.EventTime): HttpRequestType { return when (inferContentType(uri)) { C.CONTENT_TYPE_DASH -> HttpRequestType.MANIFEST_DASH C.CONTENT_TYPE_HLS -> mapHlsManifestType(uri, eventTime) C.CONTENT_TYPE_SS -> HttpRequestType.MANIFEST_SMOOTH else -> HttpRequestType.MANIFEST } } private fun mapHlsManifestType(uri: Uri, eventTime: AnalyticsListener.EventTime): HttpRequestType { try { val window = Timeline.Window() // we want the window corresponding to the eventTime that was part of the triggered event // thus we use the eventTime.windowIndex and eventTime.timeline // (and not eventTime.currentTimeline which corresponds to Player.getCurrentTimeline(), // and might not be the same timeline as the one from the eventTime) eventTime.timeline.getWindow(eventTime.windowIndex, window) val initialPlaylistUri = window.mediaItem.localConfiguration?.uri if (initialPlaylistUri != null) { return if (initialPlaylistUri == uri) HttpRequestType.MANIFEST_HLS_MASTER else HttpRequestType.MANIFEST_HLS_VARIANT } } catch (ignored: Exception) {} return HttpRequestType.MANIFEST_HLS } private fun mapTrackType(trackType: Int): HttpRequestType = when (trackType) { C.TRACK_TYPE_AUDIO -> HttpRequestType.MEDIA_AUDIO C.TRACK_TYPE_VIDEO, C.TRACK_TYPE_DEFAULT, -> HttpRequestType.MEDIA_VIDEO C.TRACK_TYPE_TEXT -> HttpRequestType.MEDIA_SUBTITLES else -> HttpRequestType.UNKNOWN } private const val HLS_MANIFEST_CLASSNAME = "com.google.android.exoplayer2.source.hls.HlsManifest" private val isHlsManifestClassLoaded get() = Util.isClassLoaded(HLS_MANIFEST_CLASSNAME, Media3ExoPlayerHttpRequestTrackingAdapter::class.java.classLoader) private fun mapDrmType(eventTime: AnalyticsListener.EventTime): HttpRequestType { if (isHlsManifestClassLoaded) { try { val window = Timeline.Window() // we want the window corresponding to the eventTime that was part of the triggered event // thus we use the eventTime.windowIndex and eventTime.timeline // (and not eventTime.currentTimeline which corresponds to Player.getCurrentTimeline(), // and might not be the same timeline as the one from the eventTime) eventTime.timeline.getWindow(eventTime.windowIndex, window) if (window.manifest is HlsManifest) { return HttpRequestType.KEY_HLS_AES } } catch (ignored: Exception) { } } // TODO AN-3302 HttpRequestType.DRM_LICENSE_WIDEVINE // maybe using trackFormat.drmInitData?.schemeType == "widevine" return HttpRequestType.DRM_OTHER } private fun mapDataType(eventTime: AnalyticsListener.EventTime, uri: Uri, dataType: Int, trackType: Int): HttpRequestType { when (dataType) { C.DATA_TYPE_DRM -> return mapDrmType(eventTime) C.DATA_TYPE_MEDIA_PROGRESSIVE_LIVE -> return HttpRequestType.MEDIA_PROGRESSIVE C.DATA_TYPE_MANIFEST -> return mapManifestType(uri, eventTime) C.DATA_TYPE_MEDIA, C.DATA_TYPE_MEDIA_INITIALIZATION, -> return mapTrackType(trackType) } return HttpRequestType.UNKNOWN } private fun mapLoadCompletedArgsToHttpRequest(eventTime: AnalyticsListener.EventTime, loadEventInfo: LoadEventInfo, mediaLoadData: MediaLoadData, statusCode: Int, success: Boolean): HttpRequest { val requestType = mapDataType(eventTime, loadEventInfo.uri, mediaLoadData.dataType, mediaLoadData.trackType) return HttpRequest(Util.timestamp, requestType, loadEventInfo.dataSpec.uri.toString(), loadEventInfo.uri.toString(), statusCode, loadEventInfo.loadDurationMs, null, loadEventInfo.bytesLoaded, success) } } }
1
Kotlin
6
9
eba960cdc95c2142f5f4bbeb0275690122dc65f9
10,593
bitmovin-analytics-collector-android
Amazon Digital Services License
src/main/kotlin/ai/hypergraph/kaliningraph/matrix/MatrixRing.kt
ileasile
424,362,465
true
{"Kotlin": 121295}
package ai.hypergraph.kaliningraph.matrix import ai.hypergraph.kaliningraph.* import ai.hypergraph.kaliningraph.types.* import org.ejml.data.* import org.ejml.kotlin.* import java.lang.reflect.Constructor import kotlin.math.* import kotlin.random.Random /** * Generic matrix which supports overloadable addition and multiplication * using an abstract algebra (e.g. tropical semiring). Useful for many * problems in graph theory. * * @see [MatrixRing] */ interface Matrix<T, R : Ring<T, R>, M : Matrix<T, R, M>> : SparseTensor<Triple<Int, Int, T>> { val data: List<T> override val map: MutableMap<Triple<Int, Int, T>, Int> get() = TODO() val numRows: Int val numCols: Int val algebra: MatrixRing<T, R> val indices get() = (0 until numRows) * (0 until numCols) val rows get() = data.chunked(numCols) val cols get() = (0 until numCols).map { c -> rows.map { it[c] } } operator fun times(that: M): M = with(algebra) { this@Matrix times that } operator fun plus(that: M): M = with(algebra) { this@Matrix plus that } // Constructs a new instance with the same concrete matrix type fun new(numCols: Int, numRows: Int, algebra: MatrixRing<T, R>, data: List<T>): M = (javaClass.getConstructor( MatrixRing::class.java, Int::class.java, Int::class.java, List::class.java ) as Constructor<M>).newInstance(algebra, numCols, numRows, data) fun join(that: Matrix<T, R, M>, op: (Int, Int) -> T): M = assert(numCols == that.numRows) { "Dimension mismatch: $numRows,$numCols . ${that.numRows},${that.numCols}" }.run { new(numCols, that.numRows, algebra, indices.map { (i, j) -> op(i, j) }) } operator fun get(r: Any, c: Any): T = TODO("Implement support for named indexing") operator fun get(r: Int, c: Int): T = data[r * numCols + c] operator fun get(r: Int): List<T> = data.toList().subList(r * numCols, r * numCols + numCols) fun transpose(): M = new(numCols, numRows, algebra, indices.map { (i, j) -> this[j, i] }) } /** * Ad hoc polymorphic algebra (can be specified at runtime). */ interface MatrixRing<T, R : Ring<T, R>> { val algebra: R infix fun <M : Matrix<T, R, M>> Matrix<T, R, M>.plus(that: Matrix<T, R, M>): M = join(that) { i, j -> with([email protected]) { this@plus[i][j] + that[i][j] } } infix fun List<T>.dot(es: List<T>): T = with(algebra) { zip(es).map { (a, b) -> a * b }.reduce { a, b -> a + b } } infix fun <M : Matrix<T, R, M>> Matrix<T, R, M>.times(that: Matrix<T, R, M>): M = join(that) { i, j -> this[i] dot that[j] } companion object { operator fun <T, R : Ring<T, R>> invoke(ring: R) = object : MatrixRing<T, R> { override val algebra: R = ring } } } // Ring with additive inverse interface MatrixField<T, R : Field<T, R>>: MatrixRing<T, R> { override val algebra: R infix fun <M : Matrix<T, R, M>> Matrix<T, R, M>.minus(that: Matrix<T, R, M>): M = join(that) { i, j -> with([email protected]) { this@minus[i][j] - that[i][j] } } companion object { operator fun <T, R : Field<T, R>> invoke(field: R) = object : MatrixField<T, R> { override val algebra: R = field } } } // https://www.ijcai.org/Proceedings/2020/0685.pdf val BOOLEAN_ALGEBRA = MatrixRing( Ring.of( nil = false, one = true, plus = { a, b -> a || b }, times = { a, b -> a && b } ) ) val INTEGER_FIELD = MatrixField( Field.of( nil = 0, one = 1, plus = { a, b -> a + b }, minus = { a, b -> a - b }, times = { a, b -> a * b }, div = { _, _ -> throw NotImplementedError("Division not defined on integer field.") } ) ) val DOUBLE_FIELD = MatrixField( Field.of( nil = 0.0, one = 1.0, plus = { a, b -> a + b }, minus = { a, b -> a - b }, times = { a, b -> a * b }, div = { a, b -> a / b } ) ) val MINPLUS_ALGEBRA = MatrixRing( Ring.of( nil = Integer.MAX_VALUE, one = 0, plus = { a, b -> min(a, b) }, times = { a, b -> a + b } ) ) val MAXPLUS_ALGEBRA = MatrixRing( Ring.of( nil = Integer.MIN_VALUE, one = 0, plus = { a, b -> max(a, b) }, times = { a, b -> a + b } ) ) abstract class AbstractMatrix<T, R: Ring<T, R>, M: AbstractMatrix<T, R, M>> constructor( override val algebra: MatrixRing<T, R>, override val numRows: Int, override val numCols: Int = numRows, override val data: List<T>, ) : Matrix<T, R, M> { val values by lazy { data.toSet() } override val map: MutableMap<Triple<Int, Int, T>, Int> by lazy { indices.fold(mutableMapOf()) { map, (r, c) -> val element = get(r, c) if (element != algebra.algebra.nil) map[Triple(r, c, element)] = 1 map } } override fun toString() = data.maxOf { it.toString().length + 2 }.let { pad -> data.foldIndexed("") { i, a, b -> a + "$b".padEnd(pad, ' ') + " " + if (i > 0 && (i + 1) % numCols == 0) "\n" else "" } } override fun equals(other: Any?) = other is FreeMatrix<*> && data.zip(other.data).all { (a, b) -> a == b } || other is Matrix<*, *, *> && other.data == data override fun hashCode() = data.hashCode() } // A free matrix has no associated algebra by default. If you try to do math // with the default implementation it will fail at runtime. open class FreeMatrix<T> constructor( override val algebra: MatrixRing<T, Ring.of<T>> = object : MatrixRing<T, Ring.of<T>> { override val algebra: Ring.of<T> by lazy { TODO() } }, override val numRows: Int, override val numCols: Int = numRows, override val data: List<T>, ) : AbstractMatrix<T, Ring.of<T>, FreeMatrix<T>>(algebra, numRows, numCols, data) { constructor(elements: List<T>) : this( numRows = sqrt(elements.size.toDouble()).toInt(), data = elements ) constructor(numRows: Int, numCols: Int = numRows, f: (Int, Int) -> T) : this( numRows = numRows, numCols = numCols, data = List(numRows * numCols) { f(it / numRows, it % numCols) } ) constructor(vararg rows: T) : this(rows.toList()) } // Concrete subclasses open class BooleanMatrix constructor( override val algebra: MatrixRing<Boolean, Ring.of<Boolean>> = BOOLEAN_ALGEBRA, override val numRows: Int, override val numCols: Int = numRows, override val data: List<Boolean>, ) : AbstractMatrix<Boolean, Ring.of<Boolean>, BooleanMatrix>(algebra, numRows, numCols, data) { constructor(elements: List<Boolean>) : this( algebra = BOOLEAN_ALGEBRA, numRows = sqrt(elements.size.toDouble()).toInt(), data = elements ) constructor(numRows: Int, numCols: Int = numRows, f: (Int, Int) -> Boolean) : this( numRows = numRows, numCols = numCols, data = List(numRows * numCols) { f(it / numRows, it % numCols) } ) constructor(vararg rows: Short) : this(rows.fold("") { a, b -> a + b }) constructor(vararg rows: String) : this(rows.fold("") { a, b -> a + b } .toCharArray().let { chars -> val values = chars.distinct() assert(values.size == 2) { "Expected two values" } chars.map { it == values[0] } } ) // TODO: Implement Four Russians for speedy boolean matmuls https://arxiv.org/pdf/0811.1714.pdf#page=5 override fun times(that: BooleanMatrix): BooleanMatrix = super.times(that) val isFull by lazy { data.all { it } } companion object { fun grayCode(size: Int): BooleanMatrix = TODO() fun ones(size: Int) = BooleanMatrix(size) { _, _ -> true } fun zeroes(size: Int) = BooleanMatrix(size) { _, _ -> false } fun one(size: Int) = BooleanMatrix(size) { i, j -> i == j } fun random(size: Int) = BooleanMatrix(size) { _, _ -> Random.nextBoolean() } } override fun toString() = data.foldIndexed("") { i, a, b -> a + (if (b) 1 else 0) + " " + if (i > 0 && (i + 1) % numCols == 0) "\n" else "" } } open class IntegerMatrix constructor( override val algebra: MatrixField<Int, Field.of<Int>> = INTEGER_FIELD, override val numRows: Int, override val numCols: Int = numRows, override val data: List<Int>, ) : AbstractMatrix<Int, Field.of<Int>, IntegerMatrix>(algebra, numRows, numCols, data) { constructor(elements: List<Int>) : this( algebra = INTEGER_FIELD, numRows = sqrt(elements.size.toDouble()).toInt(), data = elements ) constructor(numRows: Int, numCols: Int = numRows, f: (Int, Int) -> Int) : this( numRows = numRows, numCols = numCols, data = List(numRows * numCols) { f(it / numRows, it % numCols) } ) constructor(vararg rows: Int) : this(rows.toList()) operator fun minus(that: IntegerMatrix): IntegerMatrix = with(algebra) { this@IntegerMatrix minus that } } open class DoubleMatrix constructor( override val algebra: MatrixField<Double, Field.of<Double>> = DOUBLE_FIELD, override val numRows: Int, override val numCols: Int = numRows, override val data: List<Double>, ) : AbstractMatrix<Double, Field.of<Double>, DoubleMatrix>(algebra, numRows, numCols, data) { constructor(elements: List<Double>) : this( algebra = DOUBLE_FIELD, numRows = sqrt(elements.size.toDouble()).toInt(), data = elements ) constructor(numRows: Int, numCols: Int = numRows, f: (Int, Int) -> Double) : this( numRows = numRows, numCols = numCols, data = List(numRows * numCols) { f(it / numRows, it % numCols) } ) constructor(vararg rows: Double) : this(rows.toList()) operator fun minus(that: DoubleMatrix): DoubleMatrix = with(algebra) { this@DoubleMatrix minus that } } fun DMatrix.toBMat() = BooleanMatrix(numRows, numCols) { i, j -> get(i, j) > 0.5 } fun BMatrixRMaj.toBMat() = BooleanMatrix(numRows, numCols) { i, j -> get(i, j) } operator fun BooleanMatrix.times(mat: SpsMat): SpsMat = toEJMLSparse() * mat operator fun BooleanMatrix.plus(mat: SpsMat): SpsMat = toEJMLSparse() * mat operator fun SpsMat.minus(mat: BooleanMatrix): SpsMat = this - mat.toEJMLSparse() fun DoubleMatrix.toBMat() = BooleanMatrix(numRows, numCols) { i, j -> get(i, j) > 0.5 } operator fun BooleanMatrix.times(mat: DoubleMatrix): DoubleMatrix = toDoubleMatrix() * mat operator fun BooleanMatrix.plus(mat: DoubleMatrix): DoubleMatrix = toDoubleMatrix() + mat operator fun DoubleMatrix.minus(mat: BooleanMatrix): DoubleMatrix = this - mat.toDoubleMatrix() fun DoubleMatrix.toEJMLSparse() = SpsMat(numRows, numCols, numRows).also { for ((i, j) in (0 until numRows) * (0 until numCols)) if(get(i, j) != 0.0) it[i, j] = get(i, j) } fun BooleanMatrix.toDoubleMatrix() = DoubleMatrix(numRows, numCols) { i, j -> if (get(i, j)) 1.0 else 0.0 } fun BooleanMatrix.toEJMLSparse() = SpsMat(numRows, numCols, numRows).also { for ((i, j) in (0 until numRows) * (0 until numCols)) if (this[i, j]) it[i, j] = 1.0 } // TODO: Naperian functors // https://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/aplicative.pdf // "The main idea is that a rank-n array is essentially a data structure of type // D₁(D₂(...(Dₙ a))), where each Dᵢ is a dimension : a container type, categorically // a functor; one might think in the first instance of lists." // Alternatively: a length-2ⁿ array which can be "parsed" into a certain shape? // See: http://conal.net/talks/can-tensor-programming-be-liberated.pdf interface SparseTensor<T/*Should be a named tuple or dataclass of some kind*/> { // TODO: Precompute specific [Borel] subsets of T's attributes that we expect to be queried at runtime // e.g. (n-1)-D slices and 1D fibers // https://mathoverflow.net/questions/393427/generalization-of-sinkhorn-s-theorem-to-stochastic-tensors // private val marginals: MutableMap<List<T>, Int> = mutableMapOf() val map: MutableMap<T, Int> operator fun get(t: T) = map.getOrElse(t) { 0 } // TODO: Support mutability but also map-reduce-ability/merge-ability for parallelism // operator fun plus(other: SparseTensor<T>) = SparseTensor(map = this.map + other.map) // operator fun MutableMap<T, Int>.plus(map: MutableMap<T, Int>): MutableMap<T, Int> = // HashMap(this).apply { map.forEach { (k, v) -> merge(k, v, Int::plus) } } operator fun set(index: T, i: Int) { map[index] = i } fun count(selector: (T) -> Boolean) = map.entries.sumOf { if(selector(it.key)) it.value else 0 } }
0
null
0
0
4b6aadf379ec40fe0c7d5de0ee25fa64520e31b3
12,091
kaliningraph
Apache License 2.0
uilib/src/main/java/dev/entao/kan/grid/GridPage.kt
yangentao
227,030,009
false
null
package dev.entao.kan.grid import android.content.Context import android.view.View import android.widget.AdapterView import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import dev.entao.kan.appbase.Task import dev.entao.kan.creator.relative import dev.entao.kan.creator.swipeRefresh import dev.entao.kan.creator.textView import dev.entao.kan.ext.* import dev.entao.kan.list.AnyAdapter import dev.entao.kan.page.TitlePage /** * Created by <EMAIL> on 2016-08-24. */ abstract class GridPage : TitlePage() { var anyAdapter: AnyAdapter = AnyAdapter() lateinit var gridView: LineGridView lateinit var gridParent: RelativeLayout private set lateinit var refreshLayout: SwipeRefreshLayout private set lateinit var emptyView: TextView private set var emptyText = "没有内容" var loadingText = "加载中..." override fun onDestroyView() { super.onDestroyView() } override fun onCreateContent(context: Context, contentView: LinearLayout) { gridView = LineGridView(context) gridView.numColumns = 2 gridView.horizontalSpacing = 0 gridView.verticalSpacing = 0 anyAdapter.onBindView = { v, p -> onBindItemView(v, anyAdapter.getItem(p)) } anyAdapter.onNewView = this::onNewItemView anyAdapter.onRequestItems = this::onRequestItems anyAdapter.onItemsRefreshed = this::onItemsRefreshed gridView.adapter = anyAdapter gridView.onItemClickListener = AdapterView.OnItemClickListener { _, _, pos, _ -> onItemClick(anyAdapter.getItem(pos)) } gridParent = contentView.relative(LParam.FillW.HeightFlex) { refreshLayout = swipeRefresh(RParam.Fill) { isEnabled = false setOnRefreshListener { onPullRefresh() } setColorSchemeResources( android.R.color.holo_green_dark, android.R.color.holo_blue_dark, android.R.color.holo_orange_dark, android.R.color.holo_red_dark ) addView(gridView, MParam.Fill) } emptyView = textView(RParam.Fill) { textS = emptyText gravityCenter().textSizeB().gone() } gridView.emptyView = emptyView } } protected open fun onItemsRefreshed() { setRefreshing(false) } fun enablePullRefresh(enable: Boolean = true) { refreshLayout.isEnabled = enable } fun setRefreshing(refresh: Boolean) { Task.mainThread { refreshLayout.isRefreshing = refresh if (refresh) { emptyView.text = loadingText } else { emptyView.text = emptyText } } } open fun onPullRefresh() { requestItems() } open fun setItems(items: List<Any>) { anyAdapter.setItems(items) } open fun onItemClick(item: Any) { } abstract fun onNewItemView(context: Context, position: Int): View abstract fun onBindItemView(view: View, item: Any) fun requestItems() { anyAdapter.requestItems() if (refreshLayout.isEnabled) { setRefreshing(true) } } open fun onRequestItems(): List<Any> { return emptyList() } }
0
Kotlin
0
0
6fe708427ab0b717a0f18c1d9a926dff69a7aa9c
3,516
ui
MIT License
data/src/main/java/com/m3u/data/repository/programme/ProgrammeRepositoryImpl.kt
oxyroid
592,741,804
false
{"Kotlin": 1102944}
package com.m3u.data.repository.programme import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.m3u.core.architecture.dispatcher.Dispatcher import com.m3u.core.architecture.dispatcher.M3uDispatchers.IO import com.m3u.core.architecture.logger.Logger import com.m3u.core.architecture.logger.Profiles import com.m3u.core.architecture.logger.execute import com.m3u.core.architecture.logger.install import com.m3u.core.architecture.logger.post import com.m3u.core.util.basic.letIf import com.m3u.data.api.OkhttpClient import com.m3u.data.database.dao.ChannelDao import com.m3u.data.database.dao.PlaylistDao import com.m3u.data.database.dao.ProgrammeDao import com.m3u.data.database.model.Programme import com.m3u.data.database.model.ProgrammeRange import com.m3u.data.database.model.epgUrlsOrXtreamXmlUrl import com.m3u.data.parser.epg.EpgParser import com.m3u.data.parser.epg.EpgProgramme import com.m3u.data.parser.epg.toProgramme import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.filterNot import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.supervisorScope import kotlinx.datetime.Clock import okhttp3.OkHttpClient import okhttp3.Request import java.util.zip.GZIPInputStream import javax.inject.Inject import kotlin.time.Duration.Companion.days internal class ProgrammeRepositoryImpl @Inject constructor( private val playlistDao: PlaylistDao, private val channelDao: ChannelDao, private val programmeDao: ProgrammeDao, private val epgParser: EpgParser, @OkhttpClient(true) private val okHttpClient: OkHttpClient, @Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher, delegate: Logger ) : ProgrammeRepository { private val logger = delegate.install(Profiles.REPOS_PROGRAMME) override val refreshingEpgUrls = MutableStateFlow<List<String>>(emptyList()) override fun pagingProgrammes( playlistUrl: String, relationId: String ): Flow<PagingData<Programme>> = playlistDao .observeByUrl(playlistUrl) .map { playlist -> playlist?.epgUrlsOrXtreamXmlUrl() ?: emptyList() } .map { epgUrls -> findValidEpgUrl(epgUrls, relationId, defaultProgrammeRange) } .flatMapLatest { epgUrl -> Pager(PagingConfig(15)) { programmeDao.pagingProgrammes(epgUrl, relationId) }.flow } override fun observeProgrammeRange( playlistUrl: String, relationId: String ): Flow<ProgrammeRange> = playlistDao.observeByUrl(playlistUrl) .map { playlist -> playlist?.epgUrlsOrXtreamXmlUrl() ?: emptyList() } .map { epgUrls -> findValidEpgUrl(epgUrls, relationId, defaultProgrammeRange) } .flatMapLatest { epgUrl -> epgUrl ?: return@flatMapLatest flowOf() programmeDao .observeProgrammeRange(epgUrl, relationId) .filterNot { (start, end) -> start == 0L || end == 0L } } override fun observeProgrammeRange(playlistUrl: String): Flow<ProgrammeRange> = playlistDao.observeByUrl(playlistUrl) .map { playlist -> playlist?.epgUrlsOrXtreamXmlUrl() ?: emptyList() } .flatMapLatest { epgUrls -> programmeDao.observeProgrammeRange(epgUrls) } private val defaultProgrammeRange: ProgrammeRange get() = with(Clock.System.now()) { ProgrammeRange( this.minus(1.days).toEpochMilliseconds(), this.plus(1.days).toEpochMilliseconds() ) } override fun checkOrRefreshProgrammesOrThrow( vararg playlistUrls: String, ignoreCache: Boolean ): Flow<Int> = channelFlow { val epgUrls = playlistUrls.flatMap { playlistUrl -> val playlist = playlistDao.get(playlistUrl) ?: return@flatMap emptyList() playlist.epgUrlsOrXtreamXmlUrl() } .toSet() .toList() val producer = checkOrRefreshProgrammesOrThrowImpl( epgUrls = epgUrls, ignoreCache = ignoreCache ) var count = 0 producer.collect { programme -> programmeDao.insertOrReplace(programme) send(++count) } } override suspend fun getById(id: Int): Programme? = logger.execute { programmeDao.getById(id) } override suspend fun getProgrammeCurrently(channelId: Int): Programme? { val channel = channelDao.get(channelId) ?: return null val relationId = channel.relationId ?: return null val playlist = playlistDao.get(channel.playlistUrl) ?: return null val epgUrls = playlist.epgUrlsOrXtreamXmlUrl() if (epgUrls.isEmpty()) return null val time = Clock.System.now().toEpochMilliseconds() return programmeDao.getCurrentByEpgUrlsAndRelationId( epgUrls = epgUrls, relationId = relationId, time = time ) } private fun checkOrRefreshProgrammesOrThrowImpl( epgUrls: List<String>, ignoreCache: Boolean ): Flow<Programme> = channelFlow { val now = Clock.System.now().toEpochMilliseconds() // we call it job -s because we think deferred -s is sick. val jobs = epgUrls.map { epgUrl -> async { if (epgUrl in refreshingEpgUrls.value) run { logger.post { "skipped! epgUrl is refreshing. [$epgUrl]" } return@async } supervisorScope { try { refreshingEpgUrls.value += epgUrl val cacheMaxEnd = programmeDao.getMaxEndByEpgUrl(epgUrl) if (!ignoreCache && cacheMaxEnd != null && cacheMaxEnd > now) run { logger.post { "skipped! exist validate programmes. [$epgUrl]" } return@supervisorScope } programmeDao.cleanByEpgUrl(epgUrl) downloadProgrammes(epgUrl) .map { it.toProgramme(epgUrl) } .collect { send(it) } } finally { refreshingEpgUrls.value -= epgUrl } } } } jobs.awaitAll() } private fun downloadProgrammes(epgUrl: String): Flow<EpgProgramme> = channelFlow { val request = Request.Builder() .url(epgUrl) .build() val response = okHttpClient.newCall(request).execute() val url = response.request.url val contentType = response.header("Content-Type").orEmpty() val isGzip = "gzip" in contentType || // soft rule, cover the situation which with wrong MIME_TYPE(text, octect etc.) url.pathSegments.lastOrNull()?.endsWith(".gz") == true response .body ?.byteStream() ?.letIf(isGzip) { GZIPInputStream(it).buffered() } ?.use { input -> epgParser .readProgrammes(input) .collect { send(it) } } } .flowOn(ioDispatcher) /** * Attempts to find the first valid EPG URL from a list of URLs. * * This function iterates over the provided list of EPG URLs and checks * if each URL is valid by querying from the database. The validity check * uses the `relationId` and the start and end times from the `ProgrammeRange`. * The first valid EPG URL found is returned. If no valid URLs are found, * the function returns null. * * @param epgUrls A list of EPG URLs to check. * @param relationId A unique identifier representing the relation for the EPG. * @param range A `ProgrammeRange` object containing the start and end times to validate against. * @return The first valid EPG URL, or null if none are valid. */ private suspend fun findValidEpgUrl( epgUrls: List<String>, relationId: String, range: ProgrammeRange ): String? = epgUrls.firstOrNull { epgUrl -> programmeDao.checkEpgUrlIsValid(epgUrl, relationId, range.start, range.end) } }
34
Kotlin
33
375
ca92e3487c8e22b73b50197baa2d652185cb4f2e
8,594
M3UAndroid
Apache License 2.0
common/src/main/java/cn/thriic/common/utils/HttpUtils.kt
thriic
649,615,369
false
null
package com.thryan.secondclass.core.utils import com.thryan.secondclass.core.result.HttpResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import okhttp3.FormBody import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import org.json.JSONObject import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException class Requests(val url: String, val factory: Factory) { suspend inline fun <reified T> get(block: Request.() -> Unit): HttpResult<T> { val request = Request().apply { block() } request.builder.url((url + request.api).also(::println)) request.builder.get() val client = OkHttpClient() val response: Response = client.newCall(request.builder.build()).awaitResponse() return factory.convert(response.awaitString().also(::println)) } @JvmName("getString") suspend fun get(block: Request.() -> Unit): HttpResult<String> { return this.get<String>(block) } suspend inline fun <reified T> post(block: Request.() -> Unit): HttpResult<T> { val request = Request().apply { block() } request.builder.url(url + request.api) if (request.requestBody == null) { throw Exception("无参数") } request.builder.post(request.requestBody!!) val client = OkHttpClient() val response = client.newCall(request.builder.build()).awaitResponse() return factory.convert(response.awaitString().also(::println)) } @JvmName("postString") suspend fun post(block: Request.() -> Unit): HttpResult<String> { return this.post<String>(block) } inner class Request { val builder = okhttp3.Request.Builder() private var params: String = "" private var path: String = "" val api: String get() = path + params var requestBody: RequestBody? = null fun path(path: String) { this.path = path } fun params(block: Params.() -> Unit) { params = "?" + Params().apply { block() }.map.entries.joinToString(separator = "&") { "${it.key}=${it.value}" } } fun headers(block: Headers.() -> Unit) { val headers = Headers().apply { block() }.map.toMap() for ((k, v) in headers) { println("add $k $v") builder.addHeader(k, v) } } fun json(block: JSON.() -> Unit) { val jsonObject = JSON().apply { block() }.jsonObject requestBody = jsonObject.toString().encodeToByteArray() .toRequestBody( "application/json;charset=UTF-8".toMediaTypeOrNull(), 0 ) } fun form(block: Form.() -> Unit) { requestBody = Form().apply { block() }.formBody.build() } } } suspend fun okhttp3.Call.awaitResponse(): Response { return suspendCancellableCoroutine { it.invokeOnCancellation { cancel() } enqueue(object : okhttp3.Callback { override fun onFailure(call: okhttp3.Call, e: IOException) { it.resumeWithException(e) } override fun onResponse(call: okhttp3.Call, response: Response) { it.resume(response) } }) } } suspend fun Response.awaitString(): String { val res = this return withContext(Dispatchers.IO) { res.body?.string() ?: "" } } class Form { val formBody = FormBody.Builder() infix fun String.to(value: String) { println("form $this $value") formBody.add(this, value) } } class Params { val map = mutableMapOf<String, String>() infix fun String.to(value: String) { map[this] = value } } class Headers { val map = mutableMapOf<String, String>() infix fun String.to(value: String) { map[this] = value } fun cookie(block: Cookies.() -> Unit) { map["Cookie"] = Cookies().apply { block() }.map.entries.joinToString(separator = "; ") { "${it.key}=${it.value}" } } } class Cookies { val map = mutableMapOf<String, String>() infix fun String.to(value: String) { map[this] = value } } class JSON { val jsonObject = JSONObject() infix fun String.to(value: String) { println("json $this $value") jsonObject.put(this, value) } }
0
null
7
36
2ba4a75a385ebd0bcfb2dd3858969c16beeae94f
4,813
SecondClass
MIT License
composeApp/src/commonMain/kotlin/features/workoutPlanDetail/WorkoutDetailScreenViewModel.kt
anwar-pasaribu
798,728,457
false
{"Kotlin": 370338, "Swift": 585}
package features.workoutPlanDetail import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import domain.model.gym.ExerciseProgress import domain.model.gym.WorkoutPlan import domain.repository.IGymRepository import domain.usecase.GetExerciseListByWorkoutPlanUseCase import domain.usecase.GetWorkoutPlanByIdUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class WorkoutDetailScreenViewModel( private val repository: IGymRepository, private val getExerciseListByWorkoutPlanUseCase: GetExerciseListByWorkoutPlanUseCase, private val getWorkoutPlanByIdUseCase: GetWorkoutPlanByIdUseCase ): ViewModel() { private val _exerciseListStateFlow = MutableStateFlow(emptyList<ExerciseProgress>()) val exerciseListStateFlow: StateFlow<List<ExerciseProgress>> = _exerciseListStateFlow.asStateFlow() private val _workoutPlanStateFlow = MutableStateFlow<WorkoutPlan?>(null) val workoutPlanStateFlow: StateFlow<WorkoutPlan?> = _workoutPlanStateFlow.asStateFlow() fun loadWorkoutPlan(workoutPlanId: Long) { viewModelScope.launch { getExerciseListByWorkoutPlanUseCase(workoutPlanId).collect { exerciseList -> _exerciseListStateFlow.emit(exerciseList.map { exercise -> repository.getWorkoutPlanExerciseProgress( workoutPlanId = workoutPlanId, exerciseId = exercise.id ) }) } } } fun loadWorkoutPlanById(workoutPlanId: Long) { viewModelScope.launch { _workoutPlanStateFlow.value = getWorkoutPlanByIdUseCase(workoutPlanId) } } fun deleteExercise(workoutPlanId: Long, workoutPlanExerciseId: Long) { viewModelScope.launch { repository.deleteWorkoutPlanExerciseByWorkoutPlanIdAndExerciseId( workoutPlanId = workoutPlanId, exerciseId = workoutPlanExerciseId ) } } }
0
Kotlin
0
0
f2878e0f953fd2003d0c412d6de344a4932c886d
2,102
Tabiat
MIT License
roboquant/src/main/kotlin/org/roboquant/brokers/Account.kt
neurallayer
406,929,056
false
{"JavaScript": 3008147, "Kotlin": 1412145, "CSS": 1977}
/* * Copyright 2020-2023 Neural Layer * * 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 org.roboquant.brokers import org.roboquant.common.* import org.roboquant.orders.OrderState import org.roboquant.orders.OrderStatus import org.roboquant.orders.summary import java.time.Instant import java.time.temporal.ChronoUnit /** * An account represents a brokerage trading account and is unified across all broker implementations. * This is an immutable class, and it holds the following state: * * - buying power * - base currency * - [cash] balances in the account * - [positions] with its assets * - past [trades] * - [openOrders] and [closedOrders] state * * Some convenience methods convert a multi-currency Wallet to a single-currency Amount. * For this to work, you'll * need to have the appropriate exchange rates defined at [Config.exchangeRates]. * * @property baseCurrency the base currency of the account * @property lastUpdate time that the account was last updated * @property cash cash balances * @property trades List of all executed trades * @property openOrders List of [OrderState] of all open orders * @property closedOrders List of [OrderState] of all closed orders * @property positions List of all open [Position], with maximum one entry per asset * @property buyingPower amount of buying power available for trading * @constructor Create a new Account */ class Account( val baseCurrency: Currency, val lastUpdate: Instant, val cash: Wallet, val trades: List<Trade>, val openOrders: List<OrderState>, val closedOrders: List<OrderState>, val positions: List<Position>, val buyingPower: Amount ) { init { require(buyingPower.currency == baseCurrency) { "Buying power $buyingPower needs to be expressed in the baseCurrency $baseCurrency" } } /** * Cash balances converted to a single amount denoted in the [baseCurrency] of the account. If you want to know * how much cash is available for trading, please use [buyingPower] instead. */ val cashAmount: Amount get() = convert(cash) /** * [equity] converted to a single amount denoted in the [baseCurrency] of the account */ val equityAmount: Amount get() = convert(equity) /** * Total equity hold in the account. Equity is defined as sum of [cash] balances and the [positions] market value */ val equity: Wallet get() = cash + positions.marketValue /** * Unique set of assets hold in the open [positions] */ val assets: Set<Asset> get() = positions.map { it.asset }.toSet() /** * Get the associated trades for the provided [orders]. If no orders are provided all [closedOrders] linked to this * account instance are used. */ fun getOrderTrades(orders: Collection<OrderState> = this.closedOrders): Map<OrderState, List<Trade>> = orders.associateWith { order -> trades.filter { it.orderId == order.orderId } }.toMap() /** * Convert an [amount] to the account [baseCurrency] using last update of the account as a timestamp */ fun convert(amount: Amount, time: Instant = lastUpdate): Amount = amount.convert(baseCurrency, time) /** * Convert a [wallet] to the account [baseCurrency] using last update of the account as a timestamp */ fun convert(wallet: Wallet, time: Instant = lastUpdate): Amount = wallet.convert(baseCurrency, time) /** * Returns a summary that contains the high-level account information, the available cash balances and * the open positions. Optionally the summary can convert wallets to a [singleCurrency], default is not. */ fun summary(singleCurrency: Boolean = false): Summary { fun c(w: Wallet): Any { if (w.isEmpty()) return Amount(baseCurrency, 0.0) return if (singleCurrency) convert(w) else w } val s = Summary("account") val p = Summary("position summary") val t = Summary("trade summary") val o = Summary("order summary") s.add("last update", lastUpdate.truncatedTo(ChronoUnit.SECONDS)) s.add("base currency", baseCurrency.displayName) s.add("cash", c(cash)) s.add("buying power", buyingPower) s.add("equity", c(equity)) s.add(p) p.add("open", positions.size) p.add("long", positions.long.size) p.add("short", positions.short.size) p.add("total value", c(positions.marketValue)) p.add("long value", c(positions.long.marketValue)) p.add("short value", c(positions.short.marketValue)) p.add("unrealized p&l", c(positions.unrealizedPNL)) s.add(t) t.add("total", trades.size) t.add("realized p&l", c(trades.realizedPNL)) t.add("fee", trades.sumOf { it.fee }) t.add("first", trades.firstOrNull()?.time ?: "") t.add("last", trades.lastOrNull()?.time ?: "") t.add("winners", trades.count { it.pnl > 0 }) t.add("losers", trades.count { it.pnl < 0 }) s.add(o) o.add("open", openOrders.size) o.add("closed", closedOrders.size) o.add("completed", closedOrders.filter { it.status == OrderStatus.COMPLETED }.size) o.add("cancelled", closedOrders.filter { it.status == OrderStatus.CANCELLED }.size) o.add("expired", closedOrders.filter { it.status == OrderStatus.EXPIRED }.size) o.add("rejected", closedOrders.filter { it.status == OrderStatus.REJECTED }.size) return s } /** * Provide a full summary of the account that contains all cash, orders, trades and open positions. During back * testing this can become a long list of items, so look at [summary] for a shorter summary. */ fun fullSummary(singleCurrency: Boolean = false): Summary { val s = summary(singleCurrency) s.add(cash.summary()) s.add(positions.summary()) s.add(openOrders.summary("open orders")) s.add(closedOrders.summary("closed orders")) s.add(trades.summary()) return s } }
9
JavaScript
42
316
769f1aade1e8e95817591866faad4561f7768071
6,646
roboquant
Apache License 2.0