repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ysahnpark/claroforma
server/claroforma-backend/src/test/kotlin/com/claroaprende/repository/UserEsRepositoryIT.kt
1
949
package com.claroaprende.repository import com.claroaprende.model.UserAccount import org.assertj.core.api.Assertions import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner /** * Created by Young-Suk on 10/28/2017. */ @RunWith(SpringRunner::class) @SpringBootTest class MapHelperTest { @Autowired lateinit var repo: UserEsRepository @Test fun test_crud() { val userAccount = UserAccount(sid="1", username = "test", password = "xyz", givenName = "John", familyName = "Doe") repo.save(userAccount) val fetched = repo.findOne("1") Assertions.assertThat(fetched).isNotNull() repo.delete("1") val fetched2 = repo.findOne("1") Assertions.assertThat(fetched2).isNull() } }
mit
ba08be03f5740eb275f13015b4851d4e
24
83
0.704953
3.954167
false
true
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/groupslist/GroupsListPresenter.kt
1
5814
package com.mifos.mifosxdroid.online.groupslist import com.mifos.api.datamanager.DataManagerGroups import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.base.BasePresenter import com.mifos.objects.client.Page import com.mifos.objects.group.Group import rx.Subscriber import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import java.util.* import javax.inject.Inject /** * Created by Rajan Maurya on 7/6/16. */ class GroupsListPresenter @Inject constructor(private val mDataManagerGroups: DataManagerGroups) : BasePresenter<GroupsListMvpView?>() { private val mSubscriptions: CompositeSubscription private var mDbGroupList: List<Group> private var mSyncGroupList: List<Group?> private val limit = 100 private var loadmore = false private var mRestApiGroupSyncStatus = false private var mDatabaseGroupSyncStatus = false override fun attachView(mvpView: GroupsListMvpView?) { super.attachView(mvpView) } override fun detachView() { super.detachView() mSubscriptions.unsubscribe() } fun loadGroups(loadmore: Boolean, offset: Int) { this.loadmore = loadmore loadGroups(true, offset, limit) } /** * Showing Groups List in View, If loadmore is true call showLoadMoreGroups(...) and else * call showGroupsList(...). */ fun showClientList(clients: List<Group?>?) { if (loadmore) { mvpView!!.showLoadMoreGroups(clients) } else { mvpView!!.showGroups(clients) } } /** * This Method will called, when Parent (Fragment or Activity) will be true. * If Parent Fragment is true then there is no need to fetch ClientList, Just show the Parent * (Fragment or Activity)'s Groups in View * * @param groups List<Group></Group>> */ fun showParentClients(groups: List<Group?>) { mvpView!!.unregisterSwipeAndScrollListener() if (groups.size == 0) { mvpView!!.showEmptyGroups(R.string.group) } else { mRestApiGroupSyncStatus = true mSyncGroupList = groups setAlreadyClientSyncStatus() } } /** * Setting GroupSync Status True when mRestApiGroupSyncStatus && mDatabaseGroupSyncStatus * are true. */ fun setAlreadyClientSyncStatus() { if (mRestApiGroupSyncStatus && mDatabaseGroupSyncStatus) { showClientList(checkGroupAlreadySyncedOrNot(mSyncGroupList)) } } fun loadGroups(paged: Boolean, offset: Int, limit: Int) { checkViewAttached() mvpView!!.showProgressbar(true) mSubscriptions.add(mDataManagerGroups.getGroups(paged, offset, limit) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<Page<Group?>?>() { override fun onCompleted() {} override fun onError(e: Throwable) { mvpView!!.showProgressbar(false) if (loadmore) { mvpView!!.showMessage(R.string.failed_to_fetch_groups) } else { mvpView!!.showFetchingError() } } override fun onNext(groupPage: Page<Group?>?) { mSyncGroupList = groupPage!!.pageItems if (mSyncGroupList.size == 0 && !loadmore) { mvpView!!.showEmptyGroups(R.string.group) mvpView!!.unregisterSwipeAndScrollListener() } else if (mSyncGroupList.size == 0 && loadmore) { mvpView!!.showMessage(R.string.no_more_groups_available) } else { mRestApiGroupSyncStatus = true setAlreadyClientSyncStatus() } mvpView!!.showProgressbar(false) } })) } fun loadDatabaseGroups() { checkViewAttached() mSubscriptions.add(mDataManagerGroups.databaseGroups .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<Page<Group?>?>() { override fun onCompleted() {} override fun onError(e: Throwable) { mvpView!!.showMessage(R.string.failed_to_load_db_groups) } override fun onNext(groupPage: Page<Group?>?) { mDatabaseGroupSyncStatus = true mDbGroupList = groupPage!!.pageItems as List<Group> setAlreadyClientSyncStatus() } }) ) } /** * This Method Filtering the Groups Loaded from Server, is already sync or not. If yes the * put the client.setSync(true) and view will show to user that group already synced * * @param groups * @return List<Client> </Client> */ fun checkGroupAlreadySyncedOrNot(groups: List<Group?>): List<Group?> { if (mDbGroupList.size != 0) { for (dbGroup in mDbGroupList) { for (syncGroup in groups) { if (dbGroup.id.toInt() == syncGroup!!.id.toInt()) { syncGroup.isSync = true break } } } } return groups } init { mSubscriptions = CompositeSubscription() mDbGroupList = ArrayList() mSyncGroupList = ArrayList() } }
mpl-2.0
aa7114e31d304ddfa09d776e22844f76
35.572327
136
0.572239
5.113456
false
false
false
false
RyotaMurohoshi/KotLinq
src/test/kotlin/com/muhron/kotlinq/CountTest.kt
1
504
package com.muhron.kotlinq import org.junit.Assert import org.junit.Test class CountTest { @Test fun test0() { val result = sequenceOf(1, 2, 3).count { it % 2 == 0 } Assert.assertEquals(result, 1) } @Test fun test1() { val result = sequenceOf(1, 2, 3).count { it > 5 } Assert.assertEquals(result, 0) } @Test fun test2() { val result = emptySequence<Int>().count { it % 2 == 0 } Assert.assertEquals(result, 0) } }
mit
3efc1a105d9596c16208d25c4f7210f4
17.666667
63
0.55754
3.5
false
true
false
false
msebire/intellij-community
java/debugger/memory-agent/src/com/intellij/debugger/memory/agent/extractor/AgentExtractor.kt
1
1283
// Copyright 2000-2019 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.debugger.memory.agent.extractor import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import org.apache.commons.io.FileUtils import java.io.File import java.io.FileNotFoundException class AgentExtractor { private val platform: PlatformType = let { if (SystemInfo.isLinux) return@let PlatformType.LINUX if (SystemInfo.isMac) return@let PlatformType.MACOS return@let if (SystemInfo.is32Bit) PlatformType.WINDOWS32 else PlatformType.WINDOWS64 } fun extract(): File { val file = FileUtil.createTempFile("${platform.prefix}memory_agent", platform.suffix, true) val agentFileName = "${platform.prefix}memory_agent${platform.suffix}" val inputStream = AgentExtractor::class.java.classLoader.getResourceAsStream("bin/$agentFileName") if (inputStream == null) throw FileNotFoundException(agentFileName) FileUtils.copyToFile(inputStream, file) return file } private enum class PlatformType(val prefix: String, val suffix: String) { WINDOWS32("", "32.dll"), WINDOWS64("", ".dll"), LINUX("lib", ".so"), MACOS("lib", ".dylib") } }
apache-2.0
ec4187536fa0917c04e22924f4ac7549
39.09375
140
0.745908
4.125402
false
false
false
false
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/home/bundles/appcoins/FeaturedAppcBundleAdapter.kt
1
1587
package cm.aptoide.pt.home.bundles.appcoins import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import cm.aptoide.pt.R import cm.aptoide.pt.home.bundles.apps.AppInBundleViewHolder import cm.aptoide.pt.home.bundles.base.HomeBundle import cm.aptoide.pt.home.bundles.base.HomeEvent import cm.aptoide.pt.view.app.AppViewHolder import cm.aptoide.pt.view.app.Application import rx.subjects.PublishSubject import java.text.DecimalFormat class FeaturedAppcBundleAdapter(var apps: List<Application>, val oneDecimalFormatter: DecimalFormat, val appClickedEvents: PublishSubject<HomeEvent>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var homeBundle: HomeBundle? = null private var bundlePosition: Int = -1 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return AppInBundleViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.bonus_appc_home_item, parent, false), appClickedEvents, oneDecimalFormatter) } override fun getItemCount(): Int { return apps.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder as AppViewHolder).setApp(apps[position], homeBundle, bundlePosition) } fun update(apps: List<Application>) { this.apps = apps notifyDataSetChanged() } fun updateBundle(homeBundle: HomeBundle, position: Int) { this.homeBundle = homeBundle this.bundlePosition = position } }
gpl-3.0
151ac082418460c9fc5d21e8b49193a7
33.521739
94
0.749842
4.420613
false
false
false
false
Yubyf/QuoteLock
app/src/main/java/com/crossbowffs/quotelock/modules/wikiquote/WikiquoteQuoteModule.kt
1
2060
package com.crossbowffs.quotelock.modules.wikiquote import android.content.ComponentName import android.content.Context import com.crossbowffs.quotelock.R import com.crossbowffs.quotelock.api.QuoteData import com.crossbowffs.quotelock.api.QuoteModule import com.crossbowffs.quotelock.api.QuoteModule.Companion.CHARACTER_TYPE_CJK import com.crossbowffs.quotelock.utils.Xlog import com.crossbowffs.quotelock.utils.className import com.crossbowffs.quotelock.utils.downloadUrl import org.jsoup.Jsoup import java.io.IOException import java.util.regex.Pattern class WikiquoteQuoteModule : QuoteModule { companion object { private val TAG = className<WikiquoteQuoteModule>() } override fun getDisplayName(context: Context): String { return context.getString(R.string.module_wikiquote_name) } override fun getConfigActivity(context: Context): ComponentName? { return null } override fun getMinimumRefreshInterval(context: Context): Int { return 86400 } override fun requiresInternetConnectivity(context: Context): Boolean { return true } @Suppress("BlockingMethodInNonBlockingContext") @Throws(IOException::class) override suspend fun getQuote(context: Context): QuoteData? { val html = "https://zh.m.wikiquote.org/zh-cn/Wikiquote:%E9%A6%96%E9%A1%B5".downloadUrl() val document = Jsoup.parse(html) val quoteAllText = document.select("#mp-everyday-quote").text() Xlog.d(TAG, "Downloaded text: %s", quoteAllText) val quoteMatcher = Pattern.compile("(.*?)\\s*[\\u2500\\u2014\\u002D]{2}\\s*(.*?)").matcher(quoteAllText) if (!quoteMatcher.matches()) { Xlog.e(TAG, "Failed to parse quote") return null } val quoteText = quoteMatcher.group(1) ?: "" val quoteAuthor = quoteMatcher.group(2) ?: "" return QuoteData(quoteText = quoteText, quoteSource = "", quoteAuthor = quoteAuthor) } override val characterType: Int get() = CHARACTER_TYPE_CJK }
mit
787ae47f085f3034b26413768031d473
34.534483
97
0.702913
4.103586
false
false
false
false
MFlisar/Lumberjack
library/src/main/java/com/michaelflisar/lumberjack/core/DefaultFormatter.kt
1
1473
package com.michaelflisar.lumberjack.core import com.michaelflisar.lumberjack.data.StackData import com.michaelflisar.lumberjack.interfaces.IFormatter import timber.log.BaseTree import timber.log.ConsoleTree open class DefaultFormatter : IFormatter { override fun formatLine(tree: BaseTree, prefix: String, message: String) : String { return if (tree is ConsoleTree) { // tag is logged anyways inside the console, so we do NOT add it to the message! message } else { "$prefix: $message" } } override fun formatLogPrefix(lumberjackTag: String?, stackData: StackData) : String { return if (lumberjackTag != null) { "[<$lumberjackTag> ${getStackTag(stackData)}]" } else { "[${getStackTag(stackData)}]" } } protected open fun getStackTag(stackData: StackData): String { val simpleClassName = formatClassName(stackData.className) var tag = "$simpleClassName:${stackData.element?.lineNumber} ${stackData.element?.methodName}" stackData.element2?.let { val simpleClassName2 = formatClassName(stackData.className2) val extra = simpleClassName2.replace(simpleClassName, "") tag += " ($extra:${it.lineNumber})" } return tag } protected open fun formatClassName(className: String) : String { return className.substring(className.lastIndexOf('.') + 1) } }
apache-2.0
55cbde330196210b2aa4ba69c53bd538
34.95122
102
0.653089
4.319648
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/util/PrefUtils.kt
1
5822
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.util import android.content.Context import android.preference.PreferenceManager import co.timetableapp.model.Timetable import org.threeten.bp.LocalTime object PrefUtils { const val PREF_CURRENT_TIMETABLE = "pref_current_timetable" @JvmStatic fun getCurrentTimetable(context: Context): Timetable? { val sp = PreferenceManager.getDefaultSharedPreferences(context) val timetableId = sp.getInt(PREF_CURRENT_TIMETABLE, -1) return if (timetableId == -1) { null } else { Timetable.create(context, timetableId) } } @JvmStatic fun setCurrentTimetable(context: Context, timetable: Timetable) { val sp = PreferenceManager.getDefaultSharedPreferences(context) sp.edit().putInt(PREF_CURRENT_TIMETABLE, timetable.id).apply() } private const val PREF_SHOW_WEEK_ROTATIONS_WITH_NUMBERS = "pref_show_week_rotations_with_numbers" @JvmStatic fun isWeekRotationShownWithNumbers(context: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getBoolean(PREF_SHOW_WEEK_ROTATIONS_WITH_NUMBERS, false) } @JvmStatic fun setWeekRotationShownWithNumbers(context: Context, displayWithNumbers: Boolean) { val sp = PreferenceManager.getDefaultSharedPreferences(context) sp.edit().putBoolean(PREF_SHOW_WEEK_ROTATIONS_WITH_NUMBERS, displayWithNumbers).apply() } const val PREF_DEFAULT_LESSON_DURATION = "pref_default_lesson_duration" @JvmStatic fun getDefaultLessonDuration(context: Context): Int { val sp = PreferenceManager.getDefaultSharedPreferences(context) val strDuration = sp.getString(PREF_DEFAULT_LESSON_DURATION, "60") return strDuration.toInt() } const val PREF_ENABLE_ASSIGNMENT_NOTIFICATIONS = "pref_enable_assignment_notifications" @JvmStatic fun getAssignmentNotificationsEnabled(context: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getBoolean(PREF_ENABLE_ASSIGNMENT_NOTIFICATIONS, true) } const val PREF_ASSIGNMENT_NOTIFICATION_TIME = "pref_assignment_notification_time" @JvmStatic fun getAssignmentNotificationTime(context: Context): LocalTime { val sp = PreferenceManager.getDefaultSharedPreferences(context) val strTime = sp.getString(PREF_ASSIGNMENT_NOTIFICATION_TIME, "17:00") return LocalTime.parse(strTime) } @JvmStatic fun setAssignmentNotificationTime(context: Context, time: LocalTime) { val sp = PreferenceManager.getDefaultSharedPreferences(context) sp.edit().putString(PREF_ASSIGNMENT_NOTIFICATION_TIME, time.toString()).apply() NotificationUtils.setAssignmentAlarms(context, time) } const val PREF_ENABLE_CLASS_NOTIFICATIONS = "pref_enable_class_notifications" @JvmStatic fun getClassNotificationsEnabled(context: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getBoolean(PREF_ENABLE_CLASS_NOTIFICATIONS, true) } const val PREF_CLASS_NOTIFICATION_TIME = "pref_class_notification_time" @JvmStatic fun getClassNotificationTime(context: Context): Int { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getString(PREF_CLASS_NOTIFICATION_TIME, "5").toInt() } const val PREF_ENABLE_EXAM_NOTIFICATIONS = "pref_enable_exam_notifications" @JvmStatic fun getExamNotificationsEnabled(context: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getBoolean(PREF_ENABLE_EXAM_NOTIFICATIONS, true) } const val PREF_EXAM_NOTIFICATION_TIME = "pref_exam_notification_time" @JvmStatic fun getExamNotificationTime(context: Context): Int { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getString(PREF_EXAM_NOTIFICATION_TIME, "30").toInt() } const val PREF_ENABLE_EVENT_NOTIFICATIONS = "pref_enable_event_notifications" @JvmStatic fun getEventNotificationsEnabled(context: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getBoolean(PREF_ENABLE_EVENT_NOTIFICATIONS, true) } const val PREF_EVENT_NOTIFICATION_TIME = "pref_event_notification_time" @JvmStatic fun getEventNotificationTime(context: Context): Int { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getString(PREF_EVENT_NOTIFICATION_TIME, "30").toInt() } private const val PREF_AGENDA_SHOW_COMPLETED = "pref_agenda_show_completed" @JvmStatic fun showCompletedAgendaItems(context: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(context) return sp.getBoolean(PREF_AGENDA_SHOW_COMPLETED, true) } @JvmStatic fun setShowCompletedAgendaItems(context: Context, showCompleted: Boolean) { val sp = PreferenceManager.getDefaultSharedPreferences(context) sp.edit().putBoolean(PREF_AGENDA_SHOW_COMPLETED, showCompleted).apply() } }
apache-2.0
13c51f0235c18418ec93e3e0f65297f1
35.161491
101
0.7281
4.631663
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/order/StripOrderMetaData.kt
2
1873
package org.wordpress.android.fluxc.network.rest.wpcom.wc.order import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.reflect.TypeToken import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId import org.wordpress.android.fluxc.model.WCMetaData import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderMappingConst.isDisplayableAttribute import org.wordpress.android.fluxc.persistence.entity.OrderMetaDataEntity import javax.inject.Inject class StripOrderMetaData @Inject internal constructor(private val gson: Gson) { private val htmlRegex by lazy { Regex("<[^>]+>") } private val jsonRegex by lazy { Regex("""^.*(?:\{.*\}|\[.*\]).*$""") } private val type = object : TypeToken<List<WCMetaData>>() {}.type operator fun invoke(orderDto: OrderDto, localSiteId: LocalId): List<OrderMetaDataEntity> { if (orderDto.id == null) { return emptyList() } return parseMetaDataJSON(orderDto.meta_data) ?.asSequence() ?.filter { it.isDisplayableAttribute } ?.map { it.asOrderMetaDataEntity(orderDto.id, localSiteId) } ?.filter { it.value.isNotEmpty() && it.value.matches(jsonRegex).not() } ?.toList() ?: emptyList() } private fun parseMetaDataJSON(metadata: JsonElement?): List<WCMetaData>? { return metadata?.let { gson.runCatching { fromJson<List<WCMetaData>?>(metadata, type) }.getOrNull() } } private fun WCMetaData.asOrderMetaDataEntity(orderId: Long, localSiteId: LocalId) = OrderMetaDataEntity( id = id, localSiteId = localSiteId, orderId = orderId, key = key.orEmpty(), value = value.toString().replace(htmlRegex, "") ) }
gpl-2.0
47bafeed4e0fed17aea2f2e043be1d05
34.339623
103
0.642819
4.386417
false
false
false
false
shadowfox-ninja/ShadowUtils
shadow-android/src/main/java/tech/shadowfox/shadow/android/view/widgets/CircleIndicatorView.kt
1
2436
package tech.shadowfox.shadow.android.view.widgets import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.support.annotation.ColorInt import android.util.AttributeSet import android.view.View import tech.shadowfox.shadow.core.utils.ResettableLazy import tech.shadowfox.shadow.core.utils.ResettableLazyManager /** * Copyright 2017 Camaron Crowe * * 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 CircleIndicatorView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0): View(context, attrs, defStyleAttr) { private val sizeManager = ResettableLazyManager() private val bounds: RectF by ResettableLazy(sizeManager) { calculateBounds() } var indicatorColor = Color.GREEN set(@ColorInt value) { if (field == value) return field = value fillPaint.color = field invalidate() } private val fillPaint = Paint().apply { isAntiAlias = true color = indicatorColor } private fun calculateBounds(): RectF { val availableWidth = width - paddingLeft - paddingRight val availableHeight = height - paddingTop - paddingBottom val sideLength = Math.min(availableWidth, availableHeight) val left = paddingLeft + (availableWidth - sideLength) / 2f val top = paddingTop + (availableHeight - sideLength) / 2f return RectF(left, top, left + sideLength, top + sideLength) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) sizeManager.reset() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawCircle(bounds.width() / 2f, bounds.height()/2f, bounds.width() / 2f, fillPaint) } }
apache-2.0
3602788e7da42b6f4f148b8bccd7eb6c
33.814286
159
0.713465
4.511111
false
false
false
false
androidDaniel/treasure
gankotlin/src/main/java/com/ad/gan/widget/YmViewPagerTabLayout.kt
1
941
package com.ad.gan.widget import android.support.design.widget.TabLayout import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager /** * Created by yumodev on 17/6/13. */ class YmViewPagerTabLayout { private val LOG_TAG : String = "YmViewPageTabLayout" var mCount = 0; var mViewPager : ViewPager? = null var mTabLayout : TabLayout? = null var mViewPagerAdapter : FragmentPagerAdapter? = null var mFragmentList : ArrayList<Fragment>? = null var mTitleList : ArrayList<String>? = null fun setupUI(viewPager : ViewPager, tabLayout : TabLayout, adapter : FragmentPagerAdapter){ mViewPager = viewPager mViewPager!!.offscreenPageLimit = mCount mViewPager!!.adapter = adapter mTabLayout = tabLayout mTabLayout!!.setupWithViewPager(mViewPager) } }
gpl-2.0
e5b1ee7630511eb47629e161087ee452
30.4
94
0.729012
4.438679
false
false
false
false
cout970/Statistics
src/main/kotlin/com/cout970/statistics/data/ItemIdentifier.kt
1
1143
package com.cout970.statistics.data import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound class ItemIdentifier( val stack: ItemStack ) { companion object{ fun deserializeNBT(nbt: NBTTagCompound): ItemIdentifier { return ItemStack.loadItemStackFromNBT(nbt).identifier } } fun serializeNBT(): NBTTagCompound { val nbt = NBTTagCompound() stack.writeToNBT(nbt) return nbt } override fun toString(): String { return "ItemIdentifier(stack=$stack)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ItemIdentifier) return false if (stack.item != other.stack.item) return false if (stack.metadata != other.stack.metadata) return false if (stack.tagCompound != other.stack.tagCompound) return false return true } override fun hashCode(): Int { return ((stack.tagCompound?.hashCode() ?: 0) * 31 + stack.item.hashCode()) * 31 + stack.metadata } } val ItemStack.identifier: ItemIdentifier get() = ItemIdentifier(this)
gpl-3.0
e067652cf749db3dfa4443e3d255ba18
26.238095
104
0.652668
4.517787
false
false
false
false
jeffersonvenancio/BarzingaNow
android/app/src/main/java/com/barzinga/viewmodel/ProductViewModel.kt
1
631
package com.barzinga.viewmodel import com.barzinga.model.Product import io.reactivex.Observable import io.reactivex.subjects.PublishSubject /** * Created by diego.santos on 05/10/17. */ class ProductViewModel(val product: Product){ private val clicks = PublishSubject.create<Unit>() fun getDescription() = product.description?.trim() fun getPrice() = String.format("%.2f", product.price) fun getQuantity() = product.quantity.toString() fun getQuantityOrdered() = product.quantityOrdered.toString() fun onClick() { clicks.onNext(Unit) } fun clicks(): Observable<Unit> = clicks.hide() }
apache-2.0
7113cc17185ed8729407626fcef95248
26.478261
65
0.714739
4.019108
false
false
false
false
brayvqz/ejercicios_kotlin
calcular_salario/main.kt
1
718
package calcular_salario import java.util.* /** * Created by brayan on 15/04/2017. */ fun main(args: Array<String>) { var scan = Scanner(System.`in`) println("Digite la tarifa por hora : ") var tarifa = scan.nextDouble() println("Digite el numero de horas trabajadas : ") var horas = scan.nextDouble() println("El sueldo a pagar es : ${calcular(horas,tarifa)}") } fun calcular(horas:Double=0.0,tarifa:Double=0.0) : Double{ var horasComunes : Double = horas var horasExtras : Double = 0.0 if (horas > 40){ horasExtras = horas - 40; horasComunes = horas - horasExtras } return (horasComunes * tarifa) + (horasExtras * (tarifa + (tarifa * 0.5))) }
mit
5bd7604a4df6af838b49bae6faa2c365
21.4375
78
0.632312
2.906883
false
false
false
false
yotkaz/thimman
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/model/Challenge.kt
1
1166
package yotkaz.thimman.backend.model import com.fasterxml.jackson.annotation.JsonIgnore import yotkaz.thimman.backend.app.JPA_EMPTY_CONSTRUCTOR import java.util.* import javax.persistence.* @Entity data class Challenge( @Id @GeneratedValue(strategy = GenerationType.TABLE) var id: Long? = null, var name: String, var description: String, @Enumerated(EnumType.STRING) var type: ChallengeType, var reference: String? = null, @JsonIgnore @ManyToMany(fetch = FetchType.EAGER) var materials: List<Material> = ArrayList(), @JsonIgnore @ManyToMany(fetch = FetchType.LAZY) var attempts: List<Attempt> = ArrayList(), @JsonIgnore @OneToMany(fetch = FetchType.LAZY) var jobOfferChallenges: List<JobOfferChallenge> = ArrayList(), @JsonIgnore @OneToMany(fetch = FetchType.LAZY) var lessonChallenges: List<LessonChallenge> = ArrayList() ) { @Deprecated(JPA_EMPTY_CONSTRUCTOR) constructor() : this( name = "", description = "", type = ChallengeType.TASK ) }
apache-2.0
1c0532105e0dbcc839ec64e063b68f5f
22.32
70
0.628645
4.501931
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/InfoActivity.kt
1
13564
package org.videolan.vlc.gui import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.os.Bundle import android.os.Parcelable import android.view.Gravity import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.databinding.DataBindingUtil import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.* import org.videolan.libvlc.FactoryManager import org.videolan.libvlc.interfaces.IMedia import org.videolan.libvlc.interfaces.IMediaFactory import org.videolan.libvlc.util.Extensions import org.videolan.medialibrary.Tools import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.medialibrary.interfaces.media.Artist import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.resources.TAG_ITEM import org.videolan.resources.VLCInstance import org.videolan.tools.readableFileSize import org.videolan.vlc.R import org.videolan.vlc.databinding.InfoActivityBinding import org.videolan.vlc.gui.browser.PathAdapter import org.videolan.vlc.gui.browser.PathAdapterListener import org.videolan.vlc.gui.helpers.AudioUtil import org.videolan.vlc.gui.helpers.FloatingActionButtonBehavior import org.videolan.vlc.gui.helpers.MedialibraryUtils import org.videolan.vlc.gui.video.MediaInfoAdapter import org.videolan.vlc.gui.view.VLCDividerItemDecoration import org.videolan.vlc.media.MediaUtils import org.videolan.vlc.util.* import org.videolan.vlc.viewmodels.browser.IPathOperationDelegate import org.videolan.vlc.viewmodels.browser.PathOperationDelegate import java.io.File import java.util.* private const val TAG = "VLC/InfoActivity" private const val TAG_FAB_VISIBILITY = "FAB" @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class InfoActivity : AudioPlayerContainerActivity(), View.OnClickListener, PathAdapterListener, IPathOperationDelegate by PathOperationDelegate() { private lateinit var item: MediaLibraryItem private lateinit var adapter: MediaInfoAdapter private lateinit var model: InfoModel internal lateinit var binding: InfoActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.info_activity) initAudioPlayerContainerActivity() supportActionBar?.setDisplayHomeAsUpEnabled(true) val item = if (savedInstanceState != null) savedInstanceState.getParcelable<Parcelable>(TAG_ITEM) as MediaLibraryItem? else intent.getParcelableExtra<Parcelable>(TAG_ITEM) as MediaLibraryItem if (item == null) { finish() return } this.item = item if (item.id == 0L) { val libraryItem = Medialibrary.getInstance().getMedia((item as MediaWrapper).uri) if (libraryItem != null) this.item = libraryItem } binding.item = item val fabVisibility = savedInstanceState?.getInt(TAG_FAB_VISIBILITY) ?: -1 model = getModel() binding.fab.setOnClickListener(this) if (item is MediaWrapper) { adapter = MediaInfoAdapter() binding.list.layoutManager = LinearLayoutManager(binding.root.context) binding.list.adapter = adapter if (model.sizeText.value === null) model.checkFile(item) if (model.mediaTracks.value === null) model.parseTracks(this, item) } model.hasSubs.observe(this, Observer { if (it) binding.infoSubtitles.visibility = View.VISIBLE }) model.mediaTracks.observe(this, Observer { adapter.setTracks(it) }) model.sizeText.observe(this, Observer { binding.sizeValueText = it }) model.cover.observe(this, Observer { if (it != null) { binding.cover = BitmapDrawable([email protected], it) lifecycleScope.launch { ViewCompat.setNestedScrollingEnabled(binding.container, true) binding.appbar.setExpanded(true, true) if (fabVisibility != -1) binding.fab.visibility = fabVisibility } } else noCoverFallback() }) if (model.cover.value === null) model.getCover(item.artworkMrl, getScreenWidth()) updateMeta() binding.directoryNotScannedButton.setOnClickListener { val media = item as MediaWrapper val parent = media.uri.toString().substring(0, media.uri.toString().lastIndexOf("/")) MedialibraryUtils.addDir(parent, applicationContext) Snackbar.make(binding.root, getString(R.string.scanned_directory_added, Uri.parse(parent).lastPathSegment), Snackbar.LENGTH_LONG).show() binding.scanned = true } } private fun updateMeta() = lifecycleScope.launchWhenStarted { var length = 0L val tracks = item.tracks val nbTracks = tracks?.size ?: 0 if (nbTracks > 0) for (media in tracks!!) length += media.length if (length > 0) binding.length = Tools.millisToTextLarge(length) if (item is MediaWrapper) { val media = item as MediaWrapper val resolution = generateResolutionClass(media.width, media.height) binding.resolution = resolution } binding.scanned = true when { item.itemType == MediaLibraryItem.TYPE_MEDIA -> { val media = item as MediaWrapper binding.progress = if (media.length == 0L) 0 else (100.toLong() * media.time / length).toInt() binding.sizeTitleText = getString(R.string.file_size) if (isSchemeSupported(media.uri?.scheme)) { binding.ariane.visibility = View.VISIBLE binding.ariane.layoutManager = LinearLayoutManager(this@InfoActivity, LinearLayoutManager.HORIZONTAL, false) binding.ariane.adapter = PathAdapter(this@InfoActivity, media) if (binding.ariane.itemDecorationCount == 0) { binding.ariane.addItemDecoration(VLCDividerItemDecoration(this@InfoActivity, DividerItemDecoration.HORIZONTAL, ContextCompat.getDrawable(this@InfoActivity, R.drawable.ic_divider)!!)) } //scheme is supported => test if the parent is scanned var isScanned = false Medialibrary.getInstance().foldersList.forEach search@{ if (media.uri.toString().startsWith(Uri.parse(it).toString())) { isScanned = true return@search } } binding.scanned = isScanned } else binding.ariane.visibility = View.GONE } item.itemType == MediaLibraryItem.TYPE_ARTIST -> { val albums = (item as Artist).albums val nbAlbums = albums?.size ?: 0 binding.sizeTitleText = getString(R.string.albums) binding.sizeValueText = nbAlbums.toString() binding.sizeIcon.setImageDrawable(ContextCompat.getDrawable(this@InfoActivity, R.drawable.ic_album)) binding.extraTitleText = getString(R.string.tracks) binding.extraValueText = nbTracks.toString() binding.extraIcon.setImageDrawable(ContextCompat.getDrawable(this@InfoActivity, R.drawable.ic_song)) } else -> { binding.sizeTitleText = getString(R.string.tracks) binding.sizeValueText = nbTracks.toString() binding.sizeIcon.setImageDrawable(ContextCompat.getDrawable(this@InfoActivity, R.drawable.ic_song)) } } } override fun backTo(tag: String) { } override fun currentContext() = this override fun showRoot() = false override fun getPathOperationDelegate() = this override fun onPostCreate(savedInstanceState: Bundle?) { fragmentContainer = binding.container super.onPostCreate(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(TAG_ITEM, item) outState.putInt(TAG_FAB_VISIBILITY, binding.fab.visibility) } private fun noCoverFallback() { binding.appbar.setExpanded(false) ViewCompat.setNestedScrollingEnabled(binding.list, false) val lp = binding.fab.layoutParams as CoordinatorLayout.LayoutParams lp.anchorId = binding.container.id lp.anchorGravity = Gravity.BOTTOM or Gravity.END lp.bottomMargin = resources.getDimensionPixelSize(R.dimen.default_margin) lp.behavior = FloatingActionButtonBehavior(this@InfoActivity, null) binding.fab.layoutParams = lp binding.fab.show() } override fun onClick(v: View) { MediaUtils.playTracks(this, item, 0) finish() } override fun onPlayerStateChanged(bottomSheet: View, newState: Int) { val visibility = binding.fab.visibility if (visibility == View.VISIBLE && newState != BottomSheetBehavior.STATE_COLLAPSED && newState != BottomSheetBehavior.STATE_HIDDEN) binding.fab.hide() else if (visibility == View.INVISIBLE && (newState == BottomSheetBehavior.STATE_COLLAPSED || newState == BottomSheetBehavior.STATE_HIDDEN)) binding.fab.show() } } @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class InfoModel : ViewModel() { internal val hasSubs = MutableLiveData<Boolean>() internal val mediaTracks = MutableLiveData<List<IMedia.Track>>() internal val sizeText = MutableLiveData<String>() internal val cover = MutableLiveData<Bitmap>() internal val mMediaFactory = FactoryManager.getFactory(IMediaFactory.factoryId) as IMediaFactory internal fun getCover(mrl: String?, width: Int) = viewModelScope.launch { cover.value = mrl?.let { withContext(Dispatchers.IO) { AudioUtil.fetchCoverBitmap(Uri.decode(it), width) } } } internal fun parseTracks(context: Context, mw: MediaWrapper) = viewModelScope.launch { val media = withContext(Dispatchers.IO) { val libVlc = VLCInstance[context] mMediaFactory.getFromUri(libVlc, mw.uri).apply { parse() } } if (!isActive) return@launch var subs = false val trackCount = media.trackCount val tracks = LinkedList<IMedia.Track>() for (i in 0 until trackCount) { val track = media.getTrack(i) tracks.add(track) subs = subs or (track.type == IMedia.Track.Type.Text) } media.release() hasSubs.value = subs mediaTracks.value = tracks.toList() } internal fun checkFile(mw: MediaWrapper) = viewModelScope.launch { val itemFile = withContext(Dispatchers.IO) { File(Uri.decode(mw.location.substring(5))) } if (!withContext(Dispatchers.IO) { itemFile.exists() } || !isActive) return@launch if (mw.type == MediaWrapper.TYPE_VIDEO) checkSubtitles(itemFile) sizeText.value = itemFile.length().readableFileSize() } private suspend fun checkSubtitles(itemFile: File) = withContext(Dispatchers.IO) { var extension: String var filename: String var videoName = Uri.decode(itemFile.name) val parentPath = Uri.decode(itemFile.parent) videoName = videoName.substring(0, videoName.lastIndexOf('.')) val subFolders = arrayOf("/Subtitles", "/subtitles", "/Subs", "/subs") var files: Array<String>? = itemFile.parentFile.list() var filesLength = files?.size ?: 0 for (subFolderName in subFolders) { val subFolder = File(parentPath + subFolderName) if (!subFolder.exists()) continue val subFiles = subFolder.list() var subFilesLength = 0 var newFiles = arrayOfNulls<String>(0) if (subFiles != null) { subFilesLength = subFiles.size newFiles = arrayOfNulls(filesLength + subFilesLength) System.arraycopy(subFiles, 0, newFiles, 0, subFilesLength) } files?.let { System.arraycopy(it, 0, newFiles, subFilesLength, filesLength) } files = newFiles.filterNotNull().toTypedArray() filesLength = files.size } if (files != null) for (i in 0 until filesLength) { filename = Uri.decode(files[i]) val index = filename.lastIndexOf('.') if (index <= 0) continue extension = filename.substring(index) if (!Extensions.SUBTITLES.contains(extension)) continue if (!isActive) return@withContext if (filename.startsWith(videoName)) { hasSubs.postValue(true) return@withContext } } } }
gpl-2.0
76a56b68d491665a341df1368dc289b1
42.754839
206
0.669788
4.804818
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/structure2/TypeProxy.kt
1
1351
package com.github.pgutkowski.kgraphql.schema.structure2 import com.github.pgutkowski.kgraphql.schema.introspection.TypeKind import com.github.pgutkowski.kgraphql.schema.introspection.__EnumValue import com.github.pgutkowski.kgraphql.schema.introspection.__Field import com.github.pgutkowski.kgraphql.schema.introspection.__InputValue import com.github.pgutkowski.kgraphql.schema.introspection.__Type import kotlin.reflect.KClass open class TypeProxy(var proxied: Type) : Type { override fun isInstance(value: Any?): Boolean = proxied.isInstance(value) override val kClass: KClass<*>? get() = proxied.kClass override val kind: TypeKind get() = proxied.kind override val name: String? get() = proxied.name override val description: String get() = proxied.description override val fields: List<__Field>? get() = proxied.fields override val interfaces: List<__Type>? get() = proxied.interfaces override val possibleTypes: List<__Type>? get() = proxied.possibleTypes override val enumValues: List<__EnumValue>? get() = proxied.enumValues override val inputFields: List<__InputValue>? get() = proxied.inputFields override val ofType: __Type? get() = proxied.ofType override fun get(name: String) = proxied[name] }
mit
ca32c948d715dc9d91fd7c163c3c5bd3
28.391304
77
0.706144
4.169753
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/query/handlers/TurnCardDealtEventHandler.kt
1
1663
package com.flexpoker.table.query.handlers import com.flexpoker.framework.event.EventHandler import com.flexpoker.framework.pushnotifier.PushNotificationPublisher import com.flexpoker.pushnotifications.TableUpdatedPushNotification import com.flexpoker.table.command.events.TurnCardDealtEvent import com.flexpoker.table.query.dto.CardDTO import com.flexpoker.table.query.repository.CardsUsedInHandRepository import com.flexpoker.table.query.repository.TableRepository import org.springframework.stereotype.Component import javax.inject.Inject @Component class TurnCardDealtEventHandler @Inject constructor( private val tableRepository: TableRepository, private val cardsUsedInHandRepository: CardsUsedInHandRepository, private val pushNotificationPublisher: PushNotificationPublisher ) : EventHandler<TurnCardDealtEvent> { override fun handle(event: TurnCardDealtEvent) { handleUpdatingTable(event) handlePushNotifications(event) } private fun handleUpdatingTable(event: TurnCardDealtEvent) { val tableDTO = tableRepository.fetchById(event.aggregateId) val turnCard = cardsUsedInHandRepository.fetchTurnCard(event.handId) val visibleCommonCards = tableDTO.visibleCommonCards!!.plus(CardDTO(turnCard.card.id)) val updatedTable = tableDTO.copy(version = event.version, visibleCommonCards = visibleCommonCards) tableRepository.save(updatedTable) } private fun handlePushNotifications(event: TurnCardDealtEvent) { val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId) pushNotificationPublisher.publish(pushNotification) } }
gpl-2.0
44e2b11b9bc7a7269be27b61d51bc0bb
42.789474
106
0.809381
4.993994
false
false
false
false
hltj/kotlin-web-site-cn
.teamcity/builds/apiReferences/buildTypes/DokkaReferenceTemplate.kt
1
1325
package builds.apiReferences.buildTypes import jetbrains.buildServer.configs.kotlin.FailureAction import jetbrains.buildServer.configs.kotlin.Template import jetbrains.buildServer.configs.kotlin.buildSteps.gradle import jetbrains.buildServer.configs.kotlin.buildSteps.script object DokkaReferenceTemplate : Template({ name = "Dokka Reference Template" artifactRules = "build/dokka/htmlMultiModule/** => pages.zip" steps { script { name = "Drop SNAPSHOT word for deploy" scriptContent = """ #!/bin/bash CURRENT_VERSION="$(sed -E s/^v?//g <<<%release.tag%)" sed -i -E "s/^version=.+(-SNAPSHOT)?/version=${'$'}CURRENT_VERSION/gi" ./gradle.properties """.trimIndent() dockerImage = "debian" } gradle { name = "Build dokka html" tasks = "dokkaHtmlMultiModule" } } requirements { contains("docker.server.osType", "linux") } params { param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true") } dependencies { dependency(PrepareCustomDokkaTemplates) { snapshot { onDependencyFailure = FailureAction.CANCEL onDependencyCancel = FailureAction.CANCEL } artifacts { artifactRules = "+:dokka-templates/** => dokka-templates" } } } })
apache-2.0
4bb33864d81dfb9a73630d31a89f95b1
24.980392
106
0.650566
4.387417
false
true
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/dribbble/data/search/SearchRemoteDataSource.kt
1
2518
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.dribbble.data.search import io.plaidapp.core.data.Result import io.plaidapp.core.dribbble.data.api.model.Shot import io.plaidapp.core.dribbble.data.search.DribbbleSearchService.Companion.PER_PAGE_DEFAULT import io.plaidapp.core.dribbble.data.search.SearchRemoteDataSource.SortOrder.RECENT import io.plaidapp.core.util.safeApiCall import java.io.IOException import javax.inject.Inject /** * Work with our fake Dribbble API to search for shots by query term. */ class SearchRemoteDataSource @Inject constructor(private val service: DribbbleSearchService) { suspend fun search( query: String, page: Int, sortOrder: SortOrder = RECENT, pageSize: Int = PER_PAGE_DEFAULT ) = safeApiCall( call = { requestSearch(query, page, sortOrder, pageSize) }, errorMessage = "Error getting Dribbble data" ) private suspend fun requestSearch( query: String, page: Int, sortOrder: SortOrder = RECENT, pageSize: Int = PER_PAGE_DEFAULT ): Result<List<Shot>> { val response = service.searchDeferred(query, page, sortOrder.sort, pageSize) if (response.isSuccessful) { val body = response.body() if (body != null) { return Result.Success(body) } } return Result.Error( IOException("Error getting Dribbble data ${response.code()} ${response.message()}") ) } enum class SortOrder(val sort: String) { POPULAR(""), RECENT("latest") } companion object { @Volatile private var INSTANCE: SearchRemoteDataSource? = null fun getInstance(service: DribbbleSearchService): SearchRemoteDataSource { return INSTANCE ?: synchronized(this) { INSTANCE ?: SearchRemoteDataSource(service).also { INSTANCE = it } } } } }
apache-2.0
5605477590c27f3e5a39f51daf085ac4
32.573333
95
0.669182
4.472469
false
false
false
false
gameofbombs/kt-postgresql-async
db-async-common/src/main/kotlin/com/github/mauricio/async/db/general/ArrayRowData.kt
2
1558
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.general import com.github.mauricio.async.db.RowData class ArrayRowData(val row: Int, val mapping: Map<String, Int>, val columns: Array<Any?>) : RowData { override fun iterator(): Iterator<Any?> = columns.iterator() val size: Int get() = columns.size /** * * Returns a column value by it's position in the originating query. * * @param columnNumber * @return */ override operator fun get(columnNumber: Int): Any? = columns[columnNumber] /** * * Returns a column value by it's name in the originating query. * * @param columnName * @return */ override operator fun get(columnName: String): Any? = columns[mapping[columnName]!!] /** * * Number of this row in the query results. Counts start at 0. * * @return */ override val rowNumber: Int get() = row }
apache-2.0
00ef2359e8ded4220f31c2ccab8fa3e0
28.358491
101
0.669666
4.105541
false
false
false
false
whoww/SneakPeek
app/src/main/java/de/sneakpeek/data/MovieInfoProductionCompany.kt
1
1020
package de.sneakpeek.data import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class MovieInfoProductionCompany( @Expose @SerializedName("name") var name: String?, @Expose @SerializedName("id") var id: Int = 0) : Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<MovieInfoProductionCompany> = object : Parcelable.Creator<MovieInfoProductionCompany> { override fun createFromParcel(source: Parcel): MovieInfoProductionCompany = MovieInfoProductionCompany(source) override fun newArray(size: Int): Array<MovieInfoProductionCompany?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readString(), source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(name) dest.writeInt(id) } }
mit
7da0278b38b0a4b9cc90a861cbcdf4f8
31.935484
137
0.70098
4.594595
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/Circle.kt
1
1932
package com.soywiz.korge.view import com.soywiz.korge.ui.* import com.soywiz.korim.color.* import com.soywiz.korim.paint.Paint import com.soywiz.korma.geom.shape.* import com.soywiz.korma.geom.vector.* /** * Creates a [Circle] of [radius] and [fill]. * The [autoScaling] determines if the underlying texture will be updated when the hierarchy is scaled. * The [callback] allows to configure the [Circle] instance. */ inline fun Container.circle( radius: Double = 16.0, fill: Paint = Colors.WHITE, stroke: Paint = Colors.WHITE, strokeThickness: Double = 0.0, autoScaling: Boolean = true, callback: @ViewDslMarker Circle.() -> Unit = {} ): Circle = Circle(radius, fill, stroke, strokeThickness, autoScaling).addTo(this, callback) /** * A [Graphics] class that automatically keeps a circle shape with [radius] and [color]. * The [autoScaling] property determines if the underlying texture will be updated when the hierarchy is scaled. */ open class Circle( radius: Double = 16.0, fill: Paint = Colors.WHITE, stroke: Paint = Colors.WHITE, strokeThickness: Double = 0.0, autoScaling: Boolean = true, ) : ShapeView(shape = VectorPath(), fill = fill, stroke = stroke, strokeThickness = strokeThickness, autoScaling = autoScaling) { /** Radius of the circle */ var radius: Double by uiObservable(radius) { updateGraphics() } /** Color of the circle. Internally it uses the [colorMul] property */ var color: RGBA get() = colorMul set(value) { colorMul = value } override val bwidth get() = radius * 2 override val bheight get() = radius * 2 init { this.color = color updateGraphics() } private fun updateGraphics() { hitShape2d = Shape2d.Circle(radius, radius, radius) updateShape { clear() circle([email protected], [email protected], [email protected]) } } }
apache-2.0
9b9137ffb1e9848bdeee4467e8763295
33.5
129
0.67236
3.926829
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/o/katydid/vdom/types/MimeType.kt
1
2070
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.vdom.types /** * Structures a MIME type as a type and subtype with optional parameters. * * @constructor Constructs a MIME type with given [type] and [subtype] and optional [parameters]. */ class MimeType( /** The main type of the MIME type. */ val type: String, /** The secondary type of the MIME type. */ val subtype: String, /** Optional key/value parameters for the MIME type. */ val parameters: Map<String, String> = mapOf() ) { init { require(!type.isEmpty()) { "MIME type cannot be empty." } require(!subtype.isEmpty()) { "MIME subtype cannot be empty." } } //// /** Converts this MIME type to its string equivalent. */ override fun toString(): String { var result = "$type/$subtype" for ((key, value) in parameters) { result += "; $key=$value" } return result } //// companion object { /** * Parses a string [mimeType] into a MIME type. */ fun fromString(mimeType: String): MimeType { val slashSplit = mimeType.split("/") require(slashSplit.size == 2) { "Expected one '/' in MIME type '$mimeType'." } val type = slashSplit[0] require(!type.isEmpty()) { "Type cannot be empty in MIME type '$mimeType'." } val semicolonSplit = slashSplit[1].split(";") val subtype = semicolonSplit[0] require(!subtype.isEmpty()) { "Subtype cannot be empty in MIME type '$mimeType'." } val parameters = mutableMapOf<String, String>() for (i in 1 until semicolonSplit.size) { val equalsSplit = semicolonSplit[i].split("=") require(equalsSplit.size == 2) { "Expected one '=' in MIME type parameter '$mimeType'." } parameters[equalsSplit[0]] = equalsSplit[1] } return MimeType(type, subtype, parameters) } } }
apache-2.0
3763ddc8adc9b30fee4273529ae9e296
22.793103
105
0.569082
4.432548
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/ds/File.kt
1
7589
package org.pixelndice.table.pixelclient.ds import javafx.scene.image.Image import org.apache.logging.log4j.LogManager import java.io.* import java.nio.file.FileSystems import java.nio.file.Files import java.security.MessageDigest import java.util.* import java.util.stream.Collectors /* See TODO for file system schematics */ private val logger = LogManager.getLogger(File::class.java) private const val hashSize: Int = 64 private const val maxFileSize: Long = 1024 * 1024 * 10 private val resourcesPath: java.nio.file.Path = FileSystems.getDefault().getPath("resources") /** * This enum represents an MP3 or a image file enum */ enum class FileCategory{ IMAGE{ override fun fileExtension(): List<String> { return listOf(".BMP", ".GIF", ".JPEG", ".JPG", ".PNG") } }, SOUND{ override fun fileExtension(): List<String> { return listOf(".MP3") } }; abstract fun fileExtension(): List<String> } /** * This class represents an file. * * */ class File { /** * Sets the file name and category * @property name file name */ var name: String = "" set(value){ field = value category = category(value) } /** * Sets the file hash * @property hash file hash */ var hash: String = "" /** * Sets the file category * @property category file category enum */ private var category: FileCategory? = null /** * Gets file system path * @property systemPath system path */ val systemPath: java.nio.file.Path get(){ return resourcesPath.resolve(category.toString()).resolve(hash + name) } /** * Returns the file string representation */ override fun toString(): String { return "$hash - $name - $systemPath" } /** * Checks if two files are equal */ override fun equals(other: Any?): Boolean { if (other == null) return false if (other !is File) return false if (other === this) return true return this.hash == other.hash } /** * hashCode override for hashmaps */ override fun hashCode(): Int { return Objects.hash(this.hash) } /** * Delete the file from system */ fun delete() { this.systemPath.toFile().delete() } /** * Returns an image from file */ fun toImage(): Image { if( category != FileCategory.IMAGE ) logger.fatal("Not a valid image file: $systemPath") return ImageCache.getImage(systemPath) } companion object { /** * Default icon for missing file */ const val banPath = "/icons/open-iconic-master/png/ban-8x.png" /** * Returns an file category given file's extension */ private fun category(source: String): FileCategory?{ val ret: FileCategory? ret = FileCategory.values().find{ fileCategory -> fileCategory.fileExtension().any{source.toUpperCase().endsWith(it)} } return ret } /** * Returns sha256 hash from file contents */ private fun sha256(source: java.nio.file.Path): String { val byteArraySize = 2048 try { val inputStream = FileInputStream(source.toString()) val bytes = ByteArray(byteArraySize) var numBytes: Int val md = MessageDigest.getInstance("SHA-256") numBytes = inputStream.read(bytes) while (numBytes != -1) { md.update(bytes, 0, numBytes) numBytes = inputStream.read(bytes) } inputStream.close() return String.format("%064x", java.math.BigInteger(1, md.digest())) }catch(e: Exception){ logger.fatal("Exception while generating hash. $e") throw Exception("Exception while generating hash. $e") } } /** * Add given file to PixelnDice Library */ fun addFile(source: java.nio.file.Path): File { if( java.nio.file.Files.notExists(source)){ logger.error("File ${source.fileName} does not exist") throw Exception("File ${source.fileName} does not exist") } if( java.nio.file.Files.isDirectory(source)){ logger.error("${source.fileName} is not a file") throw Exception("${source.fileName} is not a file") } if( source.toFile().length() > maxFileSize){ logger.error("File ${source.fileName} is greater than $maxFileSize bytes") throw Exception("File ${source.fileName} is greater than $maxFileSize bytes") } val category = category(source.toString()) if( category == null ){ logger.warn("File format is not supported.File: ${source.fileName}") throw IllegalArgumentException("File format is not supported. File: ${source.fileName}") } val ret = File() ret.name = source.fileName.toString() ret.hash = sha256(source) try { Files.copy(source, ret.systemPath) } catch (e: IOException) { logger.error("Error copying file from $source to ${ret.systemPath}") throw Exception("Error copying file from $source to ${ret.systemPath}") } return ret } /** * List Image files libraty contents */ fun listImages(): List<File> { createResourcesFolder() return Files.walk(resourcesPath.resolve(FileCategory.IMAGE.toString())) .filter { Files.isRegularFile(it) } .map { path -> val fd = File() fd.name = path.fileName.toString().substring(hashSize) fd.hash = path.fileName.toString().substring(0, hashSize) fd } .collect(Collectors.toList()) } /** * Returns image file given hash */ fun getImageByHash(h: String): File? { return listImages().find { it.hash == h } } private fun createResourcesFolder(){ // if directory exists? if (java.nio.file.Files.notExists(resourcesPath)) { try { Files.createDirectories(resourcesPath) } catch (e: IOException) { logger.fatal( "Failed to create base folder: $resourcesPath") throw Exception("storage.FileLib - init. Failed to create base folder: $resourcesPath") } } FileCategory.values().forEach { category -> val tmpPath = resourcesPath.resolve(category.toString()) if(java.nio.file.Files.notExists(tmpPath)){ try { Files.createDirectories(tmpPath) } catch (e: IOException) { logger.fatal( "Failed to create base folder: $tmpPath") throw Exception("storage.FileLib - init. Failed to create base folder: $tmpPath") } } } } } }
bsd-2-clause
1e37fe9d3ce7b71ab8caa6d7d08f9729
25.534965
107
0.535248
4.788013
false
false
false
false
panpf/sketch
sketch-video-ffmpeg/src/androidTest/java/com/github/panpf/sketch/video/ffmpeg/test/utils/BitmapUtils.kt
1
1021
/* * Copyright (C) 2022 panpf <[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 express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.video.ffmpeg.test.utils import android.graphics.Bitmap val Bitmap.cornerA: Int get() = getPixel(0, 0) val Bitmap.cornerB: Int get() = getPixel(width - 1, 0) val Bitmap.cornerC: Int get() = getPixel(width - 1, height - 1) val Bitmap.cornerD: Int get() = getPixel(0, height - 1) fun Bitmap.corners(): List<Int> = listOf(cornerA, cornerB, cornerC, cornerD)
apache-2.0
bfa7939392f40ee4541ae4d0ebdbc780
33.066667
76
0.720862
3.672662
false
false
false
false
werelord/nullpod
nullpodApp/src/main/kotlin/com/cyrix/nullpod/NullpodPlayer.kt
1
8453
/** * NullpodPlayer * * Copyright 2017 Joel Braun * * This file is part of nullPod. * * nullPod is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nullPod is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nullPod. If not, see <http://www.gnu.org/licenses/>. */ package com.cyrix.nullpod import android.content.Context import android.net.Uri import android.os.Handler import android.widget.TextView import com.cyrix.nullpod.data.PodcastTrack import com.cyrix.util.* import com.google.android.exoplayer2.* import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ExtractorMediaSource import com.google.android.exoplayer2.source.TrackGroupArray import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import com.google.android.exoplayer2.trackselection.TrackSelectionArray import com.google.android.exoplayer2.ui.DebugTextViewHelper import com.google.android.exoplayer2.upstream.FileDataSourceFactory import kotlinx.coroutines.experimental.* import kotlinx.coroutines.experimental.android.UI import java.io.File //--------------------------------------------------------------------------- class NullpodPlayer(ctx: Context) { companion object { // slightly less than a second, to deal with actual computations const val DefaultProgressIntervalMs = 990L } private val log = CxLogger <NullpodPlayer>() private var _debugTVHelper : DebugTextViewHelper? = null private val _player: SimpleExoPlayer = ExoPlayerFactory.newSimpleInstance(ctx, DefaultTrackSelector()) /* future: not sure if we need monitor here.. we can record track progress on play/pause/next/jump events; * a UI element that needs to report progress can implement it only when that element is showing. reducing cycles.. * probably minimal tho.. */ private var _progressMonitorJob: Job? = null private var _currentProgress: Long = 0L private var _currentTrack: PodcastTrack? = null private val _playListeners = mutableListOf<PlayerListener>() val isPlaying: Boolean get() { return when (_player.playbackState) { Player.STATE_IDLE, Player.STATE_BUFFERING, Player.STATE_ENDED -> false Player.STATE_READY -> _player.playWhenReady else -> false } } //--------------------------------------------------------------------------- private val eventListener = object : Player.EventListener { override fun onTimelineChanged(timeline: Timeline?, manifest: Any?) { log.function() } override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) { log.function() } override fun onLoadingChanged(isLoading: Boolean) { log.function("isLoading: $isLoading") } override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { log.function("playWhenReady: $playWhenReady, state: $playbackState") when (playbackState) { Player.STATE_IDLE -> log.debug { "exoplayer idle" } Player.STATE_BUFFERING -> log.debug { "exoplayer buffering" } Player.STATE_READY -> { log.debug { "exoplayer ready: pos: ${_player.currentPosition} max: ${_player.duration}" } // todo: here.. need to check shit.. // if (isPlaying == false) { // isPlaying = true _playListeners.asyncForEach { listener -> listener.onPlayStarted() } // } } Player.STATE_ENDED -> { log.debug { "exoplayer ended!" } _player.playWhenReady = false _player.seekTo(0) _progressMonitorJob?.cancel() _progressMonitorJob = null } } } override fun onRepeatModeChanged(repeatMode: Int) { log.function() } override fun onPlayerError(error: ExoPlaybackException?) { log.function(error.toString()) // todo: more here?? } override fun onPositionDiscontinuity() { log.function() } override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) { log.function() } } //--------------------------------------------------------------------------- init { _player.addListener(eventListener) _player.playbackState } //--------------------------------------------------------------------------- fun togglePlayback(track: PodcastTrack) { val currentPlayback = isPlaying // check state, and current track if (_currentTrack != track) { // thank god data classes // new track, start playback _currentTrack = track prepare(Uri.fromFile(File(track.filepath))) _player.playWhenReady = true } else { // same track; doesn't matter what state we're in, just toggle // todo: need to test hammering play button, handle that situation.. actors on the job? _player.playWhenReady = (currentPlayback == false) } } //--------------------------------------------------------------------------- private fun prepare(uri: Uri) { log.function() // todo: make file selection from array, for seamless shit?? or just handle externally individual, since there's really no buffering needed? val mediaSource = ExtractorMediaSource(uri, FileDataSourceFactory(), DefaultExtractorsFactory(), Handler(), ExtractorMediaSource.EventListener { error -> log.error("Exception fired on load:", error) }) _player.prepare(mediaSource) // start the progress monitor _progressMonitorJob = startProgressMonitor() } //--------------------------------------------------------------------------- fun attachDebugTV(tv: TextView) { @Suppress("ConstantConditionIf") if (BuildConfig.internalTest) { _debugTVHelper = DebugTextViewHelper(_player, tv) async(UI) { _debugTVHelper?.start() } } } //--------------------------------------------------------------------------- fun detachDebugTV() { @Suppress("ConstantConditionIf") if (BuildConfig.internalTest) { async(UI) { _debugTVHelper?.stop() _debugTVHelper = null } } } //--------------------------------------------------------------------------- private fun startProgressMonitor() = launch(CommonPool) { log.function() while (isActive) { val progress = _player.currentPosition //log.function("player progress: $progress") // only report progress if it changes.. if (progress != _currentProgress) { _currentProgress = progress _playListeners.asyncForEach { it.onInterval(progress) } } // todo: need to modify delay interval based on playback speed.. delay(DefaultProgressIntervalMs) } } //--------------------------------------------------------------------------- // warning; any adding of listener must be paired with a removal of listener // future: use weakrefext and discard removeListener? fun addListener(listener: PlayerListener) { _playListeners.add(listener) } //--------------------------------------------------------------------------- fun removeListener(listener: PlayerListener) { _playListeners.remove(listener) } //--------------------------------------------------------------------------- interface PlayerListener { fun onPlayStarted() {} fun onPlayPaused() {} fun onTrackFinished() {} fun onInterval(progressMs: Long) {} } }
gpl-3.0
c12ca99c14f2f028a5fdf2954c921e3f
39.835749
148
0.574707
5.333123
false
false
false
false
edsilfer/star-wars-wiki
app/src/main/java/br/com/edsilfer/android/starwarswiki/infrastructure/retrofit/GCSAPIEndPoint.kt
1
856
package br.com.edsilfer.android.searchimages.communication import br.com.edsilfer.android.starwarswiki.model.dictionary.SearchResult import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Query /** * Created by ferna on 2/20/2017. */ interface GCSAPIEndPoint { companion object { private const val QUERY_ARG_QUERY = "q" private const val QUERY_ARG_APPLICATION_ID = "cx" private const val QUERY_ARG_FILE_TYPE = "fileType" private const val QUERY_ARG_API_ID = "key" } @GET("v1") fun searchImage( @Query(QUERY_ARG_QUERY) query: String, @Query(encoded = true, value = QUERY_ARG_APPLICATION_ID) applicationKey: String, @Query(QUERY_ARG_FILE_TYPE) fileType: String, @Query(QUERY_ARG_API_ID) key: String ): Observable<SearchResult> }
apache-2.0
e7cd2a5a280bef3e274cbf1666573115
30.740741
92
0.679907
3.705628
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/typing/assist/RsSmartEnterProcessor.kt
3
2115
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.typing.assist import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.LBRACE import org.rust.lang.core.psi.RsElementTypes.RBRACE import org.rust.lang.core.psi.ext.ancestors /** * Smart enter implementation for the Rust language. */ class RsSmartEnterProcessor : SmartEnterProcessorWithFixers() { init { addFixers( MethodCallFixer(), SemicolonFixer(), CommaFixer(), FunctionOrStructFixer() ) addEnterProcessors( AfterSemicolonEnterProcessor(), AfterFunctionOrStructEnterProcessor(), PlainEnterProcessor() ) } override fun getStatementAtCaret(editor: Editor, psiFile: PsiFile): PsiElement? { val atCaret = super.getStatementAtCaret(editor, psiFile) ?: return null if (atCaret is PsiWhiteSpace) return null loop@ for (each in atCaret.ancestors) { val elementType = each.node.elementType when { elementType == LBRACE || elementType == RBRACE -> continue@loop each is RsMatchArm || each.parent is RsBlock || each.parent is RsFunction || each.parent is RsStructItem -> return each } } return null } override fun doNotStepInto(element: PsiElement): Boolean { return true } override fun processDefaultEnter(project: Project, editor: Editor, file: PsiFile) { plainEnter(editor) } private class PlainEnterProcessor : FixEnterProcessor() { override fun doEnter(atCaret: PsiElement, file: PsiFile, editor: Editor, modified: Boolean): Boolean { plainEnter(editor) return true } } }
mit
4388e25ae854dd188f22fbae79b1ace1
30.567164
110
0.661939
4.785068
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/TextFieldInteractionsTest.kt
3
13484
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.geometry.Offset import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class TextFieldInteractionsTest { @get:Rule val rule = createComposeRule() val testTag = "textField" @Test fun coreTextField_interaction_pressed() { val state = mutableStateOf(TextFieldValue("")) val interactionSource = MutableInteractionSource() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.testTag(testTag), value = state.value, onValueChange = { state.value = it }, interactionSource = interactionSource ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performTouchInput { down(center) } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<PressInteraction.Press>()).hasSize(1) } rule.onNodeWithTag(testTag) .performTouchInput { up() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<PressInteraction.Press>()).hasSize(1) assertThat(interactions.filterIsInstance<PressInteraction.Release>()).hasSize(1) } } @Test fun coreTextField_interaction_pressed_removedWhenCancelled() { val state = mutableStateOf(TextFieldValue("")) val interactionSource = MutableInteractionSource() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.testTag(testTag), value = state.value, onValueChange = { state.value = it }, interactionSource = interactionSource ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performTouchInput { down(center) } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<PressInteraction.Press>()).hasSize(1) } rule.onNodeWithTag(testTag) .performTouchInput { cancel() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<PressInteraction.Press>()).hasSize(1) assertThat(interactions.filterIsInstance<PressInteraction.Cancel>()).hasSize(1) } } @Test fun coreTextField_interaction_focused() { val state = mutableStateOf(TextFieldValue("")) val interactionSource = MutableInteractionSource() val focusRequester = FocusRequester() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.testTag(testTag), value = state.value, onValueChange = { state.value = it }, interactionSource = interactionSource ) Box( modifier = Modifier.requiredSize(10.dp).focusRequester(focusRequester).focusable(), ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performClick() rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<FocusInteraction.Focus>()).hasSize(1) } rule.runOnIdle { // request focus on the box so TextField will lose it focusRequester.requestFocus() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<FocusInteraction.Focus>()).hasSize(1) assertThat(interactions.filterIsInstance<FocusInteraction.Unfocus>()).hasSize(1) } } @Test fun coreTextField_interaction_horizontally_dragged() { val state = mutableStateOf(TextFieldValue("test ".repeat(100))) val interactionSource = MutableInteractionSource() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.testTag(testTag), value = state.value, singleLine = true, onValueChange = { state.value = it }, interactionSource = interactionSource ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performTouchInput { down(center) moveBy(Offset(x = 100f, y = 0f)) } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) } rule.onNodeWithTag(testTag) .performTouchInput { up() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) assertThat(interactions.filterIsInstance<DragInteraction.Stop>()).hasSize(1) } } @Test fun coreTextField_interaction_dragged_horizontally_cancelled() { val state = mutableStateOf(TextFieldValue("test ".repeat(100))) val interactionSource = MutableInteractionSource() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.testTag(testTag), value = state.value, singleLine = true, onValueChange = { state.value = it }, interactionSource = interactionSource ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performTouchInput { down(center) moveBy(Offset(x = 100f, y = 0f)) } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) } rule.onNodeWithTag(testTag) .performTouchInput { cancel() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) assertThat(interactions.filterIsInstance<DragInteraction.Cancel>()).hasSize(1) } } @Test fun coreTextField_interaction_vertically_dragged() { val state = mutableStateOf(TextFieldValue("test\n".repeat(10))) val interactionSource = MutableInteractionSource() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.requiredSize(50.dp).testTag(testTag), value = state.value, maxLines = 3, onValueChange = { state.value = it }, interactionSource = interactionSource ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performTouchInput { down(center) moveBy(Offset(x = 0f, y = 150f)) } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) } rule.onNodeWithTag(testTag) .performTouchInput { up() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) assertThat(interactions.filterIsInstance<DragInteraction.Stop>()).hasSize(1) } } @Test fun coreTextField_interaction_dragged_vertically_cancelled() { val state = mutableStateOf(TextFieldValue("test\n".repeat(10))) val interactionSource = MutableInteractionSource() var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() BasicTextField( modifier = Modifier.requiredSize(50.dp).testTag(testTag), value = state.value, maxLines = 3, onValueChange = { state.value = it }, interactionSource = interactionSource ) } val interactions = mutableListOf<Interaction>() scope!!.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(testTag) .performTouchInput { down(center) moveBy(Offset(x = 0f, y = 150f)) } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) } rule.onNodeWithTag(testTag) .performTouchInput { cancel() } rule.runOnIdle { // Not asserting total size as we have other interactions here too assertThat(interactions.filterIsInstance<DragInteraction.Start>()).hasSize(1) assertThat(interactions.filterIsInstance<DragInteraction.Cancel>()).hasSize(1) } } }
apache-2.0
d1474786e564731a6a867b993c0c00bc
36.248619
99
0.622219
5.601994
false
true
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/util/MyCheckBox.kt
1
3267
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.util import android.app.Activity import android.view.View import android.widget.CheckBox import android.widget.CompoundButton import androidx.annotation.IdRes /** * @author [email protected] */ object MyCheckBox { private val EMPTY_ON_CHECKED_CHANGE_LISTENER: CompoundButton.OnCheckedChangeListener = CompoundButton.OnCheckedChangeListener { _, _ -> } fun isChecked(activity: Activity, @IdRes checkBoxViewId: Int, defaultValue: Boolean): Boolean { val view = activity.findViewById<View?>(checkBoxViewId) return if (view == null || !CheckBox::class.java.isAssignableFrom(view.javaClass)) { defaultValue } else (view as CheckBox).isChecked } fun setEnabled(activity: Activity, @IdRes viewId: Int, checked: Boolean): Boolean { return set(activity, viewId, checked, true) } fun setEnabled(parentView: View?, @IdRes viewId: Int, checked: Boolean): Boolean { parentView ?: return false return set(parentView, viewId, checked, EMPTY_ON_CHECKED_CHANGE_LISTENER) } operator fun set(activity: Activity, @IdRes viewId: Int, checked: Boolean, enabled: Boolean): Boolean { return set(activity, viewId, checked, if (enabled) EMPTY_ON_CHECKED_CHANGE_LISTENER else null) } operator fun set(activity: Activity, @IdRes viewId: Int, checked: Boolean, onCheckedChangeListener: CompoundButton.OnCheckedChangeListener?): Boolean { return set(activity.findViewById(viewId), checked, onCheckedChangeListener) } operator fun set(parentView: View, @IdRes viewId: Int, checked: Boolean, onCheckedChangeListener: CompoundButton.OnCheckedChangeListener?): Boolean { return set(parentView.findViewById(viewId), checked, onCheckedChangeListener) } /** * @return true if succeeded */ operator fun set(checkBoxIn: View?, checked: Boolean, onCheckedChangeListener: CompoundButton.OnCheckedChangeListener?): Boolean { val success = checkBoxIn != null && CheckBox::class.java.isAssignableFrom(checkBoxIn.javaClass) if (success) { val checkBox = checkBoxIn as CheckBox checkBox.setOnCheckedChangeListener(null) checkBox.isChecked = checked checkBox.isEnabled = onCheckedChangeListener != null if (onCheckedChangeListener != null && onCheckedChangeListener !== EMPTY_ON_CHECKED_CHANGE_LISTENER) { checkBox.setOnCheckedChangeListener(onCheckedChangeListener) } } return success } }
apache-2.0
952d88ec4bd5ed1d2816e0b71813b0ea
40.884615
114
0.695745
4.868852
false
false
false
false
wealthfront/magellan
magellan-library/src/main/java/com/wealthfront/magellan/lifecycle/LifecycleRegistry.kt
1
4757
package com.wealthfront.magellan.lifecycle import android.content.Context import com.wealthfront.magellan.lifecycle.LifecycleLimit.CREATED import com.wealthfront.magellan.lifecycle.LifecycleLimit.DESTROYED import com.wealthfront.magellan.lifecycle.LifecycleLimit.NO_LIMIT import com.wealthfront.magellan.lifecycle.LifecycleLimit.SHOWN public class LifecycleRegistry : LifecycleAware, LifecycleOwner { internal val listeners: Set<LifecycleAware> get() = listenersToMaxStates.keys private var listenersToMaxStates: Map<LifecycleAware, LifecycleLimit> = linkedMapOf() override val children: List<LifecycleAware> get() = listeners.toList() override var currentState: LifecycleState = LifecycleState.Destroyed private set(newState) { val oldState = field field = newState listenersToMaxStates.forEach { (lifecycleAware, maxState) -> if (oldState.limitBy(maxState).order != newState.limitBy(maxState).order) { lifecycleAware.transition( oldState.limitBy(maxState), newState.limitBy(maxState) ) } } } override fun attachToLifecycle(lifecycleAware: LifecycleAware, detachedState: LifecycleState) { attachToLifecycleWithMaxState(lifecycleAware, NO_LIMIT, detachedState) } public fun attachToLifecycleWithMaxState( lifecycleAware: LifecycleAware, maxState: LifecycleLimit = NO_LIMIT, detachedState: LifecycleState = LifecycleState.Destroyed ) { if (listenersToMaxStates.containsKey(lifecycleAware)) { throw IllegalStateException( "Cannot attach a lifecycleAware that is already a child: " + lifecycleAware::class.java.simpleName ) } lifecycleAware.transition(detachedState, currentState.limitBy(maxState)) listenersToMaxStates = listenersToMaxStates + (lifecycleAware to maxState) } override fun removeFromLifecycle( lifecycleAware: LifecycleAware, detachedState: LifecycleState ) { if (!listenersToMaxStates.containsKey(lifecycleAware)) { throw IllegalStateException( "Cannot remove a lifecycleAware that is not a child: " + lifecycleAware::class.java.simpleName ) } val maxState = listenersToMaxStates[lifecycleAware]!! listenersToMaxStates = listenersToMaxStates - lifecycleAware lifecycleAware.transition(currentState.limitBy(maxState), detachedState) } public fun updateMaxState(lifecycleAware: LifecycleAware, maxState: LifecycleLimit) { if (!listenersToMaxStates.containsKey(lifecycleAware)) { throw IllegalArgumentException( "Cannot update the state of a lifecycleAware that is not a child: " + lifecycleAware::class.java.simpleName ) } val oldMaxState = listenersToMaxStates[lifecycleAware]!! if (oldMaxState != maxState) { val needsToTransition = !currentState.isWithinLimit(minOf(maxState, oldMaxState)) if (needsToTransition) { lifecycleAware.transition( currentState.limitBy(oldMaxState), currentState.limitBy(maxState) ) } listenersToMaxStates = listenersToMaxStates + (lifecycleAware to maxState) } } override fun create(context: Context) { currentState = LifecycleState.Created(context.applicationContext) } override fun show(context: Context) { currentState = LifecycleState.Shown(context) } override fun resume(context: Context) { currentState = LifecycleState.Resumed(context) } override fun pause(context: Context) { currentState = LifecycleState.Shown(context) } override fun hide(context: Context) { currentState = LifecycleState.Created(context.applicationContext) } override fun destroy(context: Context) { currentState = LifecycleState.Destroyed } override fun backPressed(): Boolean = onAllActiveListenersUntilTrue { it.backPressed() } private fun onAllActiveListenersUntilTrue(action: (LifecycleAware) -> Boolean): Boolean = listenersToMaxStates .asSequence() .filter { it.value >= SHOWN } .map { it.key } .map(action) .any { it } } public enum class LifecycleLimit(internal val order: Int) { DESTROYED(0), CREATED(1), SHOWN(2), NO_LIMIT(3) } private fun LifecycleState.isWithinLimit(limit: LifecycleLimit): Boolean = order <= limit.order private fun LifecycleState.limitBy(limit: LifecycleLimit): LifecycleState = if (isWithinLimit(limit)) { this } else { limit.getMaxLifecycleState(context!!) } private fun LifecycleLimit.getMaxLifecycleState(context: Context): LifecycleState = when (this) { DESTROYED -> LifecycleState.Destroyed CREATED -> LifecycleState.Created(context) SHOWN -> LifecycleState.Shown(context) NO_LIMIT -> LifecycleState.Resumed(context) }
apache-2.0
87c568ba5d8d4cea54c42c37442dc336
33.471014
103
0.733445
4.622935
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/CoverLayout.kt
2
2765
package ru.fantlab.android.ui.widgets import android.content.Context import androidx.annotation.AttrRes import androidx.annotation.DrawableRes import androidx.annotation.StyleRes import androidx.swiperefreshlayout.widget.CircularProgressDrawable import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.ImageView import androidx.core.content.ContextCompat import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import kotlinx.android.synthetic.main.image_layout.view.* import ru.fantlab.android.R import ru.fantlab.android.provider.glide.GlideApp import ru.fantlab.android.provider.glide.SvgSoftwareLayerSetter class CoverLayout : FrameLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int, @StyleRes defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) private lateinit var progressBar: CircularProgressDrawable override fun onFinishInflate() { super.onFinishInflate() View.inflate(context, R.layout.image_layout, this) if (isInEditMode) return initProgressBar() } private fun initProgressBar() { progressBar = CircularProgressDrawable(context) progressBar.strokeWidth = 5f progressBar.centerRadius = 30f progressBar.start() } fun setUrl(url: String?, @DrawableRes fallbackImage: Int = R.drawable.work) { Glide.with(context) .load(url) .fallback(ContextCompat.getDrawable(context, fallbackImage)) .placeholder(progressBar) .error(ContextCompat.getDrawable(context, fallbackImage)) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .into(image) } fun setUrl(url: String?, defaultImageUrl: String) { GlideApp.with(context) .load(url) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .placeholder(progressBar) .error(GlideApp.with(context) .load(defaultImageUrl) .diskCacheStrategy(DiskCacheStrategy.DATA) .listener(SvgSoftwareLayerSetter()) ) .into(image) } fun setUrlGif(url: String?, @DrawableRes fallbackImage: Int = R.drawable.work) { image.scaleType = ImageView.ScaleType.FIT_START Glide.with(context) .load(url) .fallback(ContextCompat.getDrawable(context, fallbackImage)) .error(ContextCompat.getDrawable(context, fallbackImage)) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .into(image) } fun setDotColor(color: Dot.Color) { dot.apply { this.color = color visibility = View.VISIBLE } } }
gpl-3.0
8520b50bd841aa72ac12891e976df8fe
30.078652
159
0.769982
3.916431
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/module/project/domain/SimpleComponent.kt
3
1370
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.project.domain /** * @author MyCollab Ltd. * @since 1.0 */ class SimpleComponent : Component() { var userLeadAvatarId: String? = null var userLeadFullName: String? = null var createdUserAvatarId: String? = null var createdUserFullName: String? = null var numOpenBugs: Int? = null var numBugs: Int? = null var numOpenTasks: Int? = null var numTasks: Int? = null lateinit var projectName: String lateinit var projectShortName: String enum class Field { numOpenBugs, numBugs, numOpenTasks, NumTasks; fun equalTo(value: Any): Boolean = name == value } }
agpl-3.0
e0eaefb3785e99f5fb33a03c3df107a1
26.38
81
0.702703
4.098802
false
false
false
false
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/a_gettingStarted/6.2 coordinate systems depth.kt
1
8132
package learnOpenGL.a_gettingStarted /** * Created by GBarbieri on 25.04.2017. */ import glm_.func.rad import glm_.glm import glm_.mat4x4.Mat4 import glm_.vec2.Vec2 import glm_.vec3.Vec3 import gln.buffer.glBindBuffer import gln.draw.glDrawArrays import gln.get import gln.glClearColor import gln.glf.semantic import gln.program.usingProgram import gln.texture.glTexImage2D import gln.texture.plus import gln.uniform.glUniform import gln.vertexArray.glBindVertexArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.common.flipY import learnOpenGL.common.readImage import learnOpenGL.common.toBuffer import org.lwjgl.opengl.EXTABGR import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL12.GL_BGR import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.* import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.floatBufferBig import uno.buffer.intBufferBig import uno.buffer.use import uno.glfw.glfw import uno.glsl.Program import uno.glsl.glDeleteProgram import uno.glsl.usingProgram fun main(args: Array<String>) { with(CoordinateSystemsDepth()) { run() end() } } val verticesCube = floatArrayOf( -0.5f, -0.5f, -0.5f, 0f, 0f, +0.5f, -0.5f, -0.5f, 1f, 0f, +0.5f, +0.5f, -0.5f, 1f, 1f, +0.5f, +0.5f, -0.5f, 1f, 1f, -0.5f, +0.5f, -0.5f, 0f, 1f, -0.5f, -0.5f, -0.5f, 0f, 0f, -0.5f, -0.5f, +0.5f, 0f, 0f, +0.5f, -0.5f, +0.5f, 1f, 0f, +0.5f, +0.5f, +0.5f, 1f, 1f, +0.5f, +0.5f, +0.5f, 1f, 1f, -0.5f, +0.5f, +0.5f, 0f, 1f, -0.5f, -0.5f, +0.5f, 0f, 0f, -0.5f, +0.5f, +0.5f, 1f, 0f, -0.5f, +0.5f, -0.5f, 1f, 1f, -0.5f, -0.5f, -0.5f, 0f, 1f, -0.5f, -0.5f, -0.5f, 0f, 1f, -0.5f, -0.5f, +0.5f, 0f, 0f, -0.5f, +0.5f, +0.5f, 1f, 0f, +0.5f, +0.5f, +0.5f, 1f, 0f, +0.5f, +0.5f, -0.5f, 1f, 1f, +0.5f, -0.5f, -0.5f, 0f, 1f, +0.5f, -0.5f, -0.5f, 0f, 1f, +0.5f, -0.5f, +0.5f, 0f, 0f, +0.5f, +0.5f, +0.5f, 1f, 0f, -0.5f, -0.5f, -0.5f, 0f, 1f, +0.5f, -0.5f, -0.5f, 1f, 1f, +0.5f, -0.5f, +0.5f, 1f, 0f, +0.5f, -0.5f, +0.5f, 1f, 0f, -0.5f, -0.5f, +0.5f, 0f, 0f, -0.5f, -0.5f, -0.5f, 0f, 1f, -0.5f, +0.5f, -0.5f, 0f, 1f, +0.5f, +0.5f, -0.5f, 1f, 1f, +0.5f, +0.5f, +0.5f, 1f, 0f, +0.5f, +0.5f, +0.5f, 1f, 0f, -0.5f, +0.5f, +0.5f, 0f, 0f, -0.5f, +0.5f, -0.5f, 0f, 1f) private class CoordinateSystemsDepth { val window = initWindow("Coordinate Systems Depth") val program = ProgramA() val vbo = intBufferBig(1) val vao = intBufferBig(1) enum class Texture { A, B } val textures = intBufferBig<Texture>() val matBuffer = floatBufferBig(16) inner class ProgramA : Program("shaders/a/_6_2", "coordinate-systems.vert", "coordinate-systems.frag") { val model = glGetUniformLocation(name, "model") val view = glGetUniformLocation(name, "view") val proj = glGetUniformLocation(name, "projection") init { usingProgram(name) { "textureA".unitE = Texture.A "textureB".unitE = Texture.B } } } init { // configure global opengl state glEnable(GL_DEPTH_TEST) // set up vertex data (and buffer(s)) and configure vertex attributes glGenVertexArrays(vao) glGenBuffers(vbo) // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, verticesCube, GL_STATIC_DRAW) // position attribute glVertexAttribPointer(semantic.attr.POSITION, Vec3.length, GL_FLOAT, false, Vec3.size + Vec2.size, 0) glEnableVertexAttribArray(semantic.attr.POSITION) // texture coord attribute glVertexAttribPointer(semantic.attr.TEX_COORD, Vec2.length, GL_FLOAT, false, Vec3.size + Vec2.size, Vec3.size) glEnableVertexAttribArray(semantic.attr.TEX_COORD) // load and create a texture glGenTextures(textures) // texture A glBindTexture(GL_TEXTURE_2D, textures[Texture.A]) // set the texture wrapping parameters to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) // load image, create texture and generate mipmaps var image = readImage("textures/container.jpg").flipY() image.toBuffer().use { glTexImage2D(GL_RGB, image.width, image.height, GL_BGR, GL_UNSIGNED_BYTE, it) glGenerateMipmap(GL_TEXTURE_2D) } // texture B glBindTexture(GL_TEXTURE_2D, textures[Texture.B]) // set the texture wrapping parameters to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) // load image, create texture and generate mipmaps image = readImage("textures/awesomeface.png").flipY() image.toBuffer().use { glTexImage2D(GL_TEXTURE_2D, GL_RGB, image.width, image.height, EXTABGR.GL_ABGR_EXT, GL_UNSIGNED_BYTE, it) glGenerateMipmap(GL_TEXTURE_2D) } /* You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. */ //glBindVertexArray() } fun run() { while (window.open) { window.processInput() // render glClearColor(clearColor) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) // also clear the depth buffer now! // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0 + Texture.A) glBindTexture(GL_TEXTURE_2D, textures[Texture.A]) glActiveTexture(GL_TEXTURE0 + Texture.B) glBindTexture(GL_TEXTURE_2D, textures[Texture.B]) usingProgram(program) { // create transformations val model = glm.rotate(Mat4(), glfw.time, 0.5f, 1f, 0f) val view = glm.translate(Mat4(), 0f, 0f, -3f) val projection = glm.perspective(45f.rad, window.aspect, 0.1f, 100f) // pass them to the shaders (3 different ways) glUniformMatrix4fv(program.model, false, model to matBuffer) glUniform(program.view, view) /* note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. Best place is the framebuffer size callback */ projection to program.proj // render container glBindVertexArray(vao) glDrawArrays(GL_TRIANGLES, 36) } window.swapAndPoll() } } fun end() { // optional: de-allocate all resources once they've outlived their purpose: glDeleteProgram(program) glDeleteVertexArrays(vao) glDeleteBuffers(vbo) glDeleteTextures(textures) destroyBuf(vao, vbo, textures, matBuffer) window.end() } }
mit
2a0ddcd52a2696cd0393999b6e658f9d
32.8875
125
0.608583
3.181534
false
false
false
false
inorichi/tachiyomi-extensions
src/en/hentaifox/src/eu/kanade/tachiyomi/extension/en/hentaifox/HentaiFox.kt
1
7942
package eu.kanade.tachiyomi.extension.en.hentaifox import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable @Nsfw class HentaiFox : ParsedHttpSource() { override val name = "HentaiFox" override val baseUrl = "https://hentaifox.com" override val lang = "en" override val supportsLatest = false override val client: OkHttpClient = network.cloudflareClient // Popular override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/pag/$page/", headers) } override fun popularMangaSelector() = "div.thumb" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("h2 a").let { title = it.text() setUrlWithoutDomain(it.attr("href")) } thumbnail_url = element.select("img").first().attr("abs:src") } } override fun popularMangaNextPageSelector() = "li.page-item:last-of-type:not(.disabled)" // Latest override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used") override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used") override fun latestUpdatesSelector() = throw UnsupportedOperationException("Not used") override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used") override fun latestUpdatesNextPageSelector() = throw UnsupportedOperationException("Not used") // Search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return if (query.isNotEmpty()) { GET("$baseUrl/search/?q=$query&page=$page", headers) } else { var url = "$baseUrl/tag/" filters.forEach { filter -> when (filter) { is GenreFilter -> { url += "${filter.toUriPart()}/pag/$page/" } } } GET(url, headers) } } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() // Details override fun mangaDetailsParse(document: Document): SManga { return document.select("div.gallery_top").let { info -> SManga.create().apply { title = info.select("h1").text() genre = info.select("ul.tags a").joinToString { it.ownText() } artist = info.select("ul.artists a").joinToString { it.ownText() } thumbnail_url = info.select("img").attr("abs:src") description = info.select("ul.parodies a") .let { e -> if (e.isNotEmpty()) "Parodies: ${e.joinToString { it.ownText() }}\n\n" else "" } description += info.select("ul.characters a") .let { e -> if (e.isNotEmpty()) "Characters: ${e.joinToString { it.ownText() }}\n\n" else "" } description += info.select("ul.groups a") .let { e -> if (e.isNotEmpty()) "Groups: ${e.joinToString { it.ownText() }}\n\n" else "" } } } } // Chapters override fun chapterListParse(response: Response): List<SChapter> { return listOf( SChapter.create().apply { name = "Chapter" // page path with a marker at the end url = "${response.request.url.toString().replace("/gallery/", "/g/")}#" // number of pages url += response.asJsoup().select("[id=load_pages]").attr("value") } ) } override fun chapterListSelector() = throw UnsupportedOperationException("Not used") override fun chapterFromElement(element: Element): SChapter = throw UnsupportedOperationException("Not used") // Pages override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { // split the "url" to get the page path and number of pages return chapter.url.split("#").let { list -> Observable.just(listOf(1..list[1].toInt()).flatten().map { Page(it, list[0] + "$it/") }) } } override fun imageUrlParse(document: Document): String { return document.select("img#gimg").attr("abs:src") } override fun pageListParse(document: Document): List<Page> = throw UnsupportedOperationException("Not used") // Filters override fun getFilterList() = FilterList( Filter.Header("NOTE: Ignored if using text search!"), Filter.Separator(), GenreFilter() ) // Top 50 tags private class GenreFilter : UriPartFilter( "Category", arrayOf( Pair("<select>", "---"), Pair("Big breasts", "big-breasts"), Pair("Sole female", "sole-female"), Pair("Sole male", "sole-male"), Pair("Anal", "anal"), Pair("Nakadashi", "nakadashi"), Pair("Group", "group"), Pair("Stockings", "stockings"), Pair("Blowjob", "blowjob"), Pair("Schoolgirl uniform", "schoolgirl-uniform"), Pair("Rape", "rape"), Pair("Lolicon", "lolicon"), Pair("Glasses", "glasses"), Pair("Defloration", "defloration"), Pair("Ahegao", "ahegao"), Pair("Incest", "incest"), Pair("Shotacon", "shotacon"), Pair("X-ray", "x-ray"), Pair("Bondage", "bondage"), Pair("Full color", "full-color"), Pair("Double penetration", "double-penetration"), Pair("Femdom", "femdom"), Pair("Milf", "milf"), Pair("Yaoi", "yaoi"), Pair("Multi-work series", "multi-work-series"), Pair("Schoolgirl", "schoolgirl"), Pair("Mind break", "mind-break"), Pair("Paizuri", "paizuri"), Pair("Mosaic censorship", "mosaic-censorship"), Pair("Impregnation", "impregnation"), Pair("Males only", "males-only"), Pair("Sex toys", "sex-toys"), Pair("Sister", "sister"), Pair("Dark skin", "dark-skin"), Pair("Ffm threesome", "ffm-threesome"), Pair("Hairy", "hairy"), Pair("Cheating", "cheating"), Pair("Sweating", "sweating"), Pair("Yuri", "yuri"), Pair("Netorare", "netorare"), Pair("Full censorship", "full-censorship"), Pair("Schoolboy uniform", "schoolboy-uniform"), Pair("Dilf", "dilf"), Pair("Big penis", "big-penis"), Pair("Futanari", "futanari"), Pair("Swimsuit", "swimsuit"), Pair("Collar", "collar"), Pair("Uncensored", "uncensored"), Pair("Big ass", "big-ass"), Pair("Story arc", "story-arc"), Pair("Teacher", "teacher") ) ) private open class UriPartFilter(displayName: String, private val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
apache-2.0
42bfe6f99655d19b654c366a800a4ef8
36.462264
117
0.587635
4.429448
false
false
false
false
raxden/square
square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/fragmentbottomsheet/FragmentBottomSheetActivityInterceptor.kt
2
5974
package com.raxdenstudios.square.interceptor.commons.fragmentbottomsheet import android.app.Activity import android.os.Bundle import android.support.design.widget.BottomSheetBehavior import android.support.v4.app.Fragment import android.view.View import com.raxdenstudios.square.interceptor.ActivityInterceptor class FragmentBottomSheetActivityInterceptor<TView : View, TFragment : Fragment>( callback: HasFragmentBottomSheetInterceptor<TView, TFragment> ) : ActivityInterceptor<FragmentBottomSheetInterceptor, HasFragmentBottomSheetInterceptor<TView, TFragment>>(callback), FragmentBottomSheetInterceptor { companion object { private val IS_VISIBLE = FragmentBottomSheetActivityInterceptor::class.java.simpleName + "_isVisible" private val BOTTOM_SHEET_BEHAVIOUR_STATE = FragmentBottomSheetActivityInterceptor::class.java.simpleName + "_bottomSheetBehaviourState" } private lateinit var mBottomSheetView: TView private lateinit var mBottomSheetBehavior: BottomSheetBehavior<TView> private var mBottomSheetListenerList: MutableList<BottomSheetListener> = mutableListOf() private lateinit var mContainerView: View private var mCurrentPeekHeight: Int = 0 private var mCurrentState: Int = 0 private var mFragment: TFragment? = null override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { super.onActivityCreated(activity, savedInstanceState) mBottomSheetView = mCallback.onCreateBottomSheetView() mBottomSheetBehavior = initBottomSheetBehaviour(savedInstanceState) getFragmentManager(activity)?.also { fm -> mContainerView = mCallback.onLoadBottomSheetFragmentContainer() if (savedInstanceState == null) { mFragment = mCallback.onCreateBottomSheetFragment().also { fm.beginTransaction() .replace(mContainerView.id, it, it.javaClass.simpleName) .commit() mCallback.onBottomSheetFragmentLoaded(it) } } } } override fun onActivityStarted(activity: Activity, savedInstanceState: Bundle?) { super.onActivityStarted(activity, savedInstanceState) savedInstanceState?.containsKey(IS_VISIBLE)?.also { if (!savedInstanceState.getBoolean(IS_VISIBLE)) { hide() } } getFragmentManager(activity)?.also { fm -> if (savedInstanceState != null) { mFragment = (fm.findFragmentById(mContainerView.id) as? TFragment)?.also { mCallback.onBottomSheetFragmentLoaded(it) } } } } override fun onActivityDestroyed(activity: Activity) { super.onActivityDestroyed(activity) mFragment = null mBottomSheetListenerList.clear() } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) { outState?.putInt(BOTTOM_SHEET_BEHAVIOUR_STATE, mBottomSheetBehavior.state) outState?.putBoolean(IS_VISIBLE, isVisible()) super.onActivitySaveInstanceState(activity, outState) } override fun collapse() { mBottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED } override fun expand() { mBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED } override fun hide() { if (!isVisible()) return mCurrentPeekHeight = mBottomSheetBehavior.peekHeight mCurrentState = mBottomSheetBehavior.state mBottomSheetBehavior.peekHeight = 0 mBottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED } override fun show() { if (isVisible()) return mBottomSheetBehavior.peekHeight = mCurrentPeekHeight mBottomSheetBehavior.state = mCurrentState } override fun isVisible(): Boolean = mBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED || mBottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED && (mBottomSheetBehavior.peekHeight == -1 || mBottomSheetBehavior.peekHeight > 0) override fun isExpanded(): Boolean = mBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED override fun isCollapsed(): Boolean = mBottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED interface BottomSheetListener { fun onStateChanged(bottomSheet: View, newState: Int) fun onSlide(bottomSheet: View, slideOffset: Float) } override fun addBottomSheetListener(listener: BottomSheetListener) { if (!mBottomSheetListenerList.contains(listener)) mBottomSheetListenerList.add(listener) } override fun removeBottomSheetListener(listener: BottomSheetListener) { if (mBottomSheetListenerList.contains(listener)) mBottomSheetListenerList.remove(listener) } private fun initBottomSheetBehaviour(savedInstanceState: Bundle?): BottomSheetBehavior<TView> { return BottomSheetBehavior.from<TView>(mBottomSheetView).also { behaviour -> behaviour.state = savedInstanceState?.getInt(BOTTOM_SHEET_BEHAVIOUR_STATE).takeIf { it != 0 }?.also { state -> state } ?: BottomSheetBehavior.STATE_COLLAPSED behaviour.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { mBottomSheetListenerList.forEach { it.onStateChanged(bottomSheet, newState) } } override fun onSlide(bottomSheet: View, slideOffset: Float) { mBottomSheetListenerList.forEach { it.onSlide(bottomSheet, slideOffset) } } }) mCallback.onBottomSheetBehaviourCreated(behaviour) } } }
apache-2.0
dc9b09f6e1db462b7ea7f143a47ac733
40.493056
162
0.685805
5.755299
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/seven/indicatorlist/IndicatorListAdapter.kt
1
9262
package com.intfocus.template.subject.seven.indicatorlist import android.content.Context import android.os.Build import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseExpandableListAdapter import android.widget.TextView import com.alibaba.fastjson.JSON import com.intfocus.template.R import com.intfocus.template.model.response.attention.Test2 import com.intfocus.template.subject.one.entity.SingleValue import com.intfocus.template.subject.seven.indicatorgroup.IndicatorGroupAdapter import com.intfocus.template.subject.seven.listener.EventRefreshIndicatorListItemData import com.intfocus.template.subject.seven.listener.IndicatorListItemDataUpdateListener import com.intfocus.template.ui.view.autofittextview.AutofitTextView import com.intfocus.template.util.LoadAssetsJsonUtil import com.intfocus.template.util.LogUtil import com.intfocus.template.util.OKHttpUtils import com.intfocus.template.util.RxBusUtil import okhttp3.Call import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.io.IOException /** * **************************************************** * @author jameswong * created on: 17/12/18 下午5:35 * e-mail: [email protected] * name: 模板七 - 关注 - 详情信息列表适配器 * desc: * **************************************************** */ class IndicatorListAdapter(private val mCtx: Context, val fragment: Fragment, val data: List<Test2.DataBeanXX.AttentionedDataBean>) : BaseExpandableListAdapter(), IndicatorListItemDataUpdateListener { companion object { val CODE_EVENT_REFRESH_INDICATOR_LIST_ITEM_DATA = 1 } val testApi = "https://api.douban.com/v2/book/search?q=%E7%BC%96%E7%A8%8B%E8%89%BA%E6%9C%AF" private val coCursor = mCtx.resources.getIntArray(R.array.co_cursor)!! private val bgList = mutableListOf( R.drawable.bg_radius_sold_red, R.drawable.bg_radius_sold_yellow, R.drawable.bg_radius_sold_green ) private var currentItemDataIndex = 0 private var firstUpdateData = true override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean = false override fun hasStableIds(): Boolean = false override fun getGroupId(groupPosition: Int): Long = groupPosition.toLong() override fun getGroupCount(): Int = data.size override fun getGroup(groupPosition: Int): Test2.DataBeanXX.AttentionedDataBean = data[groupPosition] override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View { var view: View? = null var groupHolder: IndicatorGroupHolder? = null if (convertView != null) { view = convertView groupHolder = view.tag as IndicatorGroupHolder } else { view = LayoutInflater.from(mCtx).inflate(R.layout.item_indicator_list_group, parent, false) groupHolder = IndicatorGroupHolder() groupHolder.tvName = view!!.findViewById(R.id.tv_item_indicator_list_group_name) groupHolder.tvId = view.findViewById(R.id.tv_item_indicator_list_group_id) groupHolder.tvValue = view.findViewById(R.id.tv_item_indicator_list_group_value) view.tag = groupHolder } getGroup(groupPosition).attention_item_name?.let { groupHolder.tvName?.text = it } getGroup(groupPosition).attention_item_id?.let { groupHolder.tvId?.text = it } RxBusUtil.getInstance().toObservable(EventRefreshIndicatorListItemData::class.java) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { event -> LogUtil.d(this@IndicatorListAdapter, "groupPosition ::: " + groupPosition) LogUtil.d(this@IndicatorListAdapter, "event.childPosition ::: " + event.childPosition) firstUpdateData = false val data = getChild(groupPosition, 0)[event.childPosition] if (data.isReal_time) { // data.real_time_api?.let { testApi.let { OKHttpUtils.newInstance().getAsyncData(it, object : OKHttpUtils.OnReusltListener { override fun onFailure(call: Call?, e: IOException?) { } override fun onSuccess(call: Call?, response: String?) { val itemData = JSON.parseObject(LoadAssetsJsonUtil.getAssetsJsonData(data.real_time_api), SingleValue::class.java) data.main_data = itemData.main_data data.sub_data = itemData.sub_data data.state = itemData.state data.isReal_time = false data.let { groupHolder.tvValue?.text = it.main_data.data groupHolder.tvValue?.setTextColor(coCursor[it.state.color % coCursor.size]) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { groupHolder.tvValue?.background = mCtx.getDrawable(bgList[it.state.color % coCursor.size]) } else { groupHolder.tvValue?.background = mCtx.resources.getDrawable(bgList[it.state.color % coCursor.size]) } currentItemDataIndex = event.childPosition } } }) } } else { data.let { groupHolder.tvValue?.text = it.main_data.data groupHolder.tvValue?.setTextColor(coCursor[it.state.color % coCursor.size]) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { groupHolder.tvValue?.background = mCtx.getDrawable(bgList[it.state.color % coCursor.size]) } else { groupHolder.tvValue?.background = mCtx.resources.getDrawable(bgList[it.state.color % coCursor.size]) } currentItemDataIndex = event.childPosition } } } // if (firstUpdateData) { val itemData = getChild(groupPosition, 0)[currentItemDataIndex] groupHolder.tvValue?.text = itemData.main_data.data groupHolder.tvValue?.setTextColor(coCursor[itemData.state.color % coCursor.size]) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { groupHolder.tvValue?.background = mCtx.getDrawable(bgList[itemData.state.color % coCursor.size]) } else { groupHolder.tvValue?.background = mCtx.resources.getDrawable(bgList[itemData.state.color % coCursor.size]) } groupHolder.tvValue?.setOnClickListener { currentItemDataIndex += 1 RxBusUtil.getInstance().post(EventRefreshIndicatorListItemData(currentItemDataIndex % getChild(groupPosition, 0).size)) } // } return view } override fun getChildrenCount(groupPosition: Int): Int = 1 override fun getChild(groupPosition: Int, childPosition: Int): List<SingleValue> = getGroup(groupPosition).attention_item_data override fun getChildId(groupPosition: Int, childPosition: Int): Long = childPosition.toLong() override fun getChildView(groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup?): View { var view: View? = null var childHolder: IndicatorChildHolder? = null if (convertView != null) { view = convertView childHolder = view.tag as IndicatorChildHolder } else { view = LayoutInflater.from(mCtx).inflate(R.layout.item_indicator_list_child, parent, false) childHolder = IndicatorChildHolder() childHolder.rvIndicatorGroup = view!!.findViewById(R.id.rv_indicator_group) view.tag = childHolder childHolder.rvIndicatorGroup!!.isFocusable = false } childHolder.rvIndicatorGroup!!.layoutManager = LinearLayoutManager(mCtx, LinearLayoutManager.HORIZONTAL, false) childHolder.rvIndicatorGroup!!.adapter = IndicatorGroupAdapter(mCtx, getChild(groupPosition, 0), CODE_EVENT_REFRESH_INDICATOR_LIST_ITEM_DATA) return view } fun setData() { } override fun dataUpdated(pos: Int) { } class IndicatorGroupHolder { var tvName: TextView? = null var tvId: TextView? = null var tvValue: AutofitTextView? = null } class IndicatorChildHolder { var rvIndicatorGroup: RecyclerView? = null } }
gpl-3.0
5219bedd94df6baa7a1831c0d6cbdb0c
47.072917
200
0.62091
4.716403
false
false
false
false
SecUSo/privacy-friendly-qr-scanner
app/src/main/java/com/secuso/privacyfriendlycodescanner/qrscanner/util/WebSearchUtil.kt
1
2681
package com.secuso.privacyfriendlycodescanner.qrscanner.util import android.content.Context import android.content.Intent import android.net.Uri import android.preference.PreferenceManager import androidx.appcompat.app.AlertDialog import com.secuso.privacyfriendlycodescanner.qrscanner.R object WebSearchUtil { @JvmStatic fun openWebSearchDialog(context: Context, content: String) { val searchEngineURI = getSearchEngineURI(context) val dialog: AlertDialog = AlertDialog.Builder(context) .setMessage( context.resources.getString( R.string.fragment_result_text_dialog_message, getSearchEngineName(context) ) ) .setIcon(R.drawable.ic_warning) .setTitle(R.string.fragment_result_text_dialog_title) .setPositiveButton( R.string.fragment_result_text_dialog_positive_button ) { _, _ -> val uri = Uri.parse(String.format(searchEngineURI, content)) val search = Intent(Intent.ACTION_VIEW, uri) val caption: String = context.resources.getStringArray(R.array.text_array).get(0) context.startActivity(Intent.createChooser(search, caption)) } .setNegativeButton(android.R.string.cancel, null).create() dialog.show() } private fun getPrefSearchEngineIndex(context: Context): Int { val searchEngines: Array<String> = context.resources.getStringArray(R.array.pref_search_engine_values) val pref = PreferenceManager.getDefaultSharedPreferences(context) val activeSearchEngine = pref.getString("pref_search_engine", searchEngines[0]) var i = 0 while (i < searchEngines.size) { if (searchEngines[i] == activeSearchEngine) { break } i++ } return if (i < searchEngines.size) { i } else 0 } private fun getSearchEngineURI(context: Context): String { val searchEngineIndex = getPrefSearchEngineIndex(context) val searchEngineUris: Array<String> = context.resources.getStringArray(R.array.pref_search_engine_uris) return searchEngineUris[searchEngineIndex] } private fun getSearchEngineName(context: Context): String { val searchEngineIndex = getPrefSearchEngineIndex(context) val searchEnginesEntries: Array<String> = context.resources.getStringArray(R.array.pref_search_engine_entries) return searchEnginesEntries[searchEngineIndex] } }
gpl-3.0
67a7a240ebc62308639c0be797bd9383
38.441176
87
0.643044
4.813285
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQuerySlidingWindowClausePsiImpl.kt
1
2266
/* * Copyright (C) 2016-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQuerySlidingWindowClause class XQuerySlidingWindowClausePsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQuerySlidingWindowClause, XpmSyntaxValidationElement { // region PsiElement override fun getUseScope(): SearchScope = LocalSearchScope(parent.parent) // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = firstChild // endregion // region XpmVariableBinding override val variableName: XsQNameValue? get() = children().filterIsInstance<XPathEQName>().firstOrNull() // endregion // region XpmCollectionBinding override val variableType: XdmSequenceType? get() = children().filterIsInstance<XdmSequenceType>().firstOrNull() override val bindingExpression: XpmExpression? get() = children().filterIsInstance<XpmExpression>().firstOrNull() // endregion }
apache-2.0
eead1febf04e0b0a19a575b0aeceb24a
36.147541
85
0.772727
4.633947
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/execution/configurations/rdf/RdfFormatLanguages.kt
1
5774
/* * Copyright (C) 2019 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.processor.query.execution.configurations.rdf import com.intellij.lang.Language import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher import com.intellij.openapi.fileTypes.FileNameMatcher import uk.co.reecedunn.intellij.plugin.core.lang.LanguageData val N3: Language by lazy { Language.findInstancesByMimeType("text/n3").firstOrNull() ?: run { val language = Language.findLanguageByID("N3") ?: object : Language("N3") {} language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("n3") ) override val mimeTypes: Array<String> = arrayOf("text/n3") }) language } } val NQuads: Language by lazy { Language.findInstancesByMimeType("application/n-quads").firstOrNull() ?: run { val language = Language.findLanguageByID("NQuads") ?: object : Language("NQuads") { override fun getDisplayName(): String = "N-Quads" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("nq") ) override val mimeTypes: Array<String> = arrayOf("application/n-quads") }) language } } val NTriples: Language by lazy { Language.findInstancesByMimeType("application/n-triples").firstOrNull() ?: run { val language = Language.findLanguageByID("NTriples") ?: object : Language("NTriples") { override fun getDisplayName(): String = "N-Triples" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("nt") ) override val mimeTypes: Array<String> = arrayOf("application/n-triples") }) language } } val RdfJson: Language by lazy { Language.findInstancesByMimeType("application/rdf+json").firstOrNull() ?: run { val language = Language.findLanguageByID("RDFJSON") ?: object : Language("RDFJSON") { override fun getDisplayName(): String = "RDF/JSON" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("rj") ) override val mimeTypes: Array<String> = arrayOf("application/rdf+json") }) language } } val RdfXml: Language by lazy { Language.findInstancesByMimeType("application/rdf+xml").firstOrNull() ?: run { val language = Language.findLanguageByID("RDFXML") ?: object : Language("RDFXML") { override fun getDisplayName(): String = "RDF/XML" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("rdf") ) override val mimeTypes: Array<String> = arrayOf("application/rdf+xml") }) language } } val TriG: Language by lazy { Language.findInstancesByMimeType("application/trig").firstOrNull() ?: run { val language = Language.findLanguageByID("TriG") ?: object : Language("TriG") { override fun getDisplayName(): String = "TriG" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("trig") ) override val mimeTypes: Array<String> = arrayOf("application/trig") }) language } } val TripleXml: Language by lazy { Language.findInstancesByMimeType("application/vnd.marklogic.triples+xml").firstOrNull() ?: run { val language = Language.findLanguageByID("TripleXml") ?: object : Language("TripleXml") { override fun getDisplayName(): String = "MarkLogic Triple/XML" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("xml") ) override val mimeTypes: Array<String> = arrayOf("application/vnd.marklogic.triples+xml") }) language } } val Turtle: Language by lazy { Language.findInstancesByMimeType("text/turtle").firstOrNull() ?: run { val language = Language.findLanguageByID("Turtle") ?: object : Language("Turtle") { override fun getDisplayName(): String = "Turtle" } language.putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("ttl") ) override val mimeTypes: Array<String> = arrayOf("text/turtle") }) language } } val RDF_FORMATS: List<Language> by lazy { listOf(N3, NQuads, NTriples, RdfJson, RdfXml, TriG, TripleXml, Turtle) }
apache-2.0
39cc529f10b43cbefcc6a1225b34e9e1
37.238411
100
0.647904
4.600797
false
false
false
false
mtransitapps/parser
src/main/java/org/mtransit/parser/db/DBUtils.kt
1
19609
package org.mtransit.parser.db import org.mtransit.commons.sql.SQLCreateBuilder import org.mtransit.parser.DefaultAgencyTools import org.mtransit.parser.FileUtils import org.mtransit.parser.MTLog import org.mtransit.parser.gtfs.data.GStopTime import org.mtransit.parser.gtfs.data.GTripStop import org.mtransit.parser.mt.data.MSchedule import java.io.File import java.sql.Connection import java.sql.DriverManager import org.mtransit.commons.sql.SQLUtils as SQLUtilsCommons object DBUtils { private const val FILE_PATH = "input/db_file" private const val STOP_TIMES_TABLE_NAME = "g_stop_times" private const val TRIP_STOPS_TABLE_NAME = "g_trip_stops" private const val SCHEDULES_TABLE_NAME = "m_schedule" private const val SQL_RESULT_ALIAS = "result" private const val SQL_NULL = "null" private val connection: Connection by lazy { FileUtils.deleteIfExist(File(FILE_PATH)) // delete previous DriverManager.getConnection( if (DefaultAgencyTools.IS_CI) { SQLUtils.getJDBCSQLiteFile(FILE_PATH) } else { SQLUtils.JDBC_SQLITE_MEMORY // faster } ) } private var selectCount = 0 private var selectRowCount = 0 private var insertCount = 0 private var insertRowCount = 0 private var deleteCount = 0 private var deletedRowCount = 0 init { val statement = connection.createStatement() SQLUtils.execute(statement, "PRAGMA synchronous = OFF") SQLUtils.execute(statement, "PRAGMA journal_mode = MEMORY") SQLUtils.execute(statement, SQLUtilsCommons.PRAGMA_AUTO_VACUUM_NONE) SQLUtils.executeUpdate(statement, SQLUtilsCommons.getSQLDropIfExistsQuery(STOP_TIMES_TABLE_NAME)) SQLUtils.executeUpdate(statement, SQLUtilsCommons.getSQLDropIfExistsQuery(TRIP_STOPS_TABLE_NAME)) SQLUtils.executeUpdate(statement, SQLUtilsCommons.getSQLDropIfExistsQuery(SCHEDULES_TABLE_NAME)) SQLUtils.executeUpdate( statement, SQLCreateBuilder.getNew(STOP_TIMES_TABLE_NAME) .appendColumn(GStopTime.TRIP_ID, SQLUtilsCommons.INT) .appendColumn(GStopTime.STOP_ID, SQLUtilsCommons.INT) .appendColumn(GStopTime.STOP_SEQUENCE, SQLUtilsCommons.INT) .appendColumn(GStopTime.ARRIVAL_TIME, SQLUtilsCommons.INT) .appendColumn(GStopTime.DEPARTURE_TIME, SQLUtilsCommons.INT) .appendColumn(GStopTime.STOP_HEADSIGN, SQLUtilsCommons.TXT) // string ?? .appendColumn(GStopTime.PICKUP_TYPE, SQLUtilsCommons.INT) .appendColumn(GStopTime.DROP_OFF_TYPE, SQLUtilsCommons.INT) .appendColumn(GStopTime.TIME_POINT, SQLUtilsCommons.INT) .appendPrimaryKeys( GStopTime.TRIP_ID, GStopTime.STOP_SEQUENCE, ) .build() ) SQLUtils.executeUpdate( statement, SQLCreateBuilder.getNew(TRIP_STOPS_TABLE_NAME) .appendColumn(GTripStop.ROUTE_ID, SQLUtilsCommons.INT) .appendColumn(GTripStop.TRIP_ID, SQLUtilsCommons.INT) .appendColumn(GTripStop.STOP_ID, SQLUtilsCommons.INT) .appendColumn(GTripStop.STOP_SEQUENCE, SQLUtilsCommons.INT) .build() ) SQLUtils.executeUpdate( statement, SQLCreateBuilder.getNew(SCHEDULES_TABLE_NAME) .appendColumn(MSchedule.ROUTE_ID, SQLUtilsCommons.INT) .appendColumn(MSchedule.SERVICE_ID, SQLUtilsCommons.INT) .appendColumn(MSchedule.TRIP_ID, SQLUtilsCommons.INT) .appendColumn(MSchedule.STOP_ID, SQLUtilsCommons.INT) .appendColumn(MSchedule.ARRIVAL, SQLUtilsCommons.INT) .appendColumn(MSchedule.DEPARTURE, SQLUtilsCommons.INT) .appendColumn(MSchedule.PATH_ID, SQLUtilsCommons.INT) .appendColumn(MSchedule.HEADSIGN_TYPE, SQLUtilsCommons.INT) .appendColumn(MSchedule.HEADSIGN_VALUE, SQLUtilsCommons.TXT) // string ?? .build() ) } @Suppress("unused") @JvmStatic fun beginTransaction() = SQLUtils.beginTransaction(this.connection) @Suppress("unused") @JvmStatic fun endTransaction() = SQLUtils.endTransaction(this.connection) @JvmStatic fun setAutoCommit(autoCommit: Boolean) = SQLUtils.setAutoCommit(this.connection, autoCommit) @Suppress("unused") @JvmStatic fun commit() = SQLUtils.commit(this.connection) @JvmStatic @JvmOverloads fun insertStopTime(gStopTime: GStopTime, allowUpdate: Boolean = false): Boolean { val rs = SQLUtils.executeUpdate( connection.createStatement(), (if (allowUpdate) SQLUtilsCommons.INSERT_OR_REPLACE_INTO else SQLUtilsCommons.INSERT_INTO) + STOP_TIMES_TABLE_NAME + SQLUtilsCommons.VALUES_P1 + "${gStopTime.tripIdInt}," + "${gStopTime.stopIdInt}," + "${gStopTime.stopSequence}," + "${gStopTime.arrivalTime}," + "${gStopTime.departureTime}," + "${gStopTime.stopHeadsign?.let { SQLUtils.quotes(SQLUtils.escape(it)) }}," + "${gStopTime.pickupType.id}," + "${gStopTime.dropOffType.id}," + "${gStopTime.timePoint.id}" + SQLUtilsCommons.P2 ) insertRowCount++ insertCount++ return rs > 0 } @JvmStatic fun insertTripStop(gTripStop: GTripStop): Boolean { val rs = SQLUtils.executeUpdate( connection.createStatement(), SQLUtilsCommons.INSERT_INTO + TRIP_STOPS_TABLE_NAME + SQLUtilsCommons.VALUES_P1 + "${gTripStop.routeIdInt}," + "${gTripStop.tripIdInt}," + "${gTripStop.stopIdInt}," + "${gTripStop.stopSequence}" + SQLUtilsCommons.P2 ) insertRowCount++ insertCount++ return rs > 0 } @JvmStatic fun insertSchedule(mSchedule: MSchedule): Boolean { val rs = SQLUtils.executeUpdate( connection.createStatement(), SQLUtilsCommons.INSERT_INTO + SCHEDULES_TABLE_NAME + SQLUtilsCommons.VALUES_P1 + "${mSchedule.routeId}," + "${mSchedule.serviceIdInt}," + "${mSchedule.tripId}," + "${mSchedule.stopId}," + "${mSchedule.arrival}," + "${mSchedule.departure}," + "${mSchedule.pathIdInt}," + "${mSchedule.headsignType}," + "${mSchedule.headsignValue?.let { SQLUtils.quotes(SQLUtils.escape(it)) }}" + SQLUtilsCommons.P2 ) insertRowCount++ insertCount++ return rs > 0 } @JvmStatic fun selectStopTimes( tripId: Int? = null, tripIds: List<Int>? = null, limitMaxNbRow: Int? = null, limitOffset: Int? = null ): List<GStopTime> { var query = "SELECT * FROM $STOP_TIMES_TABLE_NAME" tripId?.let { query += " WHERE ${GStopTime.TRIP_ID} = $tripId" } tripIds?.let { query += " WHERE ${GStopTime.TRIP_ID} IN ${ tripIds .distinct() .joinToString( separator = ",", prefix = "(", postfix = ")" ) { "$it" } }" } query += " ORDER BY " + "${GStopTime.TRIP_ID} ASC, " + "${GStopTime.STOP_SEQUENCE} ASC, " + "${GStopTime.DEPARTURE_TIME} ASC" limitMaxNbRow?.let { query += " LIMIT $limitMaxNbRow" limitOffset?.let { query += " OFFSET $limitOffset" } } val result = ArrayList<GStopTime>() val rs = SQLUtils.executeQuery(connection.createStatement(), query) while (rs.next()) { var stopHeadSign: String? = rs.getString(GStopTime.STOP_HEADSIGN) if (stopHeadSign == SQL_NULL) { stopHeadSign = null } result.add( GStopTime( rs.getInt(GStopTime.TRIP_ID), rs.getInt(GStopTime.ARRIVAL_TIME), rs.getInt(GStopTime.DEPARTURE_TIME), rs.getInt(GStopTime.STOP_ID), rs.getInt(GStopTime.STOP_SEQUENCE), stopHeadSign, rs.getInt(GStopTime.PICKUP_TYPE), rs.getInt(GStopTime.DROP_OFF_TYPE), rs.getInt(GStopTime.TIME_POINT), ) ) selectRowCount++ } selectCount++ return result } @JvmStatic fun selectTripStops( tripIdInt: Int? = null, tripIdInts: List<Int>? = null, limitMaxNbRow: Int? = null, limitOffset: Int? = null ): List<GTripStop> { var query = "SELECT * FROM $TRIP_STOPS_TABLE_NAME" tripIdInt?.let { query += " WHERE ${GTripStop.TRIP_ID} = $tripIdInt" } tripIdInts?.let { query += " WHERE ${GTripStop.TRIP_ID} IN ${ tripIdInts .distinct() .joinToString( separator = ",", prefix = "(", postfix = ")" ) { "$it" } }" } limitMaxNbRow?.let { query += " LIMIT $limitMaxNbRow" limitOffset?.let { query += " OFFSET $limitOffset" } } val result = ArrayList<GTripStop>() val rs = SQLUtils.executeQuery(connection.createStatement(), query) while (rs.next()) { result.add( GTripStop( rs.getInt(GTripStop.ROUTE_ID), rs.getInt(GTripStop.TRIP_ID), rs.getInt(GTripStop.STOP_ID), rs.getInt(GTripStop.STOP_SEQUENCE) ) ) selectRowCount++ } selectCount++ return result } @JvmStatic fun selectSchedules( serviceIdInt: Int? = null, serviceIdInts: List<Int>? = null, tripId: Long? = null, tripIds: List<Long>? = null, stopIdInt: Int? = null, stopIdInts: List<Int>? = null, arrival: Int? = null, departure: Int? = null, limitMaxNbRow: Int? = null, limitOffset: Int? = null ): List<MSchedule> { var query = "SELECT * FROM $SCHEDULES_TABLE_NAME" var whereAdded = false // SERVICE ID serviceIdInt?.let { @Suppress("KotlinConstantConditions") query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.SERVICE_ID} = $serviceIdInt" } serviceIdInts?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.SERVICE_ID} IN ${ serviceIdInts .distinct() .joinToString( separator = ",", prefix = "(", postfix = ")" ) { "$it" } }" whereAdded = true } // TRIP ID tripId?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.TRIP_ID} = $tripId" } tripIds?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.TRIP_ID} IN ${ tripIds .distinct() .joinToString( separator = ",", prefix = "(", postfix = ")" ) { "$it" } }" whereAdded = true } // STOP ID stopIdInt?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.STOP_ID} = $stopIdInt" } stopIdInts?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.STOP_ID} IN ${ stopIdInts .distinct() .joinToString( separator = ",", prefix = "(", postfix = ")" ) { "$it" } }" whereAdded = true } // ARRIVAL & DEPARTURE arrival?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.ARRIVAL} = $arrival" } departure?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.DEPARTURE} = $departure" } query += " ORDER BY " + "${MSchedule.SERVICE_ID} ASC, " + "${MSchedule.TRIP_ID} ASC, " + "${MSchedule.STOP_ID} ASC, " + "${MSchedule.DEPARTURE} ASC" // LIMIT limitMaxNbRow?.let { query += " LIMIT $limitMaxNbRow" limitOffset?.let { query += " OFFSET $limitOffset" } } val result = ArrayList<MSchedule>() val rs = SQLUtils.executeQuery(connection.createStatement(), query) while (rs.next()) { var headsignValue: String? = rs.getString(MSchedule.HEADSIGN_VALUE) if (headsignValue == SQL_NULL) { headsignValue = null } result.add( MSchedule( rs.getLong(MSchedule.ROUTE_ID), rs.getInt(MSchedule.SERVICE_ID), rs.getLong(MSchedule.TRIP_ID), rs.getInt(MSchedule.STOP_ID), rs.getInt(MSchedule.ARRIVAL), rs.getInt(MSchedule.DEPARTURE), rs.getInt(MSchedule.PATH_ID), rs.getInt(MSchedule.HEADSIGN_TYPE), headsignValue ) ) selectRowCount++ } selectCount++ return result } @Suppress("unused") @JvmStatic fun deleteStopTime(gStopTime: GStopTime): Boolean { var query = "DELETE FROM $STOP_TIMES_TABLE_NAME" query += " WHERE " + "${GStopTime.TRIP_ID} = ${gStopTime.tripIdInt}" + " AND " + "${GStopTime.STOP_ID} = ${gStopTime.stopIdInt}" + " AND " + "${GStopTime.STOP_SEQUENCE} = ${gStopTime.stopSequence}" val rs = SQLUtils.executeUpdate(connection.createStatement(), query) deletedRowCount += rs if (rs > 1) { throw MTLog.Fatal("Deleted too many stop times!") } deleteCount++ return rs > 0 } @JvmStatic fun deleteStopTimes(tripId: Int? = null): Int { var query = "DELETE FROM $STOP_TIMES_TABLE_NAME" tripId?.let { query += " WHERE " + "${GStopTime.TRIP_ID} = $tripId" } deleteCount++ val rs = SQLUtils.executeUpdate(connection.createStatement(), query) deletedRowCount += rs return rs } @Suppress("unused") @JvmStatic fun deleteSchedules( serviceIdInt: Int? = null, tripId: Long? = null, stopIdInt: Int? = null, arrival: Int? = null, departure: Int? = null ): Int { var query = "DELETE FROM $SCHEDULES_TABLE_NAME" var whereAdded = false serviceIdInt?.let { @Suppress("KotlinConstantConditions") query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.SERVICE_ID} = $serviceIdInt" } tripId?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.TRIP_ID} = $tripId" } // STOP ID stopIdInt?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.STOP_ID} = $stopIdInt" } // ARRIVAL & DEPARTURE arrival?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.ARRIVAL} = $arrival" } departure?.let { query += if (whereAdded) { " AND" } else { " WHERE" } whereAdded = true query += " ${MSchedule.DEPARTURE} = $departure" } deleteCount++ val rs = SQLUtils.executeUpdate(connection.createStatement(), query) deletedRowCount += rs return rs } @JvmStatic fun countStopTimes(): Int { val rs = SQLUtils.executeQuery( connection.createStatement(), "SELECT COUNT(*) AS $SQL_RESULT_ALIAS FROM $STOP_TIMES_TABLE_NAME" ) selectCount++ if (rs.next()) { selectRowCount++ return rs.getInt(SQL_RESULT_ALIAS) } throw MTLog.Fatal("Error while counting stop times!") } @JvmStatic fun countTripStops(): Int { val rs = SQLUtils.executeQuery( connection.createStatement(), "SELECT COUNT(*) AS $SQL_RESULT_ALIAS FROM $TRIP_STOPS_TABLE_NAME" ) selectCount++ if (rs.next()) { selectRowCount++ return rs.getInt(SQL_RESULT_ALIAS) } throw MTLog.Fatal("Error while counting trip stops!") } @JvmStatic fun countSchedule(): Int { val rs = SQLUtils.executeQuery( connection.createStatement(), "SELECT COUNT(*) AS $SQL_RESULT_ALIAS FROM $SCHEDULES_TABLE_NAME" ) selectCount++ if (rs.next()) { selectRowCount++ return rs.getInt(SQL_RESULT_ALIAS) } throw MTLog.Fatal("Error while counting schedules!") } @JvmStatic fun printStats() { MTLog.log("SQL: insert [$insertCount|$insertRowCount], select [$selectCount|$selectRowCount], delete [$deleteCount|$deletedRowCount].") } }
apache-2.0
bc02d426c49d374e61908c7a34bdd425
32.927336
143
0.498955
4.472856
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/util/ColourScheme.kt
1
3551
package nl.sugcube.dirtyarrows.util import org.bukkit.Color /** * @author SugarCaney */ open class ColourScheme(vararg val colours: Color) : List<Color> by colours.toList() { companion object { val TRICOLORE = ColourScheme( Color.fromRGB(174, 28, 40), Color.fromRGB(255, 255, 255), Color.fromRGB(33, 70, 139), ) val RAINBOW = ColourScheme( Color.fromRGB(255, 0, 0), Color.fromRGB(255, 140, 0), Color.fromRGB(255, 238, 0), Color.fromRGB(77, 233, 76), Color.fromRGB(55, 131, 255), Color.fromRGB(72, 21, 170), ) val ORANGE_YELLOW = ColourScheme( Color.fromRGB(245, 128, 37), Color.fromRGB(245, 152, 48), Color.fromRGB(245, 176, 59), Color.fromRGB(245, 200, 69), Color.fromRGB(245, 224, 80), ) val TRANS_RIGHTS = ColourScheme( Color.fromRGB(85, 205, 252), Color.fromRGB(255, 255, 255), Color.fromRGB(247, 168, 184), ) val LOVE_PASTEL = ColourScheme( Color.fromRGB(255, 240, 243), Color.fromRGB(254, 225, 230), Color.fromRGB(206, 204, 228), Color.fromRGB(230, 247, 241), Color.fromRGB(255, 251, 242), ) val REAL_SKIN_TONES = ColourScheme( Color.fromRGB(141, 85, 36), Color.fromRGB(198, 134, 66), Color.fromRGB(224, 172, 105), Color.fromRGB(241, 194, 125), Color.fromRGB(255, 219, 172), ) val LEAF_IN_FALL = ColourScheme( Color.fromRGB(186, 70, 52), Color.fromRGB(216, 92, 78), Color.fromRGB(234, 162, 80), Color.fromRGB(245, 221, 139), Color.fromRGB(206, 194, 24), Color.fromRGB(95, 120, 24), ) val OCEAN = ColourScheme( Color.fromRGB(7, 96, 148), Color.fromRGB(10, 124, 190), Color.fromRGB(75, 199, 207), Color.fromRGB(121, 217, 210), Color.fromRGB(32, 178, 170), ) val EUROPE = ColourScheme( Color.fromRGB(0, 51, 153), Color.fromRGB(0, 51, 153), Color.fromRGB(255, 204, 0), Color.fromRGB(0, 51, 153), Color.fromRGB(0, 51, 153), ) val ACE = ColourScheme( Color.fromRGB(0, 0, 0), Color.fromRGB(164, 164, 164), Color.fromRGB(255, 255, 255), Color.fromRGB(129, 0, 129), ) val LIME = ColourScheme( Color.fromRGB(77, 138, 18), Color.fromRGB(130, 183, 42), Color.fromRGB(194, 224, 106), Color.fromRGB(227, 231, 138), Color.fromRGB(253, 246, 190), ) val SCARLET = ColourScheme( Color.fromRGB(255, 247, 240), Color.fromRGB(255, 61, 61), Color.fromRGB(198, 47, 47), Color.fromRGB(165, 39, 39), Color.fromRGB(127, 15, 11), ) val DEFAULT_SCHEMES = listOf( TRICOLORE, RAINBOW, ORANGE_YELLOW, TRANS_RIGHTS, LOVE_PASTEL, REAL_SKIN_TONES, LEAF_IN_FALL, OCEAN, EUROPE, ACE, LIME, SCARLET ) } }
gpl-3.0
89aa65382355ad5de299505ebdeb84fe
31.290909
108
0.470008
3.745781
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/navigation/KindlishNavigation.kt
1
707
package eu.kanade.tachiyomi.ui.reader.viewer.navigation import android.graphics.RectF import eu.kanade.tachiyomi.ui.reader.viewer.ViewerNavigation /** * Visualization of default state without any inversion * +---+---+---+ * | M | M | M | P: Previous * +---+---+---+ * | P | N | N | M: Menu * +---+---+---+ * | P | N | N | N: Next * +---+---+---+ */ class KindlishNavigation : ViewerNavigation() { override var regions: List<Region> = listOf( Region( rectF = RectF(0.33f, 0.33f, 1f, 1f), type = NavigationRegion.NEXT, ), Region( rectF = RectF(0f, 0.33f, 0.33f, 1f), type = NavigationRegion.PREV, ), ) }
apache-2.0
3aae1269a119c6225323acec22102f1c
24.25
60
0.534653
3.415459
false
false
false
false
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt
1
1812
@file:Suppress("DEPRECATION") package info.nightscout.androidaps.complications import android.app.PendingIntent import android.graphics.drawable.Icon import android.support.wearable.complications.ComplicationData import android.support.wearable.complications.ComplicationText import info.nightscout.androidaps.R import info.nightscout.androidaps.data.RawDisplayData import info.nightscout.androidaps.interaction.utils.DisplayFormat import info.nightscout.androidaps.interaction.utils.SmallestDoubleString import info.nightscout.shared.logging.LTag /* * Created by dlvoy on 2019-11-12 */ class IobIconComplication : BaseComplicationProviderService() { override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { var complicationData: ComplicationData? = null if (dataType == ComplicationData.TYPE_SHORT_TEXT) { val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(DisplayFormat.MAX_FIELD_LEN_SHORT) val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) .setShortText(ComplicationText.plainText(iob)) .setIcon(Icon.createWithResource(this, R.drawable.ic_ins)) .setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_ins_burnin)) .setTapAction(complicationPendingIntent) complicationData = builder.build() } else { aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") } return complicationData } override fun getProviderCanonicalName(): String = IobIconComplication::class.java.canonicalName!! override fun getComplicationAction(): ComplicationAction = ComplicationAction.BOLUS }
agpl-3.0
0bfdbeba72135935b906c451c98f6785
46.684211
137
0.762141
4.806366
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquireResponsePacket.kt
1
1558
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * SneckLimitInquireResponsePacket */ class SneckLimitInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump init { msgType = 0x90.toByte() aapsLogger.debug(LTag.PUMPCOMM, "SneckLimitInquireResponsePacket init") } override fun handleMessage(data: ByteArray?) { val result = defect(data) if (result != 0) { aapsLogger.debug(LTag.PUMPCOMM, "SneckLimitInquireResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) val result2 = getByteToInt(bufferData) if(!isSuccInquireResponseResult(result2)) { failed = true return } diaconnG8Pump.maxBolus = getShortToInt(bufferData).toDouble() / 100 diaconnG8Pump.maxBolusePerDay = getShortToInt(bufferData).toDouble() / 100 aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") aapsLogger.debug(LTag.PUMPCOMM, "maxBolusePerDay --> ${diaconnG8Pump.maxBolusePerDay}") aapsLogger.debug(LTag.PUMPCOMM, "maxBolus --> ${diaconnG8Pump.maxBolus}") } override fun getFriendlyName(): String { return "PUMP_SNACK_LIMIT_INQUIRE_RESPONSE" } }
agpl-3.0
42d77b0d59141bd735c9f708bd06b438
32.869565
98
0.689345
4.245232
false
false
false
false
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt
1
1756
@file:Suppress("DEPRECATION") package info.nightscout.androidaps.complications import android.app.PendingIntent import android.support.wearable.complications.ComplicationData import android.support.wearable.complications.ComplicationText import dagger.android.AndroidInjection import info.nightscout.androidaps.data.RawDisplayData import info.nightscout.shared.logging.LTag /* * Created by dlvoy on 2019-11-12 */ class LongStatusFlippedComplication : BaseComplicationProviderService() { // Not derived from DaggerService, do injection here override fun onCreate() { AndroidInjection.inject(this) super.onCreate() } override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { var complicationData: ComplicationData? = null when (dataType) { ComplicationData.TYPE_LONG_TEXT -> { val glucoseLine = displayFormat.longGlucoseLine(raw) val detailsLine = displayFormat.longDetailsLine(raw) val builderLong = ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT) .setLongTitle(ComplicationText.plainText(detailsLine)) .setLongText(ComplicationText.plainText(glucoseLine)) .setTapAction(complicationPendingIntent) complicationData = builderLong.build() } else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") } return complicationData } override fun getProviderCanonicalName(): String = LongStatusFlippedComplication::class.java.canonicalName!! override fun usesSinceField(): Boolean = true }
agpl-3.0
00660d3664fc06c3c6b0a7a00e7ac6b7
39.860465
137
0.70672
5.241791
false
false
false
false
rlac/unitconverter
app/src/main/kotlin/au/id/rlac/unitconverter/widget/BindableSpinnerAdapter.kt
1
1948
package au.id.rlac.unitconverter.widget import android.R import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView /** * Basic static collection spinner adapter that supports passing in custom binding functions. * * @property layout Item layout, must have a TextView with the id text1. * @property ddLayout Drop down item layout, must have a TextView with the id text1. * @property bind Called to bind an item to a TextView. * @property getId Called to request the item's id. * @property items The list of items to bind. The list is owned by this adapter and must not be * modified. */ class BindableSpinnerAdapter<T>(context: Context, private val layout: Int = R.layout.simple_spinner_item, private val ddLayout: Int = R.layout.simple_spinner_dropdown_item, private val bind: (T, TextView) -> Unit, private val getId: (T) -> Long, private val items: List<T>) : BaseAdapter() { val inflater = LayoutInflater.from(context) override fun getCount(): Int = items.size override fun getItem(position: Int): Any? = items[position] override fun getItemId(position: Int): Long = getId(items[position]) override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val view = convertView ?: inflater.inflate(layout, parent, false) bind(items[position], view.findViewById(R.id.text1) as TextView) return view } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View? { val view = convertView ?: inflater.inflate(ddLayout, parent, false) bind(items[position], view.findViewById(R.id.text1) as TextView) return view } }
apache-2.0
b4114d86661c8831963acdb5c9049b21
39.604167
98
0.688398
4.348214
false
false
false
false
k9mail/k-9
app/core/src/test/java/com/fsck/k9/helper/ListUnsubscribeHelperTest.kt
2
3781
package com.fsck.k9.helper import androidx.core.net.toUri import com.fsck.k9.RobolectricTest import com.fsck.k9.mail.internet.MimeMessage import com.google.common.truth.Truth.assertThat import kotlin.test.assertNull import org.junit.Test class ListUnsubscribeHelperTest : RobolectricTest() { @Test fun `get list unsubscribe url - should accept mailto`() { val message = buildMimeMessageWithListUnsubscribeValue( "<mailto:[email protected]>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertThat(result).isEqualTo(MailtoUnsubscribeUri("mailto:[email protected]".toUri())) } @Test fun `get list unsubscribe url - should prefer mailto 1`() { val message = buildMimeMessageWithListUnsubscribeValue( "<mailto:[email protected]>, <https://example.com/unsubscribe>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertThat(result).isEqualTo(MailtoUnsubscribeUri("mailto:[email protected]".toUri())) } @Test fun `get list unsubscribe url - should prefer mailto 2`() { val message = buildMimeMessageWithListUnsubscribeValue( "<https://example.com/unsubscribe>, <mailto:[email protected]>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertThat(result).isEqualTo(MailtoUnsubscribeUri("mailto:[email protected]".toUri())) } @Test fun `get list unsubscribe url - should allow https if no mailto`() { val message = buildMimeMessageWithListUnsubscribeValue( "<https://example.com/unsubscribe>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertThat(result).isEqualTo(HttpsUnsubscribeUri("https://example.com/unsubscribe".toUri())) } @Test fun `get list unsubscribe url - should correctly parse uncommon urls`() { val message = buildMimeMessageWithListUnsubscribeValue( "<https://domain.example/one,two>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertThat(result).isEqualTo(HttpsUnsubscribeUri("https://domain.example/one,two".toUri())) } @Test fun `get list unsubscribe url - should ignore unsafe entries 1`() { val message = buildMimeMessageWithListUnsubscribeValue( "<http://example.com/unsubscribe>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertNull(result) } @Test fun `get list unsubscribe url - should ignore unsafe entries 2`() { val message = buildMimeMessageWithListUnsubscribeValue( "<http://example.com/unsubscribe>, <https://example.com/unsubscribe>" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertThat(result).isEqualTo(HttpsUnsubscribeUri("https://example.com/unsubscribe".toUri())) } @Test fun `get list unsubscribe url - should ignore empty`() { val message = buildMimeMessageWithListUnsubscribeValue( "" ) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertNull(result) } @Test fun `get list unsubscribe url - should ignore missing header`() { val message = MimeMessage() val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) assertNull(result) } private fun buildMimeMessageWithListUnsubscribeValue(value: String): MimeMessage { val message = MimeMessage() message.addHeader("List-Unsubscribe", value) return message } }
apache-2.0
3f7f62a17b5d971c8c05fad599ff2c1d
38.8
100
0.696377
4.853659
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractKotlinInplaceIntroducer.kt
3
3370
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.refactoring.introduce.inplace.AbstractInplaceIntroducer import com.intellij.refactoring.rename.inplace.InplaceRefactoring import com.intellij.util.ui.FormBuilder import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import java.awt.BorderLayout abstract class AbstractKotlinInplaceIntroducer<D : KtNamedDeclaration>( localVariable: D?, expression: KtExpression?, occurrences: Array<KtExpression>, @Nls title: String, project: Project, editor: Editor ) : AbstractInplaceIntroducer<D, KtExpression>(project, editor, expression, localVariable, occurrences, title, KotlinFileType.INSTANCE) { protected fun initFormComponents(init: FormBuilder.() -> Unit) { myWholePanel.layout = BorderLayout() with(FormBuilder.createFormBuilder()) { init() myWholePanel.add(panel, BorderLayout.CENTER) } } protected fun runWriteCommandAndRestart(action: () -> Unit) { myEditor.putUserData(InplaceRefactoring.INTRODUCE_RESTART, true) try { stopIntroduce(myEditor) myProject.executeWriteCommand(commandName, commandName, action) // myExprMarker was invalidated by stopIntroduce() myExprMarker = myExpr?.let { createMarker(it) } startInplaceIntroduceTemplate() } finally { myEditor.putUserData(InplaceRefactoring.INTRODUCE_RESTART, false) } } protected fun updateVariableName() { val currentName = inputName.quoteIfNeeded() if (currentName.isIdentifier()) { localVariable.setName(currentName) } } override fun getActionName(): String? = null override fun restoreExpression( containingFile: PsiFile, declaration: D, marker: RangeMarker, exprText: String? ): KtExpression? { if (exprText == null || !declaration.isValid) return null val leaf = containingFile.findElementAt(marker.startOffset) ?: return null leaf.getParentOfTypeAndBranch<KtProperty> { nameIdentifier }?.let { return it.replaced(KtPsiFactory(myProject).createDeclaration(exprText)) } val occurrenceExprText = (myExpr as? KtProperty)?.name ?: exprText return leaf .getNonStrictParentOfType<KtSimpleNameExpression>() ?.replaced(KtPsiFactory(myProject).createExpression(occurrenceExprText)) } override fun updateTitle(declaration: D?) = updateTitle(declaration, null) override fun saveSettings(declaration: D) { } }
apache-2.0
5d94dfacdbad3597999a4ed4b7d18e02
37.747126
158
0.726113
4.912536
false
false
false
false
JStege1206/AdventOfCode
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/utils/assembunny/Jnz.kt
1
1048
package nl.jstege.adventofcode.aoc2016.utils.assembunny import nl.jstege.adventofcode.aoccommon.utils.extensions.isCastableToInt import nl.jstege.adventofcode.aoccommon.utils.machine.Machine /** * A "Jump if not zero" instruction. When the first operand is equal to zero, * the program will jump the amount of instruction equal to the value of the * register in the second operand. * @author Jelle Stege */ class Jnz(operands: List<String>, machine: Machine) : Assembunny(operands, machine) { override fun invoke() { if (operands.size < 2) { throw IllegalArgumentException("Instruction 'jnz' was given too few arguments") } val check = if (operands[0].isCastableToInt()) { operands[0].toInt() } else { machine.registers[operands[0]] } val jmp = if (operands[1].isCastableToInt()) { operands[1].toInt() } else { machine.registers[operands[1]] } machine.ir += if (check == 0 || jmp == 0) 1 else jmp } }
mit
76584c7815d8226b350a4b80dcdb0f81
35.137931
91
0.640267
3.984791
false
false
false
false
KotlinNLP/SimpleDNN
examples/SumSignRelevanceTest.kt
1
6384
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ import com.kotlinnlp.simplednn.core.arrays.DistributionArray import com.kotlinnlp.simplednn.core.functionalities.activations.Softmax import com.kotlinnlp.simplednn.core.functionalities.updatemethods.learningrate.LearningRateMethod import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh import com.kotlinnlp.simplednn.core.functionalities.losses.SoftmaxCrossEntropyCalculator import com.kotlinnlp.simplednn.core.neuralprocessor.recurrent.RecurrentNeuralProcessor import com.kotlinnlp.simplednn.core.functionalities.outputevaluation.ClassificationEvaluation import com.kotlinnlp.simplednn.core.neuralnetwork.preset.SimpleRecurrentNeuralNetwork import traininghelpers.training.SequenceWithFinalOutputTrainer import traininghelpers.validation.SequenceWithFinalOutputEvaluator import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import utils.Corpus import utils.SequenceExampleWithFinalOutput fun main() { println("Start 'Sum Sign Relevance Test'") SumSignRelevanceTest(dataset = DatasetBuilder.build()).start() println("\nEnd.") } /** * */ object DatasetBuilder { /** * @return a dataset of examples of sequences */ fun build(): Corpus<SequenceExampleWithFinalOutput<DenseNDArray>> = Corpus( training = arrayListOf(*Array(size = 10000, init = { this.createExample() })), validation = arrayListOf(*Array(size = 1000, init = { this.createExample() })), test = arrayListOf(*Array(size = 100, init = { this.createExample() })) ) /** * @return an example containing a sequence of single features with a random value in {-1.0, 0.0, 1.0} and a gold * output which is the sign of the sum of the features (represented by a one hot encoder [0 = negative, * 1 = zero sign, 2 = positive]) */ private fun createExample(): SequenceExampleWithFinalOutput<DenseNDArray> { val features = arrayListOf(*Array(size = 10, init = { this.getRandomInput() })) val outputGoldIndex = Math.signum(features.sumByDouble { it[0] }) + 1 return SequenceExampleWithFinalOutput( sequenceFeatures = features, outputGold = DenseNDArrayFactory.oneHotEncoder(length = 3, oneAt = outputGoldIndex.toInt()) ) } /** * @return a [DenseNDArray] containing a single value within {-1.0, 0.0, 1.0} */ private fun getRandomInput(): DenseNDArray { val value = Math.round(Math.random() * 2.0 - 1.0).toDouble() return DenseNDArrayFactory.arrayOf(doubleArrayOf(value)) } } /** * */ class SumSignRelevanceTest(val dataset: Corpus<SequenceExampleWithFinalOutput<DenseNDArray>>) { /** * The number of examples to print. */ private val examplesToPrint: Int = 20 /** * */ private val neuralNetwork = SimpleRecurrentNeuralNetwork( inputSize = 1, hiddenSize = 10, hiddenActivation = Tanh, outputSize = 3, outputActivation = Softmax()) /** * Start the test. */ fun start() { this.train() this.printRelevance() } /** * Train the network on a dataset. */ private fun train() { println("\n-- TRAINING\n") SequenceWithFinalOutputTrainer( model = this.neuralNetwork, updateMethod = LearningRateMethod(learningRate = 0.01), lossCalculator = SoftmaxCrossEntropyCalculator, examples = this.dataset.training, epochs = 3, batchSize = 1, evaluator = SequenceWithFinalOutputEvaluator( model = this.neuralNetwork, examples = this.dataset.validation, outputEvaluationFunction = ClassificationEvaluation, verbose = false), verbose = false ).train() } /** * Print the relevance of each example of the dataset. */ private fun printRelevance() { println("\n-- PRINT RELEVANCE OF %d EXAMPLES\n".format(this.examplesToPrint)) var exampleIndex = 0 SequenceWithFinalOutputEvaluator( model = this.neuralNetwork, examples = this.dataset.test, outputEvaluationFunction = ClassificationEvaluation, saveContributions = true, afterEachEvaluation = { example, isCorrect, processor -> if (isCorrect && exampleIndex < this.examplesToPrint) { this.printSequenceRelevance(neuralProcessor = processor, example = example, exampleIndex = exampleIndex++) } }, verbose = false ).evaluate() } /** * Print the relevance of each input of the sequence. * * @param neuralProcessor the neural processor of the validation * @param example the validated sequence */ private fun printSequenceRelevance(neuralProcessor: RecurrentNeuralProcessor<DenseNDArray>, example: SequenceExampleWithFinalOutput<DenseNDArray>, exampleIndex: Int) { val sequenceRelevance = this.getSequenceRelevance( neuralProcessor = neuralProcessor, outputGold = example.outputGold ) println("EXAMPLE %d".format(exampleIndex + 1)) println("Gold: %d".format(example.outputGold.argMaxIndex() - 1)) println("Sequence (input | relevance):") (0 until sequenceRelevance.size).forEach { i -> println("\t%4.1f | %8.1f".format(example.sequenceFeatures[i][0], sequenceRelevance[i])) } println() } /** * @param neuralProcessor the neural processor of the validation * @param outputGold the gold output array * * @return an array containing the relevance for each input of the sequence in respect of the gold output */ private fun getSequenceRelevance(neuralProcessor: RecurrentNeuralProcessor<DenseNDArray>, outputGold: DenseNDArray): Array<Double> { val outcomesDistr = DistributionArray.oneHot(length = 3, oneAt = outputGold.argMaxIndex()) return Array( size = 10, init = { i -> neuralProcessor.calculateRelevance( stateFrom = i, stateTo = 9, relevantOutcomesDistribution = outcomesDistr).sum() } ) } }
mpl-2.0
a42c6bb9852d8e05bd51bc194c3785ee
32.07772
116
0.689693
4.430257
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKNestedClassAllUsages.1.kt
9
603
public class X(bar: String? = Outer.A.BAR) : Outer.A() { var next: Outer.A? = Outer.A() val myBar: String? = Outer.A.BAR init { Outer.A.BAR = "" Outer.A.foos() } fun foo(a: Outer.A) { val aa: Outer.A = a aa.bar = "" } fun getNextFun(): Outer.A? { return next } public override fun foo() { super<Outer.A>.foo() } companion object : Outer.A() { } } object O : Outer.A() { } fun X.bar(a: Outer.A = Outer.A()) { } fun Any.toA(): Outer.A? { return if (this is Outer.A) this as Outer.A else null }
apache-2.0
00388efd3d459fa0a908ed08578c3d65
14.868421
57
0.502488
2.885167
false
false
false
false
ksmirenko/telegram-proger-bot
src/main/java/progerbot/Highlighter.kt
1
8756
package progerbot import com.google.appengine.api.urlfetch.HTTPMethod import com.google.appengine.api.urlfetch.HTTPRequest import com.google.appengine.api.urlfetch.URLFetchServiceFactory import gui.ava.html.image.generator.HtmlImageGenerator import java.io.ByteArrayOutputStream import java.io.IOException import java.net.URL import java.net.URLDecoder import java.net.URLEncoder import java.util.* import java.util.concurrent.ConcurrentHashMap import javax.imageio.ImageIO public object Highlighter { private val PYGMENTS_URL = "http://pygments.simplabs.com/" private val CHARSET = "UTF-8" /** * HTML prefix containing styles for highlighted text. */ private val prefix : String /** * HTML suffix of a highlighted text. */ private val suffix : String /** * A strategy for converting HTML to images. */ private val imageObtainer : ImageObtainingStrategy = ApiImageObtainingStrategy() /** * Pairs (chat ID, language) containing information about chats that * have asked to highlight a file and not sent the document yet. * Warning: old requests are not removed if the user has not sent a file or a cancel message. */ private val pendingDocumentsUsers = ConcurrentHashMap<String, String>() /** * Chat IDs for which P2I has not prepared images yet. */ private val pendingP2IRequests = Collections.newSetFromMap(ConcurrentHashMap<String, Boolean>()) init { try { // loading token from locally stored file val prop = Properties() val inputStream = MainServlet::class.java. classLoader.getResourceAsStream("res.properties") prop.load(inputStream) prefix = prop.getProperty("json.highlightPrefix") suffix = prop.getProperty("json.highlightSuffix") } catch (e : IOException) { e.printStackTrace() prefix = "" suffix = "" } } /** * Handles text messages concerning code highlighting. * @param chatId User chat ID. * @param text Message content. * @return True, if successful, or false otherwise. */ public fun handleRequest(chatId : String, text : String) : Boolean { val splitMessage = text.split(" ".toRegex(), 3) when (splitMessage[0]) { "/code" -> { try { if (splitMessage.size < 3) { TelegramApi.sendText(chatId, "You should use the following format: /code <language> <code>") return true } return highlightCodeText(splitMessage[1], splitMessage[2], chatId) } catch (e : Exception) { e.printStackTrace(System.err) TelegramApi.sendText( chatId, "I couldn't proceed your request because of:\n${e.toString()}\nSorry for that." ) return false } } "/code_file" -> { if (splitMessage.size < 2) { TelegramApi.sendText(chatId, "Error: you didn't name the language!") return true } pendingDocumentsUsers.put(chatId, splitMessage[1]) TelegramApi.sendText( chatId, "All right, now send me the file." ) } "/code_file_cancel" -> { pendingDocumentsUsers.remove(chatId) TelegramApi.sendText( chatId, "OK, we won't highlight any files now." ) } } return true } /** * Handles the message with a document containing code for highlighting. * @param chatId User chat ID. * @param fileId File ID for downloading the file from Telegram server. * @return True, if successful, or false otherwise. */ public fun handleDocument(chatId : String, fileId : String) : Boolean { if (!pendingDocumentsUsers.containsKey(chatId)) { TelegramApi.sendText(chatId, "Why are you sending me files? I don't need them.") return true } val file = TelegramApi.getFile(fileId) ?: return false val path = file.file_path ?: return false val sourceCode = TelegramApi.downloadTextFile(path) val language = pendingDocumentsUsers[chatId] ?: return false return highlightCodeText(language, sourceCode, chatId) } /** * Sends the image prepared by Page2Images to the user. */ public fun handlePreparedImage(chatId : String, imageUrl : String) { if (pendingP2IRequests.contains(chatId)) { pendingP2IRequests.remove(chatId) TelegramApi.sendText(chatId, "Here you are:\n${URLDecoder.decode(imageUrl, CHARSET)}") } } private fun highlightCodeText(language : String, content : String, chatId : String) : Boolean { // creating and sending HTTP request to Pygments val pygmentsPost = HTTPRequest(URL(PYGMENTS_URL), HTTPMethod.POST) pygmentsPost.payload = "lang=$language&code=$content".toByteArray(CHARSET) val pygmentsResponse = URLFetchServiceFactory.getURLFetchService().fetch(pygmentsPost) if (pygmentsResponse.responseCode != 200) { Logger.println("Error: Could not pygmentize code for chat $chatId") return false } Logger.println("Pygmentized and stylized code: [${addStyles(pygmentsResponse.content.toString(CHARSET))}]") // obtaining image with colored code imageObtainer.getImageFromHtml( addStyles(pygmentsResponse.content.toString(CHARSET)), chatId ) return true } /** * Adds styles (colors) to pygmentized code. */ private fun addStyles(highlightedCode : String) = prefix + highlightedCode + suffix private abstract class ImageObtainingStrategy() { public abstract fun getImageFromHtml(htmlContent : String, chatId : String) : Boolean } /** * Generates images from HTML via external library. Much faster, but prohibited by GAE. */ private class LibraryImageObtainingStrategy() : ImageObtainingStrategy() { override fun getImageFromHtml(htmlContent : String, chatId : String) : Boolean { val imageGenerator = HtmlImageGenerator() imageGenerator.loadHtml(htmlContent) val baos = ByteArrayOutputStream() ImageIO.write(imageGenerator.bufferedImage, "png", baos) return TelegramApi.sendImage(chatId, baos.toByteArray()).responseCode == 200 } } /** * Obtains images from HTML via Page2Images REST API. */ private class ApiImageObtainingStrategy() : ImageObtainingStrategy() { private val P2I_URL = "http://api.page2images.com/html2image" private val P2I_CALLBACK_URL = "https://telegram-proger-bot.appspot.com/main" private val P2I_SCREEN = "&p2i_screen=320x240" private val apiKey : String init { // loading properties val prop = Properties() val inputStream = progerbot.MainServlet::class.java. classLoader.getResourceAsStream("auth.properties") prop.load(inputStream) apiKey = prop.getProperty("json.pagetoimagesApiKey") } // FIXME: '+' characters (and maybe some other) are not shown override fun getImageFromHtml(htmlContent : String, chatId : String) : Boolean { try { pendingP2IRequests.add(chatId) val p2iResponse = HttpRequests.simpleRequest( P2I_URL, HTTPMethod.POST, "p2i_html=${URLEncoder.encode(htmlContent, CHARSET)}&p2i_key=$apiKey&p2i_imageformat=jpg" + "&p2i_fullpage=0$P2I_SCREEN&p2i_callback=$P2I_CALLBACK_URL?p2i_token=$chatId" ) if (p2iResponse.responseCode != 200) { TelegramApi.sendText(chatId, "Oops, something went wrong when I tried to generate the image!") return false } Logger.println("P2I response: [${p2iResponse.content.toString(CHARSET)}]") TelegramApi.sendText(chatId, "Your code image is being prepared now.") return true } catch (e : Exception) { Logger.println(e) return false } } } }
apache-2.0
71a84b097da0704bd2b2c4fb17a7981b
38.981735
116
0.59582
4.758696
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/gautrain/GautrainTransitData.kt
1
5216
/* * GautrainTransitData.kt * * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.gautrain import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory import au.id.micolous.metrodroid.card.classic.ClassicSector import au.id.micolous.metrodroid.multi.Parcelable import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.* import au.id.micolous.metrodroid.transit.en1545.En1545FixedInteger import au.id.micolous.metrodroid.transit.ovc.OVChipIndex import au.id.micolous.metrodroid.transit.ovc.OVChipTransitData import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.NumberUtils private const val NAME = "Gautrain" private val CARD_INFO = CardInfo( name = NAME, locationId = R.string.location_gauteng, imageId = R.drawable.gautrain, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.SOUTH_AFRICA, keysRequired = true) private fun formatSerial(serial: Long) = NumberUtils.zeroPad(serial, 10) private fun getSerial(card: ClassicCard) = card[0,0].data.byteArrayToLong(0, 4) @Parcelize data class GautrainBalanceBlock(val mBalance: Int, val mTxn: Int, private val mTxnRefill: Int, private val mA: Int, private val mB: Int, private val mC: Int): Parcelable { companion object { fun parse(input: ImmutableByteArray): GautrainBalanceBlock = GautrainBalanceBlock( mA = input.getBitsFromBuffer(0, 30), mTxn = input.getBitsFromBuffer(30, 16), mB = input.getBitsFromBuffer(46, 12), mTxnRefill = input.getBitsFromBuffer(58, 16), mC = input.getBitsFromBuffer(74, 1), mBalance = input.getBitsFromBufferSigned(75, 16) xor 0x7fff.inv()) } } @Parcelize data class GautrainTransitData(private val mSerial: Long, override val trips: List<Trip>, override val subscriptions: List<GautrainSubscription>, private val mExpdate: Int, private val mBalances: List<GautrainBalanceBlock>, private val mIndex: OVChipIndex) : TransitData() { override val serialNumber get() = formatSerial(mSerial) override val cardName get() = NAME override val balance: TransitBalance? get() = TransitBalanceStored(GautrainLookup.parseCurrency(mBalances.maxBy { it.mTxn }?.mBalance ?: 0), En1545FixedInteger.parseDate(mExpdate, GautrainLookup.timeZone)) override fun getRawFields(level: RawLevel): List<ListItem>? = mBalances.mapIndexed { idx, bal -> ListItem("Bal $idx", bal.toString()) } + mIndex.getRawFields(level) } object GautrainTransitFactory : ClassicCardTransitFactory { override val allCards get() = listOf(CARD_INFO) override fun parseTransitIdentity(card: ClassicCard) = TransitIdentity( NAME, formatSerial(getSerial(card))) override fun parseTransitData(card: ClassicCard): GautrainTransitData { val index = OVChipIndex.parse(card[39].readBlocks(11, 4)) val transactions = (35..38).flatMap { sector -> (0..12 step 2).map { block -> card[sector].readBlocks(block, 2) } }.mapNotNull { GautrainTransaction.parse(it) } val trips = TransactionTripLastPrice.merge(transactions) return GautrainTransitData( mSerial = getSerial(card), trips = trips, mExpdate = card[0, 1].data.getBitsFromBuffer(88, 20), mBalances = listOf(card[39][9].data, card[39][10].data).map { GautrainBalanceBlock.parse(it) }, subscriptions = OVChipTransitData.getSubscriptions(card, index, GautrainSubscription.Companion::parse), mIndex = index) } private val GAU_HEADER = ImmutableByteArray.fromHex("b180000006b55c0013aee4") override fun earlyCheck(sectors: List<ClassicSector>) = sectors[0].readBlocks(1, 1).copyOfRange(0, 11) == GAU_HEADER override val earlySectors get() = 2 }
gpl-3.0
0b9996f049b2c3803d8f9a524b264b84
43.965517
119
0.666028
4.230333
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/SurroundingComponent.kt
6
1940
package org.jetbrains.plugins.notebooks.visualization.outputs.impl import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.ui.IdeBorderFactory import com.intellij.util.ui.GraphicsUtil import org.jetbrains.plugins.notebooks.visualization.outputs.NotebookOutputComponentWrapper import org.jetbrains.plugins.notebooks.visualization.outputs.getEditorBackground import org.jetbrains.plugins.notebooks.visualization.ui.registerEditorSizeWatcher import org.jetbrains.plugins.notebooks.visualization.ui.textEditingAreaWidth import java.awt.BorderLayout import java.awt.Dimension import java.awt.Insets import javax.swing.JPanel internal class SurroundingComponent private constructor(private val innerComponent: InnerComponent) : JPanel( BorderLayout()) { private var presetWidth = 0 init { border = IdeBorderFactory.createEmptyBorder(Insets(10, 0, 0, 0)) add(innerComponent, BorderLayout.CENTER) } fun fireResize() { this.firePropertyChange("preferredSize", null, preferredSize) } override fun updateUI() { super.updateUI() isOpaque = true background = getEditorBackground() } override fun getPreferredSize(): Dimension = super.getPreferredSize().also { it.width = presetWidth // No need to show anything for the empty component if (innerComponent.preferredSize.height == 0) { it.height = 0 } } companion object { @JvmStatic fun create( editor: EditorImpl, innerComponent: InnerComponent, ) = SurroundingComponent(innerComponent).also { registerEditorSizeWatcher(it) { it.presetWidth = editor.textEditingAreaWidth if (it.presetWidth == 0 && GraphicsUtil.isProjectorEnvironment()) { it.presetWidth = editor.contentSize.width } innerComponent.revalidate() } for (wrapper in NotebookOutputComponentWrapper.EP_NAME.extensionList) { wrapper.wrap(it) } } } }
apache-2.0
b542c0e92f2644429f41a524f53b9169
30.819672
109
0.744845
4.564706
false
false
false
false
jk1/intellij-community
tools/index-tools/src/org/jetbrains/index/stubs/StubsGenerator.kt
3
9491
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /** * @author traff */ package org.jetbrains.index.stubs import com.google.common.hash.HashCode import com.intellij.idea.IdeaTestApplication import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.WriteAction import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.impl.DebugUtil import com.intellij.psi.stubs.* import com.intellij.util.indexing.FileContentImpl import com.intellij.util.io.PersistentHashMap import junit.framework.TestCase import org.jetbrains.index.IndexGenerator import java.io.File import java.util.* /** * Generates stubs and stores them in one persistent hash map */ open class StubsGenerator(private val stubsVersion: String, private val stubsStorageFilePath: String) : IndexGenerator<SerializedStubTree>(stubsStorageFilePath) { private val serializationManager = SerializationManagerImpl(File("$stubsStorageFilePath.names")) fun buildStubsForRoots(roots: Collection<VirtualFile>) { try { buildIndexForRoots(roots) } finally { Disposer.dispose(serializationManager) writeStubsVersionFile(stubsStorageFilePath, stubsVersion) } } override fun getIndexValue(fileContent: FileContentImpl): SerializedStubTree? { val stub = buildStubForFile(fileContent, serializationManager) if (stub == null) { return null } val bytes = BufferExposingByteArrayOutputStream() serializationManager.serialize(stub, bytes) val file = fileContent.file val contentLength = if (file.fileType.isBinary) { -1 } else { fileContent.psiFileForPsiDependentIndex.textLength } return SerializedStubTree(bytes.internalBuffer, bytes.size(), stub, file.length, contentLength) } override fun createStorage(stubsStorageFilePath: String): PersistentHashMap<HashCode, SerializedStubTree> { return PersistentHashMap(File(stubsStorageFilePath + ".input"), HashCodeDescriptor.instance, StubTreeExternalizer()) } open fun buildStubForFile(fileContent: FileContentImpl, serializationManager: SerializationManagerImpl): Stub? { return ReadAction.compute<Stub, Throwable> { StubTreeBuilder.buildStubTree(fileContent) } } } fun writeStubsVersionFile(stubsStorageFilePath: String, stubsVersion: String) { FileUtil.writeToFile(File(stubsStorageFilePath + ".version"), stubsVersion) } fun mergeStubs(paths: List<String>, stubsFilePath: String, stubsFileName: String, projectPath: String, stubsVersion: String) { val app = IdeaTestApplication.getInstance() val project = ProjectManager.getInstance().loadAndOpenProject(projectPath)!! // we don't need a project here, but I didn't find a better way to wait until indices and components are initialized try { val stubExternalizer = StubTreeExternalizer() val storageFile = File(stubsFilePath, stubsFileName + ".input") if (storageFile.exists()) { storageFile.delete() } val storage = PersistentHashMap<HashCode, SerializedStubTree>(storageFile, HashCodeDescriptor.instance, stubExternalizer) val stringEnumeratorFile = File(stubsFilePath, stubsFileName + ".names") if (stringEnumeratorFile.exists()) { stringEnumeratorFile.delete() } val newSerializationManager = SerializationManagerImpl(stringEnumeratorFile) val map = HashMap<HashCode, Int>() println("Writing results to ${storageFile.absolutePath}") for (path in paths) { println("Reading stubs from $path") var count = 0 val fromStorageFile = File(path, stubsFileName + ".input") val fromStorage = PersistentHashMap<HashCode, SerializedStubTree>(fromStorageFile, HashCodeDescriptor.instance, stubExternalizer) val serializationManager = SerializationManagerImpl(File(path, stubsFileName + ".names")) try { fromStorage.processKeysWithExistingMapping( { key -> count++ val value = fromStorage.get(key) val stub = value.getStub(false, serializationManager) // re-serialize stub tree to correctly enumerate strings in the new string enumerator val bytes = BufferExposingByteArrayOutputStream() newSerializationManager.serialize(stub, bytes) val newStubTree = SerializedStubTree(bytes.internalBuffer, bytes.size(), null, value.byteContentLength, value.charContentLength) if (storage.containsMapping(key)) { if (newStubTree != storage.get(key)) { // TODO: why are they slightly different??? val s = storage.get(key).getStub(false, newSerializationManager) val bytes2 = BufferExposingByteArrayOutputStream() newSerializationManager.serialize(stub, bytes2) val newStubTree2 = SerializedStubTree(bytes2.internalBuffer, bytes2.size(), null, value.byteContentLength, value.charContentLength) TestCase.assertTrue(newStubTree == newStubTree2) // wtf!!! why are they equal now??? } map.put(key, map.get(key)!! + 1) } else { storage.put(key, newStubTree) map.put(key, 1) } true }) } finally { fromStorage.close() Disposer.dispose(serializationManager) } println("Items in ${fromStorageFile.absolutePath}: $count") } storage.close() Disposer.dispose(newSerializationManager) val total = map.size println("Total items in storage: $total") writeStubsVersionFile(stringEnumeratorFile.nameWithoutExtension, stubsVersion) for (i in 2..paths.size) { val count = map.entries.stream().filter({ e -> e.value == i }).count() println("Intersection between $i: ${"%.2f".format(if (total > 0) 100.0 * count / total else 0.0)}%") } } finally { ApplicationManager.getApplication().invokeAndWait(Runnable { ProjectManager.getInstance().closeProject(project) WriteAction.run<Throwable> { Disposer.dispose(project) Disposer.dispose(app) } }, ModalityState.NON_MODAL) } System.exit(0) } /** * Generates stubs for file content for different language levels returned by languageLevelIterator * and checks that they are all equal. */ abstract class LanguageLevelAwareStubsGenerator<T>(stubsVersion: String, stubsStorageFilePath: String) : StubsGenerator(stubsVersion, stubsStorageFilePath) { companion object { val FAIL_ON_ERRORS: Boolean = System.getenv("STUB_GENERATOR_FAIL_ON_ERRORS")?.toBoolean() ?: false } abstract fun languageLevelIterator(): Iterator<T> abstract fun applyLanguageLevel(level: T) abstract fun defaultLanguageLevel(): T override fun buildStubForFile(fileContent: FileContentImpl, serializationManager: SerializationManagerImpl): Stub? { var prevLanguageLevel: T? = null var prevStub: Stub? = null val iter = languageLevelIterator() try { for (languageLevel in iter) { applyLanguageLevel(languageLevel) // create new FileContentImpl, because it caches stub in user data val content = FileContentImpl(fileContent.file, fileContent.content) val stub = super.buildStubForFile(content, serializationManager) if (stub != null) { val bytes = BufferExposingByteArrayOutputStream() serializationManager.serialize(stub, bytes) if (prevStub != null) { try { check(stub, prevStub) } catch (e: AssertionError) { val msg = "Stubs are different for ${content.file.path} between Python versions $prevLanguageLevel and $languageLevel.\n" TestCase.assertEquals(msg, DebugUtil.stubTreeToString(stub), DebugUtil.stubTreeToString(prevStub)) TestCase.fail(msg + "But DebugUtil.stubTreeToString values of stubs are unfortunately equal.") } } } prevLanguageLevel = languageLevel prevStub = stub } applyLanguageLevel(defaultLanguageLevel()) return prevStub!! } catch (e: AssertionError) { if (FAIL_ON_ERRORS) { throw e } println("Can't generate universal stub for ${fileContent.file.path}") e.printStackTrace() return null } } } private fun check(stub: Stub, stub2: Stub) { TestCase.assertEquals(stub.stubType, stub2.stubType) val stubs = stub.childrenStubs val stubs2 = stub2.childrenStubs TestCase.assertEquals(stubs.size, stubs2.size) var i = 0 val len = stubs.size while (i < len) { check(stubs[i], stubs2[i]) ++i } }
apache-2.0
f10d7e90650a88cbc4e21b6c9f85605b
33.765568
143
0.672427
5.180677
false
false
false
false
evanchooly/kobalt
src/main/kotlin/com/beust/kobalt/app/remote/DependencyData.kt
1
4528
package com.beust.kobalt.app.remote import com.beust.kobalt.Args import com.beust.kobalt.api.IClasspathDependency import com.beust.kobalt.api.ProjectDescription import com.beust.kobalt.app.BuildFileCompiler import com.beust.kobalt.internal.JvmCompilerPlugin import com.beust.kobalt.internal.PluginInfo import com.beust.kobalt.internal.TaskManager import com.beust.kobalt.internal.build.BuildFile import com.beust.kobalt.maven.DependencyManager import com.beust.kobalt.maven.dependency.FileDependency import com.beust.kobalt.misc.KFiles import com.beust.kobalt.misc.KobaltExecutors import com.google.inject.Inject import java.io.File import java.nio.file.Paths class DependencyData @Inject constructor(val executors: KobaltExecutors, val dependencyManager: DependencyManager, val buildFileCompilerFactory: BuildFileCompiler.IFactory, val pluginInfo: PluginInfo, val taskManager: TaskManager) { fun dependenciesDataFor(buildFilePath: String, args: Args) : GetDependenciesData { val projectDatas = arrayListOf<ProjectData>() fun toDependencyData(d: IClasspathDependency, scope: String): DependencyData { val dep = dependencyManager.create(d.id) return DependencyData(d.id, scope, dep.jarFile.get().absolutePath) } fun allDeps(l: List<IClasspathDependency>) = dependencyManager.transitiveClosure(l) val buildFile = BuildFile(Paths.get(buildFilePath), "GetDependenciesCommand") val buildFileCompiler = buildFileCompilerFactory.create(listOf(buildFile), pluginInfo) val projectResult = buildFileCompiler.compileBuildFiles(args) val pluginDependencies = projectResult.pluginUrls.map { File(it.toURI()) }.map { FileDependency(it.absolutePath) } val allTasks = hashSetOf<TaskData>() projectResult.projects.forEach { project -> val compileDependencies = pluginDependencies.map { toDependencyData(it, "compile") } + allDeps(project.compileDependencies).map { toDependencyData(it, "compile") } + allDeps(project.compileProvidedDependencies).map { toDependencyData(it, "compile") } val testDependencies = allDeps(project.testDependencies).map { toDependencyData(it, "testCompile") } val pd = project.projectProperties.get(JvmCompilerPlugin.DEPENDENT_PROJECTS) val dependentProjects = if (pd != null) { @Suppress("UNCHECKED_CAST") (pd as List<ProjectDescription>).filter { it.project.name == project.name }.flatMap { it.dependsOn.map { it.name } } } else { emptyList() } // Separate resource from source directories val sources = project.sourceDirectories.partition { KFiles.isResource(it) } val tests = project.sourceDirectoriesTest.partition { KFiles.isResource(it) } val projectTasks = taskManager.tasksByNames(project).values().map { TaskData(it.name, it.doc, it.group) } allTasks.addAll(projectTasks) projectDatas.add(ProjectData(project.name, project.directory, dependentProjects, compileDependencies, testDependencies, sources.second.toSet(), tests.second.toSet(), sources.first.toSet(), tests.first.toSet(), projectTasks)) } return GetDependenciesData(projectDatas, allTasks, projectResult.taskResult.errorMessage) } ///// // The JSON payloads that this command uses. The IDEA plug-in (and any client of the server) needs to // use these same classes. // class DependencyData(val id: String, val scope: String, val path: String) data class TaskData(val name: String, val description: String, val group: String) { override fun toString() = name } class ProjectData(val name: String, val directory: String, val dependentProjects: List<String>, val compileDependencies: List<DependencyData>, val testDependencies: List<DependencyData>, val sourceDirs: Set<String>, val testDirs: Set<String>, val sourceResourceDirs: Set<String>, val testResourceDirs: Set<String>, val tasks: Collection<TaskData>) class GetDependenciesData(val projects: List<ProjectData> = emptyList(), val allTasks: Collection<TaskData> = emptySet(), val errorMessage: String?) }
apache-2.0
d15751a43b61cc5ef4d5afabc203d066
48.217391
114
0.683304
4.756303
false
true
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt
2
6179
package eu.kanade.tachiyomi.ui.setting import android.app.Activity import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import androidx.preference.PreferenceGroup import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.track.NoLoginTrackService import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.data.track.anilist.AnilistApi import eu.kanade.tachiyomi.data.track.bangumi.BangumiApi import eu.kanade.tachiyomi.data.track.myanimelist.MyAnimeListApi import eu.kanade.tachiyomi.data.track.shikimori.ShikimoriApi import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.ui.setting.track.TrackLoginDialog import eu.kanade.tachiyomi.ui.setting.track.TrackLogoutDialog import eu.kanade.tachiyomi.util.preference.add import eu.kanade.tachiyomi.util.preference.defaultValue import eu.kanade.tachiyomi.util.preference.iconRes import eu.kanade.tachiyomi.util.preference.infoPreference import eu.kanade.tachiyomi.util.preference.onClick import eu.kanade.tachiyomi.util.preference.preferenceCategory import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.util.system.openInBrowser import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.widget.preference.TrackerPreference import uy.kohesive.injekt.injectLazy import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsTrackingController : SettingsController(), TrackLoginDialog.Listener, TrackLogoutDialog.Listener { private val trackManager: TrackManager by injectLazy() private val sourceManager: SourceManager by injectLazy() override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.pref_category_tracking switchPreference { key = Keys.autoUpdateTrack titleRes = R.string.pref_auto_update_manga_sync defaultValue = true } preferenceCategory { titleRes = R.string.services trackPreference(trackManager.myAnimeList) { activity?.openInBrowser(MyAnimeListApi.authUrl(), trackManager.myAnimeList.getLogoColor()) } trackPreference(trackManager.aniList) { activity?.openInBrowser(AnilistApi.authUrl(), trackManager.aniList.getLogoColor()) } trackPreference(trackManager.kitsu) { val dialog = TrackLoginDialog(trackManager.kitsu, R.string.email) dialog.targetController = this@SettingsTrackingController dialog.showDialog(router) } trackPreference(trackManager.shikimori) { activity?.openInBrowser(ShikimoriApi.authUrl(), trackManager.shikimori.getLogoColor()) } trackPreference(trackManager.bangumi) { activity?.openInBrowser(BangumiApi.authUrl(), trackManager.bangumi.getLogoColor()) } infoPreference(R.string.tracking_info) } preferenceCategory { titleRes = R.string.enhanced_services trackPreference(trackManager.komga) { val acceptedSources = trackManager.komga.getAcceptedSources() val hasValidSourceInstalled = sourceManager.getCatalogueSources() .any { it::class.qualifiedName in acceptedSources } if (hasValidSourceInstalled) { trackManager.komga.loginNoop() updatePreference(trackManager.komga.id) } else { context.toast(R.string.tracker_komga_warning, Toast.LENGTH_LONG) } } infoPreference(R.string.enhanced_tracking_info) } } private inline fun PreferenceGroup.trackPreference( service: TrackService, crossinline login: () -> Unit ): TrackerPreference { return add( TrackerPreference(context).apply { key = Keys.trackUsername(service.id) titleRes = service.nameRes() iconRes = service.getLogo() iconColor = service.getLogoColor() onClick { if (service.isLogged) { if (service is NoLoginTrackService) { service.logout() updatePreference(service.id) } else { val dialog = TrackLogoutDialog(service) dialog.targetController = this@SettingsTrackingController dialog.showDialog(router) } } else { login() } } } ) } override fun onActivityResumed(activity: Activity) { super.onActivityResumed(activity) // Manually refresh OAuth trackers' holders updatePreference(trackManager.myAnimeList.id) updatePreference(trackManager.aniList.id) updatePreference(trackManager.shikimori.id) updatePreference(trackManager.bangumi.id) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.settings_tracking, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_tracking_help -> activity?.openInBrowser(HELP_URL) } return super.onOptionsItemSelected(item) } private fun updatePreference(id: Int) { val pref = findPreference(Keys.trackUsername(id)) as? TrackerPreference pref?.notifyChanged() } override fun trackLoginDialogClosed(service: TrackService) { updatePreference(service.id) } override fun trackLogoutDialogClosed(service: TrackService) { updatePreference(service.id) } } private const val HELP_URL = "https://tachiyomi.org/help/guides/tracking/"
apache-2.0
ca4b9cc046b4670a5c4ea3a9174a52ff
37.861635
106
0.665318
5.023577
false
false
false
false
JordanCarr/KotlinForAndroidDevelopers
app/src/main/java/com/jordan_carr/KWeather/data/ForecastRequest.kt
1
1721
/* * MIT License * * Copyright (c) 2017 Jordan Carr * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.jordan_carr.KWeather.data import com.google.gson.Gson import java.net.URL class ForecastRequest(val zipCode: String) { companion object { private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce" private val URL = "http://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=metric&cnt=7" private val COMPLETE_URL = "$URL&APPID=$APP_ID&q=" } fun execute(): ForecastResult { val forecastJsonStr = URL(COMPLETE_URL + zipCode).readText() return Gson().fromJson(forecastJsonStr, ForecastResult::class.java) } }
mit
f4c763c97d6c28a8dd706a84389a3d6f
40
110
0.737943
4.021028
false
false
false
false
airbnb/lottie-android
snapshot-tests/src/androidTest/java/com/airbnb/lottie/snapshots/tests/MarkersTestCase.kt
1
1631
package com.airbnb.lottie.snapshots.tests import com.airbnb.lottie.snapshots.SnapshotTestCase import com.airbnb.lottie.snapshots.SnapshotTestCaseContext import com.airbnb.lottie.snapshots.withDrawable class MarkersTestCase : SnapshotTestCase { override suspend fun SnapshotTestCaseContext.run() { withDrawable("Tests/Marker.json", "Marker", "startFrame") { drawable -> drawable.setMinAndMaxFrame("Marker A") drawable.frame = drawable.minFrame.toInt() } withDrawable("Tests/Marker.json", "Marker", "endFrame") { drawable -> drawable.setMinAndMaxFrame("Marker A") drawable.frame = drawable.maxFrame.toInt() } withDrawable("Tests/RGBMarker.json", "Marker", "->[Green, Blue)") { drawable -> drawable.setMinAndMaxFrame("Green Section", "Blue Section", false) drawable.frame = drawable.minFrame.toInt() } withDrawable("Tests/RGBMarker.json", "Marker", "->[Green, Blue]") { drawable -> drawable.setMinAndMaxFrame("Green Section", "Blue Section", true) drawable.frame = drawable.minFrame.toInt() } withDrawable("Tests/RGBMarker.json", "Marker", "[Green, Blue)<-") { drawable -> drawable.setMinAndMaxFrame("Green Section", "Blue Section", false) drawable.frame = drawable.maxFrame.toInt() } withDrawable("Tests/RGBMarker.json", "Marker", "[Green, Blue]<-") { drawable -> drawable.setMinAndMaxFrame("Green Section", "Blue Section", true) drawable.frame = drawable.maxFrame.toInt() } } }
apache-2.0
eb64bb7594e35a3c9a9532fd482e1f2f
40.846154
87
0.641937
4.493113
false
true
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/presentation/screen/search/SearchFragment.kt
1
4248
package blue.aodev.animeultimetv.presentation.screen.search import android.os.Bundle import android.support.v17.leanback.widget.* import android.support.v4.content.ContextCompat import android.view.View import blue.aodev.animeultimetv.R import blue.aodev.animeultimetv.domain.model.AnimeSummary import blue.aodev.animeultimetv.domain.AnimeRepository import blue.aodev.animeultimetv.utils.extensions.fromBgToUi import blue.aodev.animeultimetv.presentation.screen.animedetails.AnimeDetailsActivity import blue.aodev.animeultimetv.presentation.application.MyApplication import blue.aodev.animeultimetv.presentation.common.AnimeCardPresenter import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject class SearchFragment : android.support.v17.leanback.app.SearchFragment(), android.support.v17.leanback.app.SearchFragment.SearchResultProvider { @Inject lateinit var animeRepository: AnimeRepository private val rowsAdapter = ArrayObjectAdapter(ListRowPresenter()) private lateinit var animeAdapter: ArrayObjectAdapter private var query = "" private var hasResults = false private var currentSearch: Disposable? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MyApplication.graph.inject(this) animeAdapter = ArrayObjectAdapter(AnimeCardPresenter.default(activity)) setSearchResultProvider(this) setOnItemViewClickedListener { _, item, _, _ -> if (item is AnimeSummary) { showAnimeDetails(item) } } } override fun onStart() { super.onStart() updateVerticalOffset() setupSearchOrb() } override fun getResultsAdapter(): ObjectAdapter { return rowsAdapter } override fun onQueryTextChange(newQuery: String): Boolean { search(newQuery) return true } override fun onQueryTextSubmit(query: String): Boolean { search(query) return true } private fun search(query: String) { if (query == this.query) return this.query = query if (query.length < 2) { clearSearchResults() return } currentSearch?.dispose() currentSearch = animeRepository.search(query) .fromBgToUi() .subscribeBy( onNext = { onSearchResult(it) }, onError = { onSearchResult(emptyList()) } ) } private fun onSearchResult(results: List<AnimeSummary>) { animeAdapter.clear() hasResults = results.isNotEmpty() val row = if (hasResults) { animeAdapter.addAll(0, results) ListRow(animeAdapter) } else { val header = HeaderItem(getString(R.string.search_noResults, query)) ListRow(header, animeAdapter) } rowsAdapter.clear() rowsAdapter.add(row) updateVerticalOffset() } private fun clearSearchResults() { rowsAdapter.clear() } fun hasResults(): Boolean { return hasResults } fun focusOnSearch() { view!!.findViewById<View>(R.id.lb_search_bar).requestFocus() } private fun updateVerticalOffset() { // Override the vertical offset. Not really pretty. val offsetResId = if (!hasResults()) { R.dimen.searchFragment_rowMarginTop_withHeader } else { R.dimen.searchFragment_rowMarginTop_withoutHeader } rowsFragment.verticalGridView.windowAlignmentOffset = resources.getDimensionPixelSize(offsetResId) } private fun showAnimeDetails(anime: AnimeSummary) { val intent = AnimeDetailsActivity.getIntent(activity, anime) activity.startActivity(intent) } private fun setupSearchOrb() { val defaultColor = ContextCompat.getColor(activity, R.color.searchOrb_default) val brightColor = ContextCompat.getColor(activity, R.color.searchOrb_bright) val orbColors = SearchOrbView.Colors(defaultColor, brightColor) setSearchAffordanceColors(orbColors) setSearchAffordanceColorsInListening(orbColors) } }
mit
993029dbc0d912d35726f3fe8c00693f
30.947368
86
0.679379
4.928074
false
false
false
false
BlueHuskyStudios/BHToolbox
BHToolbox/src/org/bh/tools/serialization/SerializationUtils.kt
1
2398
package org.bh.tools.serialization import org.bh.tools.util.containsIgnoreCase import org.bh.tools.util.plus import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FileOutputStream import java.util.logging.Level import java.util.logging.Logger /** * Copyright BHStudios ©2016 BH-1-PS. Made for BH Tic Tac Toe IntelliJ Project. * * Constants and static methods used for saving in a Blue Husky way * * @author Ben Leggiero * @since 2016-10-09 */ @Suppress("unused") class SerializationUtilsWrapper { companion object SerializationUtils { val SANDBOX_DIR_STRING: String val COMPANY_SANDBOX_NAME = "Blue Husky" val SANDBOX_DIR_FILE: File init { SANDBOX_DIR_STRING = (if (System.getProperty("os.name").containsIgnoreCase("windows")) System.getenv("APPDATA") else System.getProperty("java.io.tmpdir") ) + "\\$COMPANY_SANDBOX_NAME\\" SANDBOX_DIR_FILE = File(SANDBOX_DIR_STRING) } fun createSaveDirFor(programName: CharSequence, saveFileName: CharSequence): String = SANDBOX_DIR_STRING + programName + "\\" + saveFileName fun saveFileFor(programName: CharSequence, saveFileName: CharSequence): File = File(SANDBOX_DIR_FILE, programName + "\\" + saveFileName) fun createOutputStreamFor(programName: CharSequence, saveFileName: CharSequence): FileOutputStream { val outputFile = saveFileFor(programName, saveFileName) outputFile.parentFile.mkdirs() outputFile.createNewFile() try { return FileOutputStream(outputFile) } catch (ex: FileNotFoundException) { Logger.getLogger(SerializationUtils::class.java.name).log(Level.SEVERE, "Impossible FileNotFound exception", ex) throw AccessDeniedException(outputFile, reason = "The file I just made wasn't found... Somehow. Perhaps I have write but not read permission?") } } fun createInputStreamFor(programName: CharSequence, fileName: CharSequence): FileInputStream = FileInputStream(saveFileFor(programName, fileName)) } }
gpl-3.0
36a324aec9527aa2259a5bb789610e94
38.661017
128
0.631206
4.737154
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/translations/identifiers/ReferenceTranslationIdentifier.kt
1
2065
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n.translations.identifiers import com.demonwav.mcdev.i18n.translations.Translation import com.intellij.codeInsight.completion.CompletionUtilCore import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiField import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiModifier import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.impl.source.PsiClassReferenceType import com.intellij.psi.search.GlobalSearchScope class ReferenceTranslationIdentifier : TranslationIdentifier<PsiReferenceExpression>() { override fun identify(element: PsiReferenceExpression): Translation? { val reference = element.resolve() val statement = element.parent if (reference is PsiField) { val scope = GlobalSearchScope.allScope(element.project) val stringClass = JavaPsiFacade.getInstance(element.project).findClass("java.lang.String", scope) ?: return null val isConstant = reference.hasModifierProperty(PsiModifier.STATIC) && reference.hasModifierProperty(PsiModifier.FINAL) val type = reference.type as? PsiClassReferenceType ?: return null val resolved = type.resolve() ?: return null if (isConstant && (resolved.isEquivalentTo(stringClass) || resolved.isInheritor(stringClass, true))) { val referenceElement = reference.initializer as? PsiLiteral ?: return null val result = identify(element.project, element, statement, referenceElement) return result?.copy( key = result.key.replace(CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED, ""), varKey = result.varKey.replace(CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED, "") ) } } return null } override fun elementClass(): Class<PsiReferenceExpression> { return PsiReferenceExpression::class.java } }
mit
55337ddf2fc1cddf832e61c866a96010
41.142857
130
0.709443
4.952038
false
false
false
false
Flocksserver/Androidkt-CleanArchitecture-Template
app/src/main/java/de/flocksserver/androidkt_cleanarchitecture_template/model/mapper/BaseMapperMVM.kt
1
996
package de.flocksserver.androidkt_cleanarchitecture_template.model.mapper import java.util.ArrayList /** * Created by marcel on 27.07.17. */ abstract class BaseMapperMVM<ViewModel, Model> { abstract fun transformMtoVM(model: Model?): ViewModel? fun transformMtoVM(collection: List<Model>?): ArrayList<ViewModel> { val list = ArrayList<ViewModel>() var model: ViewModel? for (entity in collection!!) { model = transformMtoVM(entity) if (model != null) { list.add(model) } } return list } abstract fun transformVMtoM(viewModel: ViewModel?): Model? fun transformVMtoM(collection: List<ViewModel>?): ArrayList<Model> { val list = ArrayList<Model>() var model: Model? for (entity in collection!!) { model = transformVMtoM(entity) if (model != null) { list.add(model) } } return list } }
apache-2.0
e0158edfd430e234a5c30ac09f186e49
26.694444
73
0.588353
4.274678
false
false
false
false
mdanielwork/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/BreakpointsStatisticsCollector.kt
4
3185
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger.impl.breakpoints import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator.ensureProperKey import com.intellij.internal.statistic.utils.getCountingUsage import com.intellij.openapi.application.ReadAction import com.intellij.openapi.project.Project import com.intellij.xdebugger.breakpoints.SuspendPolicy import com.intellij.xdebugger.breakpoints.XLineBreakpoint import com.intellij.xdebugger.impl.XDebuggerManagerImpl import com.intellij.xdebugger.impl.XDebuggerUtilImpl /** * @author egor */ class BreakpointsStatisticsCollector : ProjectUsagesCollector() { override fun getGroupId(): String = "statistics.debugger.breakpoints" override fun getUsages(project: Project): MutableSet<UsageDescriptor> { return ReadAction.compute<MutableSet<UsageDescriptor>, Exception> { val breakpointManager = XDebuggerManagerImpl.getInstance(project).breakpointManager as XBreakpointManagerImpl val res = XBreakpointUtil.breakpointTypes() .filter { it.isSuspendThreadSupported() } .filter { breakpointManager.getBreakpointDefaults(it).getSuspendPolicy() != it.getDefaultSuspendPolicy() } .map { UsageDescriptor( ensureProperKey("not.default.suspend.${breakpointManager.getBreakpointDefaults(it).getSuspendPolicy()}.${it.getId()}")) } .toMutableSet() if (breakpointManager.allGroups.isNotEmpty()) { res.add(UsageDescriptor("using.groups")) } val breakpoints = breakpointManager.allBreakpoints.filter { !breakpointManager.isDefaultBreakpoint(it) } res.add(getCountingUsage("total", breakpoints.size)) val disabled = breakpoints.count { !it.isEnabled() } if (disabled > 0) { res.add(getCountingUsage("total.disabled", disabled)) } val nonSuspending = breakpoints.count { it.getSuspendPolicy() == SuspendPolicy.NONE } if (nonSuspending > 0) { res.add(getCountingUsage("total.non.suspending", nonSuspending)) } if (breakpoints.any { !XDebuggerUtilImpl.isEmptyExpression(it.getConditionExpression()) }) { res.add(UsageDescriptor("using.condition")) } if (breakpoints.any { !XDebuggerUtilImpl.isEmptyExpression(it.getLogExpressionObject()) }) { res.add(UsageDescriptor("using.log.expression")) } if (breakpoints.any { it is XLineBreakpoint<*> && it.isTemporary }) { res.add(UsageDescriptor("using.temporary")) } if (breakpoints.any { breakpointManager.dependentBreakpointManager.isMasterOrSlave(it) }) { res.add(UsageDescriptor("using.dependent")) } if (breakpoints.any { it.isLogMessage() }) { res.add(UsageDescriptor("using.log.message")) } if (breakpoints.any { it.isLogStack() }) { res.add(UsageDescriptor("using.log.stack")) } res } } }
apache-2.0
62a201dccc0d8398531bea090fc94607
38.825
140
0.724333
4.563037
false
false
false
false
songful/PocketHub
app/src/main/java/com/github/pockethub/android/ui/item/news/IssueCommentEventItem.kt
1
1958
package com.github.pockethub.android.ui.item.news import android.text.SpannableStringBuilder import android.text.TextUtils import android.view.View import androidx.text.bold import androidx.text.buildSpannedString import com.github.pockethub.android.core.issue.IssueUtils import com.github.pockethub.android.ui.view.OcticonTextView import com.github.pockethub.android.util.AvatarLoader import com.meisolsson.githubsdk.model.GitHubComment import com.meisolsson.githubsdk.model.GitHubEvent import com.meisolsson.githubsdk.model.payload.IssueCommentPayload import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.news_item.* class IssueCommentEventItem( avatarLoader: AvatarLoader, gitHubEvent: GitHubEvent ) : NewsItem(avatarLoader, gitHubEvent) { override fun bind(holder: ViewHolder, position: Int) { super.bind(holder, position) holder.tv_event_icon.text = OcticonTextView.ICON_ISSUE_COMMENT val payload = gitHubEvent.payload() as IssueCommentPayload? val details = buildSpannedString { appendComment(this, payload?.comment()) } if (TextUtils.isEmpty(details)) { holder.tv_event_details.visibility = View.GONE } else { holder.tv_event_details.text = details } holder.tv_event.text = buildSpannedString { boldActor(this, gitHubEvent) append(" commented on ") bold { val issue = payload?.issue() append("${if (IssueUtils.isPullRequest(issue)) { "pull request" } else { "issue" }} ${issue?.number()}") } append(" on ") boldRepo(this, gitHubEvent) } } private fun appendComment(details: SpannableStringBuilder, comment: GitHubComment?) { appendText(details, comment?.body()) } }
apache-2.0
3136679450916f476467a381ccb1c592
33.350877
89
0.665475
4.695444
false
false
false
false
iSoron/uhabits
uhabits-android/src/test/java/org/isoron/uhabits/BaseAndroidJVMTest.kt
1
2312
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits import com.nhaarman.mockitokotlin2.spy import org.isoron.uhabits.core.commands.CommandRunner import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.models.memory.MemoryModelFactory import org.isoron.uhabits.core.tasks.SingleThreadTaskRunner import org.isoron.uhabits.core.test.HabitFixtures import org.isoron.uhabits.core.utils.DateUtils.Companion.setFixedLocalTime import org.isoron.uhabits.core.utils.DateUtils.Companion.setStartDayOffset import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) open class BaseAndroidJVMTest { private lateinit var habitList: HabitList protected lateinit var fixtures: HabitFixtures private lateinit var modelFactory: MemoryModelFactory private lateinit var taskRunner: SingleThreadTaskRunner private lateinit var commandRunner: CommandRunner @Before open fun setUp() { val fixedLocalTime = 1422172800000L setFixedLocalTime(fixedLocalTime) setStartDayOffset(0, 0) modelFactory = MemoryModelFactory() habitList = spy(modelFactory.buildHabitList()) fixtures = HabitFixtures(modelFactory, habitList) taskRunner = SingleThreadTaskRunner() commandRunner = CommandRunner(taskRunner) } @After fun tearDown() { setFixedLocalTime(null) setStartDayOffset(0, 0) } @Test fun nothing() { } }
gpl-3.0
31b183afd7a2dd63f9a69102e4cbacba
35.109375
78
0.758546
4.360377
false
true
false
false
JetBrains/spek
spek-runtime/src/commonMain/kotlin/org/spekframework/spek2/runtime/Executor.kt
1
7419
package org.spekframework.spek2.runtime import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.spekframework.spek2.dsl.Skip import org.spekframework.spek2.runtime.execution.ExecutionListener import org.spekframework.spek2.runtime.execution.ExecutionRequest import org.spekframework.spek2.runtime.execution.ExecutionResult import org.spekframework.spek2.runtime.scope.GroupScopeImpl import org.spekframework.spek2.runtime.scope.ScopeImpl import org.spekframework.spek2.runtime.scope.TestScopeImpl import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext class Executor { fun execute(request: ExecutionRequest, concurrency: Int) { val runner = TaskRunner(concurrency) request.executionListener.executionStart() val handles = request.roots.map { runner.runTask { execute(it, request.executionListener) } } // wait for tasks handles.forEach { handle -> try { handle.await() } catch (e: Throwable) { println("An error has occurred: ${e.message}") } } request.executionListener.executionFinish() } private suspend fun execute(scope: ScopeImpl, listener: ExecutionListener): ExecutionResult? { if (scope.skip is Skip.Yes) { scopeIgnored(scope, scope.skip.reason, listener) return null } else { scopeExecutionStarted(scope, listener) suspend fun finalize(result: ExecutionResult) { val actualResult = try { when (scope) { is GroupScopeImpl -> scope.invokeAfterGroupFixtures(false) is TestScopeImpl -> scope.invokeAfterTestFixtures() } result } catch (e: Throwable) { ExecutionResult.Failure(e) } scope.after(actualResult.toPublicExecutionResult()) if (actualResult is ExecutionResult.Failure) { throw actualResult.cause } } val scopeCoroutineContext: CoroutineContext = EmptyCoroutineContext val result = executeSafely(scopeCoroutineContext, { finalize(it) }) { when (scope) { is GroupScopeImpl -> { withContext(scopeCoroutineContext) { scope.before() scope.invokeBeforeGroupFixtures(false) var failed = false for (it in scope.getChildren()) { if (failed) { scopeIgnored(it, "Previous failure detected, skipping.", listener) continue } val result = execute(it, listener) if (scope.failFast && it is TestScopeImpl && result is ExecutionResult.Failure) { failed = true } } } } is TestScopeImpl -> { val exception = withContext(scopeCoroutineContext) { val job = async { scope.before() scope.invokeBeforeTestFixtures() scope.execute() } if (scope.timeout == 0L) { try { job.await() null } catch (e: Throwable) { e } } else { val timedExecutionResult = withTimeoutOrNull(scope.timeout) { try { job.await() TimedExecutionResult.Success } catch (e: Throwable) { TimedExecutionResult.Failed(e) } } if (timedExecutionResult == null) { // test may still be running, cancel it! job.cancel() TestScopeTimeoutException(scope) } else { when (timedExecutionResult) { is TimedExecutionResult.Failed -> timedExecutionResult.exception is TimedExecutionResult.Success -> null else -> throw AssertionError("Unsupported TimedExecutionResult: $timedExecutionResult") } } } } if (exception != null) { throw exception } } } } scopeExecutionFinished(scope, result, listener) return result } } private sealed class TimedExecutionResult { object Success : TimedExecutionResult() class Failed(val exception: Throwable) : TimedExecutionResult() } private class TestScopeTimeoutException(scopeImpl: TestScopeImpl) : Throwable( "Execution of test ${scopeImpl.path.name} has timed out!" ) private suspend fun executeSafely(coroutineContext: CoroutineContext, finalize: suspend (ExecutionResult) -> Unit, block: suspend () -> Unit): ExecutionResult { val result = try { block() ExecutionResult.Success } catch (e: Throwable) { ExecutionResult.Failure(e) } // failures here will replace execution result return try { withContext(coroutineContext) { finalize(result) } result } catch (e: Throwable) { ExecutionResult.Failure(e) } } private fun scopeExecutionStarted(scope: ScopeImpl, listener: ExecutionListener) = when (scope) { is GroupScopeImpl -> listener.groupExecutionStart(scope) is TestScopeImpl -> listener.testExecutionStart(scope) } private fun scopeExecutionFinished(scope: ScopeImpl, result: ExecutionResult, listener: ExecutionListener) = when (scope) { is GroupScopeImpl -> listener.groupExecutionFinish(scope, result) is TestScopeImpl -> listener.testExecutionFinish(scope, result) } private fun scopeIgnored(scope: ScopeImpl, reason: String?, listener: ExecutionListener) = when (scope) { is GroupScopeImpl -> listener.groupIgnored(scope, reason) is TestScopeImpl -> listener.testIgnored(scope, reason) } } expect fun doRunBlocking(block: suspend CoroutineScope.() -> Unit)
bsd-3-clause
af2e3ffb399d1f6f0d174efe9ae67160
39.763736
164
0.501011
6.341026
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinHighLevelTypeArgumentInfoHandler.kt
2
5413
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.parameterInfo import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtTypeAliasSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtTypeParameterSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters import org.jetbrains.kotlin.analysis.api.types.KtClassErrorType import org.jetbrains.kotlin.analysis.api.types.KtClassType import org.jetbrains.kotlin.analysis.api.types.KtFlexibleType import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector /** * Presents type argument info for class type references (e.g., property type in declaration, base class in super types list). */ class KotlinHighLevelClassTypeArgumentInfoHandler : KotlinHighLevelTypeArgumentInfoHandlerBase() { override fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? { val typeReference = argumentList.parentOfType<KtTypeReference>() ?: return null val ktType = typeReference.getKtType() as? KtClassType ?: return null return when (ktType) { is KtNonErrorClassType -> listOfNotNull(ktType.expandedClassSymbol as? KtNamedClassOrObjectSymbol) is KtClassErrorType -> { ktType.candidateClassSymbols.mapNotNull { candidateSymbol -> when (candidateSymbol) { is KtClassOrObjectSymbol -> candidateSymbol is KtTypeAliasSymbol -> candidateSymbol.expandedType.expandedClassSymbol else -> null } as? KtNamedClassOrObjectSymbol } } } } override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java) } /** * Presents type argument info for function calls (including constructor calls). */ class KotlinHighLevelFunctionTypeArgumentInfoHandler : KotlinHighLevelTypeArgumentInfoHandlerBase() { override fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? { val callElement = argumentList.parentOfType<KtCallElement>() ?: return null // A call element may not be syntactically complete (e.g., missing parentheses: `foo<>`). In that case, `callElement.resolveCall()` // will NOT return a KtCall because there is no FirFunctionCall there. We find the symbols using the callee name instead. val reference = callElement.calleeExpression?.references?.singleOrNull() as? KtSimpleNameReference ?: return null val explicitReceiver = callElement.getQualifiedExpressionForSelector()?.receiverExpression val fileSymbol = callElement.containingKtFile.getFileSymbol() val symbols = reference.resolveToSymbols() .filterIsInstance<KtSymbolWithTypeParameters>() .filter { filterCandidate(it, callElement, fileSymbol, explicitReceiver) } // Multiple overloads may have the same type parameters (see Overloads.kt test), so we select the distinct ones. return symbols.distinctBy { buildPresentation(fetchCandidateInfo(it), -1).first } } override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java) } abstract class KotlinHighLevelTypeArgumentInfoHandlerBase : AbstractKotlinTypeArgumentInfoHandler() { protected abstract fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? override fun fetchCandidateInfos(argumentList: KtTypeArgumentList): List<CandidateInfo>? { analyze(argumentList) { val parameterOwners = findParameterOwners(argumentList) ?: return null return parameterOwners.map { fetchCandidateInfo(it) } } } protected fun KtAnalysisSession.fetchCandidateInfo(parameterOwner: KtSymbolWithTypeParameters): CandidateInfo { return CandidateInfo(parameterOwner.typeParameters.map { fetchTypeParameterInfo(it) }) } private fun KtAnalysisSession.fetchTypeParameterInfo(parameter: KtTypeParameterSymbol): TypeParameterInfo { val upperBounds = parameter.upperBounds.map { val isNullableAnyOrFlexibleAny = if (it is KtFlexibleType) { it.lowerBound.isAny && !it.lowerBound.isMarkedNullable && it.upperBound.isAny && it.upperBound.isMarkedNullable } else { it.isAny && it.isMarkedNullable } val renderedType = it.render(KtTypeRendererOptions.SHORT_NAMES) UpperBoundInfo(isNullableAnyOrFlexibleAny, renderedType) } return TypeParameterInfo(parameter.name.asString(), parameter.isReified, parameter.variance, upperBounds) } }
apache-2.0
525ecdbf7136c3287cc04461ff616555
57.215054
158
0.75448
5.333005
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt
1
11479
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInspection.* import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.CodeStyleSettingsManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.isComma import org.jetbrains.kotlin.idea.util.isLineBreak import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import javax.swing.JComponent import kotlin.properties.Delegates class TrailingCommaInspection( @JvmField var addCommaWarning: Boolean = false ) : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() { override val recursively: Boolean = false private var useTrailingComma by Delegates.notNull<Boolean>() override fun process(trailingCommaContext: TrailingCommaContext) { val element = trailingCommaContext.ktElement val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element) when (trailingCommaContext.state) { TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> { checkCommaPosition(element) checkLineBreaks(element) } else -> Unit } checkTrailingComma(trailingCommaContext) } private fun checkLineBreaks(commaOwner: KtElement) { val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) if (first?.nextLeaf(true)?.isLineBreak() == false) { first.nextSibling?.let { registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION) } } val last = TrailingCommaHelper.elementAfterLastElement(commaOwner) if (last?.prevLeaf(true)?.isLineBreak() == false) { registerProblemForLineBreak( commaOwner, last, if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } } private fun checkCommaPosition(commaOwner: KtElement) { for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) { reportProblem( invalidComma, KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"), KotlinBundle.message("inspection.trailing.comma.fix.comma.position") ) } } private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) { val commaOwner = trailingCommaContext.ktElement val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return when (trailingCommaContext.state) { TrailingCommaState.MISSING -> { if (!trailingCommaAllowedInModule(commaOwner)) return reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"), if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } TrailingCommaState.REDUNDANT -> { reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, checkTrailingCommaSettings = false, ) } else -> Unit } } private fun reportProblem( commaOrElement: PsiElement, @InspectionMessage message: String, @IntentionFamilyName fixMessage: String, highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING, checkTrailingCommaSettings: Boolean = true, ) { val commaOwner = commaOrElement.parent as KtElement // case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list val problemOwner = commonParent(commaOwner, commaOrElement) val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemOwner, message, highlightTypeWithAppliedCondition, commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset), createQuickFix(fixMessage, commaOwner), ) } } private fun registerProblemForLineBreak( commaOwner: KtElement, elementForTextRange: PsiElement, highlightType: ProblemHighlightType, ) { val problemElement = commonParent(commaOwner, elementForTextRange) val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemElement, KotlinBundle.message("inspection.trailing.comma.missing.line.break"), highlightTypeWithAppliedCondition, TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset), createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner), ) } } private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement = PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange) ?: throw KotlinExceptionWithAttachments("Common parent not found") .withPsiAttachment("commaOwner", commaOwner) .withAttachment("commaOwnerRange", commaOwner.textRange) .withPsiAttachment("elementForTextRange", elementForTextRange) .withAttachment("elementForTextRangeRange", elementForTextRange.textRange) .withPsiAttachment("parent", commaOwner.parent) .withAttachment("parentRange", commaOwner.parent.textRange) private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when { isUnitTestMode() -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING condition -> this else -> ProblemHighlightType.INFORMATION } private fun createQuickFix( @IntentionFamilyName fixMessage: String, commaOwner: KtElement, ): LocalQuickFix = ReformatTrailingCommaFix(commaOwner, fixMessage) private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange get() { val textRange = textRange if (isComma) return textRange return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let { TextRange.create(it - 1, it).intersection(textRange) } ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset) } } override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"), this, "addCommaWarning", ) class ReformatTrailingCommaFix(commaOwner: KtElement, @IntentionFamilyName private val fixMessage: String) : LocalQuickFix { val commaOwnerPointer = commaOwner.createSmartPointer() override fun getFamilyName(): String = fixMessage override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val element = commaOwnerPointer.element ?: return val range = createFormatterTextRange(element) val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile)) settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true CodeStyle.doWithTemporarySettings(project, settings, Runnable { CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset) }) } private fun createFormatterTextRange(commaOwner: KtElement): TextRange { val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner return TextRange.create(startElement.startOffset, endElement.endOffset) } override fun getFileModifierForPreview(target: PsiFile): FileModifier? { val element = commaOwnerPointer.element ?: return null return ReformatTrailingCommaFix(PsiTreeUtil.findSameElementInCopy(element, target), fixMessage) } } }
apache-2.0
5ccd60f5ecf13844ad23f6121740d622
50.707207
158
0.681331
6.293311
false
false
false
false
paplorinc/intellij-community
java/java-impl/src/com/intellij/lang/jvm/actions/actionsGrouping.kt
2
905
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.jvm.actions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.application.ApplicationManager internal fun List<IntentionAction>.groupActionsByType(): List<IntentionAction> { if (ApplicationManager.getApplication().isUnitTestMode) { return this } val groupableActions = filterIsInstance<JvmGroupIntentionAction>() val result = minus(groupableActions).toMutableList() val typeActions = groupableActions.groupBy { it.actionGroup } for ((type, actions) in typeActions) { result += if (actions.size == 1) { actions[0] } else { JvmClassIntentionActionGroup(actions, type, JavaLanguage.INSTANCE) } } return result }
apache-2.0
f230f41049016462d115605aefc5f48f
36.708333
140
0.760221
4.393204
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/misc/EmailAddress.kt
1
861
package backend.model.misc import backend.exceptions.DomainException import org.apache.commons.validator.routines.EmailValidator import org.hibernate.validator.constraints.Email import javax.persistence.Embeddable @Embeddable class EmailAddress() { @Email lateinit var value: String constructor(email: String) : this() { val validator = EmailValidator.getInstance() if (!validator.isValid(email)) throw DomainException("Invalid email $email") this.value = email } override fun toString(): String { return value } override fun equals(other: Any?): Boolean { if ((other !is EmailAddress)) return false val o = other.value.toLowerCase() val t = this.value.toLowerCase() return o == t } override fun hashCode(): Int { return value.hashCode() } }
agpl-3.0
c13da4d51ce224692a46bdf56c6cb033
24.323529
84
0.671312
4.531579
false
false
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/managecars/ManageCarsActivity.kt
1
10370
package se.barsk.park.managecars import android.content.Intent import android.os.Bundle import android.os.Handler import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ViewSwitcher import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import se.barsk.park.* import se.barsk.park.analytics.ShareCarEvent import se.barsk.park.datatypes.Car import se.barsk.park.datatypes.CarCollectionStatusChangedListener import se.barsk.park.datatypes.OwnCar class ManageCarsActivity : AppCompatActivity(), ManageCarDialog.ManageCarDialogListener, CarCollectionStatusChangedListener { override fun onCarCollectionStatusChange() { adapter.ownCars = ParkApp.carCollection.getCars() adapter.notifyDataSetChanged() showCarsPlaceholderIfNeeded() updateOptionsMenuItems() } // Called when the user clicks Save in the add/edit car dialog override fun onDialogPositiveClick(newCar: OwnCar, dialogType: ManageCarDialog.DialogType) { when (dialogType) { ManageCarDialog.DialogType.EDIT -> { ParkApp.carCollection.updateCar(newCar) finishActionMode() } ManageCarDialog.DialogType.ADD -> { ParkApp.carCollection.addCar(newCar) } } } private var actionMode: ActionMode? = null @Suppress("unused") // Used to access actionMode in tests in the mock flavor fun getActionMode() = actionMode private val adapter: SelectableCarsAdapter by lazy { SelectableCarsAdapter(ParkApp.carCollection.getCars()) {} } private val manageCarsRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.manage_cars_recyclerview) } private val fab: FloatingActionButton by lazy { findViewById<FloatingActionButton>(R.id.manage_cards_fab) } private lateinit var optionsMenu: Menu // Exposing the onClick and onLongClick functions to be able to use them in unit tests. fun recyclerOnLongClick(position: Int) = onListItemSelect(position) fun recyclerOnClick(position: Int) = if (actionMode != null) { // Select item in action mode onListItemSelect(position) } else { // Edit item when not in action mode showEditDialog(adapter.ownCars[position].id) } override fun onCreate(savedInstanceState: Bundle?) { ParkApp.init(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage_cars) manageCarsRecyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) manageCarsRecyclerView.itemAnimator = DefaultItemAnimator() manageCarsRecyclerView.adapter = adapter val touchListener = RecyclerTouchListener(this, manageCarsRecyclerView, object : RecyclerTouchListener.ClickListener { override fun onClick(view: View, position: Int) = recyclerOnClick(position) override fun onLongClick(view: View, position: Int) = recyclerOnLongClick(position) }) manageCarsRecyclerView.addOnItemTouchListener(touchListener) fab.setOnClickListener { showAddDialog() } if (intent.getBooleanExtra(INTENT_EXTRA_ADD_CAR, false)) { showAddDialog() } ParkApp.carCollection.addListener(this) showCarsPlaceholderIfNeeded() } override fun onDestroy() { super.onDestroy() ParkApp.carCollection.removeListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { optionsMenu = menu // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.manage_cars_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { updateOptionsMenuItems() return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.manage_cars_menu_manage_mode -> consume { startActionModeWithoutSelection() } R.id.manage_cars_menu_select_all -> consume { selectAllItems() } else -> super.onOptionsItemSelected(item) } private fun updateOptionsMenuItems() { val enabled = adapter.cars.isNotEmpty() val selectAll = optionsMenu.findItem(R.id.manage_cars_menu_select_all) selectAll.isVisible = enabled selectAll.isEnabled = enabled val manage = optionsMenu.findItem(R.id.manage_cars_menu_manage_mode) manage.isVisible = enabled manage.isEnabled = enabled } // Called when an item is selected in the list of cars private fun onListItemSelect(position: Int) { adapter.toggleSelection(position) if (adapter.hasSelectedItems() && actionMode == null) { // there are some selected items but no action mode, start the actionMode startActionMode() } else if (!adapter.hasSelectedItems()) { // there no selected items, finish the actionMode finishActionMode() } else { // there are selected items and already in action mode, update the menu actionMode?.invalidate() } actionMode?.title = getString(R.string.manage_cars_action_mode_title, adapter.numSelectedItems()) } private fun selectAllItems() { adapter.selectAll() startActionMode() actionMode?.title = adapter.numSelectedItems().toString() } private fun startActionModeWithoutSelection() { startActionMode() actionMode?.title = getString(R.string.action_mode_title) } private fun deleteSelectedItems() { val toDelete = adapter.selectedItemsIds.clone() // Make sure to clear the selection before deleting the items to prevent that // the view has a visible check view later on if the same view gets re-used in // the recycler view. This would lead to a crash when showItem() is called for // the new item being added to the recycler view when it tries to animate the // check view. adapter.clearSelection() ParkApp.carCollection.removeCars(toDelete) finishActionMode() } private fun startActionMode() { actionMode = (this as AppCompatActivity).startSupportActionMode(ActionModeCallback()) } private fun finishActionMode() { actionMode?.finish() actionMode = null } private fun showEditDialog(carId: String) = EditCarDialog.newInstance(carId).show(supportFragmentManager, "editCar") private fun showAddDialog() = AddCarDialog.newInstance().show(supportFragmentManager, "addCar") private fun showCarsPlaceholderIfNeeded() { // This function is typically called just after the adapter have changed but before // the recyclerview have started animating the changes. Post a message on the message // queue to continue after the recycler view have started animations so we can detect // if they are still going Handler().post { showCarsPlaceholderIfNeededAfterAnimation() } } private fun showCarsPlaceholderIfNeededAfterAnimation() { if (manageCarsRecyclerView.isAnimating) { // If the recyclerview is animating, try again a bit later // If it's animating there is an animator so it's safe to assume itemAnimator exists manageCarsRecyclerView.itemAnimator!!.isRunning { showCarsPlaceholderIfNeeded() } return } val viewSwitcher = findViewById<ViewSwitcher>(R.id.manage_cars_view_switcher) val parkedCarsView = findViewById<View>(R.id.manage_cars_recyclerview) val empty = adapter.cars.isEmpty() showPlaceholderIfNeeded(viewSwitcher, parkedCarsView, empty) } private fun shareSelectedItems() { val selected = adapter.selectedItemsIds val cars: MutableList<Car> = mutableListOf() (0 until selected.size()) .map { selected.keyAt(it) } .mapTo(cars) { adapter.cars[it] } val linkToShare = DeepLink.getDynamicLinkFor(cars, ParkApp.storageManager.getServer()) val shareTitle = resources.getQuantityString(R.plurals.share_car_title, selected.size()) startActivity(Intent.createChooser(createShareIntent(linkToShare), shareTitle)) ParkApp.analytics.logEvent(ShareCarEvent(selected.size())) } private fun createShareIntent(url: String): Intent { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, url) return shareIntent } /** * Listener for events related to the CAB. */ inner class ActionModeCallback : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean = when (item.itemId) { R.id.item_delete -> consume { deleteSelectedItems() } R.id.item_share -> consume { shareSelectedItems() } else -> true } override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { menuInflater.inflate(R.menu.manage_cars_context_menu, menu) fab.hide() return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { val enabled = adapter.numSelectedItems() > 0 val delete = menu?.findItem(R.id.item_delete) if (delete != null) { delete.isEnabled = enabled delete.isVisible = enabled } val share = menu?.findItem(R.id.item_share) if (share != null) { share.isEnabled = enabled share.isVisible = enabled } return true } override fun onDestroyActionMode(mode: ActionMode?) { adapter.clearSelection() actionMode = null fab.show() } } }
mit
433086ba20a36871440a28b844c7e743
39.193798
125
0.673963
4.952245
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/to/Extensions.kt
2
2211
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.to import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Extensions(val oid: String = "", val isService: Boolean = false, val isPersistent: Boolean = false, val menuBar: String? = MenuBarPosition.PRIMARY.position, val actionScope: String? = null, val actionSemantics: String? = null, val actionType: String = "", @SerialName("x-causeway-format") val xCausewayFormat: String? = null, private val friendlyName: String = "", private val friendlyNameForm: String = "", val collectionSemantics: String? = null, val pluralName: String = "", private val description: String = "", private val descriptionForm: String = "" ) : TransferObject { fun getFriendlyName(): String { if (friendlyName.isEmpty()) { console.log("[Extensions.getFriendlyName] is empty") } return friendlyName } fun getDescription(): String { if (description.isEmpty()) { console.log("[Extensions.getDescription] is empty") } return description } }
apache-2.0
61e35f8cc2bb5ee4776ff35d7f09574f
39.2
91
0.620534
4.946309
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IntroduceImportAliasIntention.kt
2
1960
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.imports.canBeAddedToImport import org.jetbrains.kotlin.idea.refactoring.introduce.introduceImportAlias.KotlinIntroduceImportAliasHandler import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.psi.KtInstanceExpressionWithLabel import org.jetbrains.kotlin.psi.KtNameReferenceExpression class IntroduceImportAliasIntention : SelfTargetingRangeIntention<KtNameReferenceExpression>( KtNameReferenceExpression::class.java, KotlinBundle.lazyMessage("introduce.import.alias") ) { override fun applicabilityRange(element: KtNameReferenceExpression): TextRange? { if (element.parent is KtInstanceExpressionWithLabel || element.mainReference.getImportAlias() != null) return null val targets = element.resolveMainReferenceToDescriptors() if (targets.isEmpty() || targets.any { !it.canBeAddedToImport() }) return null // It is a workaround: KTIJ-20142 actual FE could not report ambiguous references for alias for a broken reference if (element.mainReference.resolve() == null) return null return element.textRange } override fun startInWriteAction(): Boolean = false override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) { if (editor == null) return val project = element.project KotlinIntroduceImportAliasHandler.doRefactoring(project, editor, element) } }
apache-2.0
4e376a89d1dc693bb00da93a98f36c9d
52
158
0.795408
5.090909
false
false
false
false
exercism/xkotlin
exercises/practice/clock/.meta/src/reference/kotlin/Clock.kt
1
969
data class Clock(private var hours: Int, private var minutes: Int) { companion object { private const val MINUTES_IN_AN_HOUR = 60 private const val HOURS_IN_A_DAY = 24 } init { sanitiseTime() } override fun toString(): String { return "${hours.toTimeString()}:${minutes.toTimeString()}" } fun add(minutes: Int) { this.minutes += minutes sanitiseTime() } fun subtract(minutes: Int) = add(minutes * -1) private fun sanitiseTime() { while (minutes < 0) { minutes += MINUTES_IN_AN_HOUR hours-- } while (hours < 0) { hours += HOURS_IN_A_DAY } val minutesOverflow = minutes / MINUTES_IN_AN_HOUR minutes %= MINUTES_IN_AN_HOUR hours = (hours + minutesOverflow) % HOURS_IN_A_DAY } } private fun Int.toTimeString(): String { return toString().padStart(length = 2, padChar = '0') }
mit
b110e19eca8d1f2e852e7d1a7d70e2f3
22.071429
68
0.560372
3.923077
false
false
false
false
android/wear-os-samples
ComposeAdvanced/app/src/main/java/com/example/android/wearable/composeadvanced/presentation/theme/Color.kt
1
1737
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.android.wearable.composeadvanced.presentation.theme import androidx.compose.ui.graphics.Color import androidx.wear.compose.material.Colors internal data class ThemeValues(val description: String, val colors: Colors) internal val initialThemeValues = ThemeValues( "Lilac (D0BCFF)", Colors( primary = Color(0xFFD0BCFF), primaryVariant = Color(0xFF9A82DB), secondary = Color(0xFF7FCFFF), secondaryVariant = Color(0xFF3998D3) ) ) internal val themeValues = listOf( initialThemeValues, ThemeValues("Blue (Default AECBFA)", Colors()), ThemeValues( "Blue 2 (7FCFFF)", Colors( primary = Color(0xFF7FCFFF), primaryVariant = Color(0xFF3998D3), secondary = Color(0xFF6DD58C), secondaryVariant = Color(0xFF1EA446) ) ), ThemeValues( "Green (6DD58C)", Colors( primary = Color(0xFF6DD58C), primaryVariant = Color(0xFF1EA446), secondary = Color(0xFFFFBB29), secondaryVariant = Color(0xFFD68400) ) ) )
apache-2.0
bc008fc73d37eef71abedd11577afe27
31.166667
76
0.673575
4.077465
false
false
false
false
allotria/intellij-community
platform/lang-api/src/com/intellij/execution/target/TargetEnvironmentType.kt
2
4623
// Copyright 2000-2019 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.execution.target import com.intellij.execution.target.LanguageRuntimeType.Companion.EXTENSION_NAME import com.intellij.execution.target.TargetEnvironmentType.Companion.EXTENSION_NAME import com.intellij.ide.wizard.AbstractWizardStepEx import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project import javax.swing.JComponent /** * Contributed type for ["com.intellij.executionTargetType"][EXTENSION_NAME] extension point * * Contributed instances of this class define a type of target environments that can be created by user * and configured to run processes on. */ //todo[remoteServers]: suggest "predefined" configurations (e.g one per every configured SFTP connection) abstract class TargetEnvironmentType<C : TargetEnvironmentConfiguration>(id: String) : ContributedTypeBase<C>(id) { /** * Returns true if configurations of given type can be run on this OS. */ open fun isSystemCompatible(): Boolean = true /** * Returns true if the new configuration of given type may be set up by the user iteratively with the help of [createStepsForNewWizard] */ open fun providesNewWizard(project: Project, runtimeType: LanguageRuntimeType<*>?): Boolean = false /** * Prepares the wizard for setting up the new configuration instance of this type. */ open fun createStepsForNewWizard(project: Project, configToConfigure: C, runtimeType: LanguageRuntimeType<*>?) : List<AbstractWizardStepEx>? = null /** * Instantiates a new environment factory for given prepared [configuration][config]. */ abstract fun createEnvironmentFactory(project: Project, config: C): TargetEnvironmentFactory abstract fun createConfigurable(project: Project, config: C, defaultLanguage: LanguageRuntimeType<*>?, parentConfigurable: Configurable?): Configurable /** * The optional target-specific contribution to all the volumes configurables defined by the respected */ open fun createVolumeContributionUI(): TargetSpecificVolumeContributionUI? = null companion object { @JvmField val EXTENSION_NAME = ExtensionPointName.create<TargetEnvironmentType<*>>("com.intellij.executionTargetType") @JvmStatic fun <Type, Config, State> duplicateTargetConfiguration(type: Type, template: Config): Config where Config : PersistentStateComponent<State>, Config : TargetEnvironmentConfiguration, Type : TargetEnvironmentType<Config> { return duplicatePersistentComponent(type, template).also { copy -> template.runtimes.resolvedConfigs().map { next -> copy.runtimes.addConfig(next.getRuntimeType().duplicateConfig(next)) } } } } /** * Custom UI component for editing of the target specific volume data. The language runtime is expected to create separate editor instance * for each of its [LanguageRuntimeType.volumeDescriptors] descriptors. The data configured by the user will be stored in the * [LanguageRuntimeConfiguration.getTargetSpecificData], and will be made available for the target via the [TargetEnvironmentRequest]. * * Currently, only [TargetEnvironment.UploadRoot.volumeData] is actually supported. * * The [TargetSpecificVolumeData] configured by the user in this editor, * will be passed at the time of the TargetEnviron */ interface TargetSpecificVolumeContributionUI { fun createComponent(): JComponent /** * [storedData] previously serialized data originally produced by [TargetSpecificVolumeData#toStorableMap] call */ fun resetFrom(storedData: Map<String, String>) fun getConfiguredValue(): TargetSpecificVolumeData } /** * Marker interface for all the target specific data that has to be configured by the user for each volume, defined in the language runtime. * E.g, the docker target may request user to define whether particular path has to be mounted as volume, or copied to target via `docker cp`. */ interface TargetSpecificVolumeData { /** * Defines serialization format for target specific volume data. The result map is a separate copy of the real data, * its modifications do not affect the actual data. */ fun toStorableMap(): Map<String, String> } }
apache-2.0
3eef9f9284906c81fe56f2b79b8ed84f
43.893204
144
0.742375
5.0141
false
true
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/gdpr/Agreements.kt
1
4537
// 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.ide.gdpr import com.intellij.idea.Main import com.intellij.idea.SplashManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.AppUIUtil import java.util.* object Agreements { private val bundle get() = ResourceBundle.getBundle("messages.AgreementsBundle") private val isEap get() = ApplicationInfoImpl.getShadowInstance().isEAP fun showEndUserAndDataSharingAgreements(agreement: EndUserAgreement.Document) { val agreementUi = AgreementUi.create(agreement.text) val dialog = agreementUi.applyUserAgreement(agreement).pack() SplashManager.executeWithHiddenSplash(dialog.window) { dialog.show() } } fun showDataSharingAgreement() { val agreementUi = AgreementUi.create() val dialog = agreementUi.applyDataSharing().pack() SplashManager.executeWithHiddenSplash(dialog.window) { dialog.show() } } private fun AgreementUi.applyUserAgreement(agreement: EndUserAgreement.Document): AgreementUi { val isPrivacyPolicy = agreement.isPrivacyPolicy val commonUserAgreement = this .setTitle( if (isPrivacyPolicy) ApplicationInfoImpl.getShadowInstance().shortCompanyName + " " + bundle.getString("userAgreement.dialog.privacyPolicy.title") else ApplicationNamesInfo.getInstance().fullProductName + " " + bundle.getString("userAgreement.dialog.userAgreement.title")) .setDeclineButton(bundle.getString("userAgreement.dialog.exit")) { val application = ApplicationManager.getApplication() if (application == null) { System.exit(Main.PRIVACY_POLICY_REJECTION) } else { application.exit(true, true, false) } } .addCheckBox(bundle.getString("userAgreement.dialog.checkBox")) { checkBox -> this.enableAcceptButton(checkBox.isSelected) if (checkBox.isSelected) focusToAcceptButton() } if (!isEap) { commonUserAgreement .setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper -> EndUserAgreement.setAccepted(agreement) if (AppUIUtil.needToShowConsentsAgreement()) { this.applyDataSharing() } else { dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } } } else { commonUserAgreement .setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper -> EndUserAgreement.setAccepted(agreement) dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } .addEapPanel(isPrivacyPolicy) } return this } private fun AgreementUi.applyDataSharing(): AgreementUi { val dataSharingConsent = ConsentOptions.getInstance().consents.first[0] this.setText(prepareConsentsHtmlText(dataSharingConsent)) .setTitle(bundle.getString("dataSharing.dialog.title")) .clearBottomPanel() .focusToText() .setAcceptButton(bundle.getString("dataSharing.dialog.accept")) { val consentToSave = dataSharingConsent.derive(true) AppUIUtil.saveConsents(listOf(consentToSave)) it.close(DialogWrapper.OK_EXIT_CODE) } .setDeclineButton(bundle.getString("dataSharing.dialog.decline")) { val consentToSave = dataSharingConsent.derive(false) AppUIUtil.saveConsents(listOf(consentToSave)) it.close(DialogWrapper.CANCEL_EXIT_CODE) } return this } private fun prepareConsentsHtmlText(consent: Consent): String { val allProductHint = if (!ConsentOptions.getInstance().isEAP) "<p><hint>${bundle.getString("dataSharing.applyToAll.hint")}</hint></p>".replace("{0}", ApplicationInfoImpl.getShadowInstance().shortCompanyName) else "" val preferencesHint = "<p><hint>${bundle.getString("dataSharing.revoke.hint").replace("{0}", ShowSettingsUtil.getSettingsMenuName())}</hint></p>" return ("<html><body> <h1>${bundle.getString("dataSharing.consents.title")}</h1>" + "<p>" + consent.text.replace("\n", "</p><p>") + "</p>" + allProductHint + preferencesHint + "</body></html>") } }
apache-2.0
68c9b777ecedfb5fd4270a6ef738c57a
41.411215
211
0.708398
4.474359
false
false
false
false
wcomartin/PlexPy-Remote
android/app/src/main/kotlin/com/tautulli/tautulli_remote/NotificationExtender.kt
1
8830
package com.tautulli.tautulli_remote import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.onesignal.OSMutableNotification import com.onesignal.OSNotification import com.onesignal.OSNotificationReceivedEvent import com.onesignal.OneSignal.OSRemoteNotificationReceivedHandler import org.json.JSONException import org.json.JSONObject import java.net.URL import java.net.URLConnection import java.io.File import java.io.IOException import android.database.sqlite.SQLiteDatabase import android.app.* @GlideModule class AppGlideModule : AppGlideModule() class NotificationServiceExtension : OSRemoteNotificationReceivedHandler { override fun remoteNotificationReceived(context: Context, notificationReceivedEvent: OSNotificationReceivedEvent) { val notification: OSNotification = notificationReceivedEvent.getNotification() val data: JSONObject = notification.getAdditionalData() try { val serverId = data.getString("server_id") val serverInfoMap = getServerInfo(context, serverId) val deviceToken = serverInfoMap["deviceToken"]!! //* If encrypted decrypt the payload data val jsonMessage: JSONObject = if (data.getBoolean("encrypted")) { JSONObject(getUnencryptedMessage(data, deviceToken)) } else { JSONObject(data.getString("plain_text")) } val notificationType: Int = jsonMessage.optInt("notification_type", 0) val body: String = jsonMessage.getString("body") val subject: String = jsonMessage.getString("subject") val priority: Int = jsonMessage.getInt("priority") //* Create an explicit intent val intent = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0) val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_stat_logo_flat) .setContentTitle(subject) .setContentText(body) .setStyle(NotificationCompat.BigTextStyle().bigText(body)) .setColor(context.resources.getColor(R.color.amber)) .setPriority(priority) //* Set the intent that will fire when the user taps the notification .setContentIntent(pendingIntent) .setAutoCancel(true) createNotificationChannel(context) with(NotificationManagerCompat.from(context)) { //* Create notification id val tsLong: Long = System.currentTimeMillis() val ts = tsLong.toString() val tsTrunc: String = ts.substring(ts.length - 9) val notificationId: Int = Integer.parseInt(tsTrunc) // Fetch/add image and send notification if notification type is 1 or 2 if (notificationType != 0) { var posterThumb = jsonMessage.getString("poster_thumb") if (!posterThumb.isNullOrEmpty()) { var connectionAddress: String? if (serverInfoMap["primaryActive"] == "1") { connectionAddress = serverInfoMap["primaryConnectionAddress"] } else { connectionAddress = serverInfoMap["secondaryConnectionAddress"] } val urlString = if (notificationType == 1) { "$connectionAddress/api/v2?apikey=$deviceToken&cmd=pms_image_proxy&app=true&img=$posterThumb&height=200" } else { "$connectionAddress/api/v2?apikey=$deviceToken&cmd=pms_image_proxy&app=true&img=$posterThumb&width=1080" } GlideApp.with(context) .asBitmap() .load(urlString) .into(object : CustomTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { builder.setLargeIcon(resource) if (notificationType == 2) { builder.setStyle(NotificationCompat.BigPictureStyle() .bigPicture(resource) .bigLargeIcon(null)) } //* Send notification with image notify(notificationId, builder.build()) } override fun onLoadCleared(placeholder: Drawable?) {} }) } } //* Send notification notify(notificationId, builder.build()) } //* Do not return original OneSignal notification notificationReceivedEvent.complete(null) } catch (e: JSONException) { e.printStackTrace() } } private fun createNotificationChannel(context: Context) { //* Create the NotificationChannel, but only on API 26+ because //* the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = context.resources.getString(R.string.channel_name) val descriptionText = context.resources.getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText } //* Register the channel with the system val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } private fun getUnencryptedMessage(data: JSONObject?, deviceToken: String): String { if (data != null) { val salt: String = data.optString("salt", "") val cipherText: String = data.optString("cipher_text", "") val nonce: String = data.optString("nonce", "") if (salt != "" && cipherText != "" && nonce != "") { return DecryptAESGCM.decrypt(deviceToken, salt, cipherText, nonce) } } return "" } private fun getServerInfo(context: Context, serverId: String): Map<String, String> { val documentDir = context.dataDir val path = File(documentDir, "app_flutter/tautulli_remote.db") val db: SQLiteDatabase = SQLiteDatabase.openDatabase(path.absolutePath, null, 0) val query = "SELECT primary_connection_address, secondary_connection_address, primary_active, device_token FROM servers WHERE tautulli_id = \'$serverId\'" var primaryConnectionAddress = "" var secondaryConnectionAddress = "" var primaryActive = "" var deviceToken = "" val cursor = db.rawQuery(query, null) if (cursor.moveToFirst()) { cursor.moveToFirst() primaryConnectionAddress = cursor.getString(0) if (!cursor.isNull(1)) { secondaryConnectionAddress = cursor.getString(1) } primaryActive = cursor.getInt(2).toString() deviceToken = cursor.getString(3) cursor.close() } db.close() val serverInfoMap = mapOf("primaryConnectionAddress" to primaryConnectionAddress, "secondaryConnectionAddress" to secondaryConnectionAddress, "primaryActive" to primaryActive, "deviceToken" to deviceToken) return serverInfoMap } companion object { private const val CHANNEL_ID = "tautulli_remote" private const val LOG_TAG = "NotificationExtender" } }
mit
3f0109cf9fe2a5a3a6a303203dae9839
44.287179
213
0.606116
5.35476
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-core/src/main/kotlin/slatekit/core/cloud/CloudSupport.kt
1
2693
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.core.cloud import slatekit.results.Try interface CloudSupport { suspend fun <T> execute( source: String, action: String, tag: String = "", audit: Boolean = false, rethrow: Boolean = false, data: Any?, call: suspend () -> T ): T? { val result: T? = try { call() } catch (ex: Exception) { onError(source, action, tag, data, ex) null } return result } suspend fun <T> executeResult( source: String, action: String, tag: String = "", audit: Boolean = false, data: Any?, call: suspend () -> T ): Try<T> { val result = try { val resultValue = call() slatekit.results.Success(resultValue) } catch (ex: Exception) { onError(source, action, tag, data, ex) slatekit.results.Failure(ex, msg = "Error performing action $action on $source with tag $tag. $ex") } return result } fun <T> executeSync( source: String, action: String, tag: String = "", audit: Boolean = false, rethrow: Boolean = false, data: Any?, call: () -> T ): T? { val result: T? = try { call() } catch (ex: Exception) { onError(source, action, tag, data, ex) null } return result } fun <T> executeResultSync( source: String, action: String, tag: String = "", audit: Boolean = false, data: Any?, call: () -> T ): Try<T> { val result = try { val resultValue = call() slatekit.results.Success(resultValue) } catch (ex: Exception) { onError(source, action, tag, data, ex) slatekit.results.Failure(ex, msg = "Error performing action $action on $source with tag $tag. $ex") } return result } fun onAudit(source: String, action: String, tag: String, data: Any?) { } fun onError(source: String, action: String, tag: String, data: Any?, ex: Exception?) { } fun onWarn(source: String, action: String, tag: String, data: Any?, ex: Exception?) { } }
apache-2.0
1ef6abce05e14584df8ed79a4f85d6b9
25.93
111
0.523951
4.11145
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTableItem.kt
1
5449
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.ide.CopyProvider import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.ide.CopyPasteManager import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SelectedPackageModel import java.awt.datatransfer.StringSelection internal sealed class PackagesTableItem<T : PackageModel> : DataProvider, CopyProvider { val packageModel: T get() = selectedPackageModel.packageModel abstract val selectedPackageModel: SelectedPackageModel<T> protected open val handledDataKeys: List<DataKey<*>> = listOf(PlatformDataKeys.COPY_PROVIDER) fun canProvideDataFor(key: String) = handledDataKeys.any { it.`is`(key) } override fun getData(dataId: String): Any? = when { PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this else -> null } override fun performCopy(dataContext: DataContext) = CopyPasteManager.getInstance().setContents(StringSelection(getTextForCopy(packageModel))) private fun getTextForCopy(packageModel: PackageModel) = buildString { appendln("${packageModel.groupId}/${packageModel.artifactId}") append(additionalCopyText()) packageModel.remoteInfo?.versions?.let { versions -> if (versions.any()) { appendln() append(" ${PackageSearchBundle.message("packagesearch.package.copyableInfo.availableVersions")} ") append(versions.joinToString("; ") { it.version }) } } packageModel.remoteInfo?.gitHub?.let { gitHub -> appendln() append(" ") append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats")) if (gitHub.stars != null) { append(" ") append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats.stars", gitHub.stars)) } if (gitHub.forks != null) { append(" ") append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats.forks", gitHub.forks)) } } packageModel.remoteInfo?.stackOverflowTags?.tags?.let { tags -> if (tags.any()) { appendln() append(" ${PackageSearchBundle.message("packagesearch.package.copyableInfo.stackOverflowTags")} ") append(tags.joinToString("; ") { "${it.tag} (${it.count})" }) } } } protected abstract fun additionalCopyText(): String override fun isCopyVisible(dataContext: DataContext) = true override fun isCopyEnabled(dataContext: DataContext) = true data class InstalledPackage( override val selectedPackageModel: SelectedPackageModel<PackageModel.Installed>, val installedScopes: List<PackageScope>, val defaultScope: PackageScope ) : PackagesTableItem<PackageModel.Installed>() { init { require(installedScopes.isNotEmpty()) { "An installed package must have at least one installed scope" } } override val handledDataKeys = super.handledDataKeys + listOf(CommonDataKeys.VIRTUAL_FILE, CommonDataKeys.NAVIGATABLE_ARRAY) fun getData(dataId: String, module: ProjectModule?): Any? { val projectModule = module ?: packageModel.usageInfo.firstOrNull()?.projectModule return when { CommonDataKeys.VIRTUAL_FILE.`is`(dataId) -> projectModule?.buildFile CommonDataKeys.NAVIGATABLE_ARRAY.`is`(dataId) -> { val usageInfo = packageModel.usageInfo.find { it.projectModule == projectModule } ?: return null arrayOf(usageInfo.projectModule.getNavigatableDependency(packageModel.groupId, packageModel.artifactId, usageInfo.version)) } else -> getData(dataId) } } override fun additionalCopyText() = buildString { if (packageModel.usageInfo.isEmpty()) return@buildString appendln() append(" ${PackageSearchBundle.message("packagesearch.package.copyableInfo.installedVersions")} : ") append( packageModel.usageInfo.map { it.version } .distinct() .joinToString("; ") ) } } data class InstallablePackage( override val selectedPackageModel: SelectedPackageModel<PackageModel.SearchResult>, val availableScopes: List<PackageScope>, val defaultScope: PackageScope ) : PackagesTableItem<PackageModel.SearchResult>() { override fun additionalCopyText() = "" init { require(availableScopes.isNotEmpty()) { "A package must have at least one available scope" } } } }
apache-2.0
5929687f5d43dafbf19e3cece4a61b1c
41.24031
143
0.671316
5.368473
false
false
false
false
byoutline/kickmaterial
app/src/main/java/com/byoutline/kickmaterial/transitions/SharedElementTransition.kt
1
3495
package com.byoutline.kickmaterial.transitions import android.animation.Animator import android.animation.AnimatorSet import android.annotation.TargetApi import android.content.Context import android.os.Build import android.text.TextUtils import android.transition.ChangeBounds import android.transition.ChangeImageTransform import android.transition.Transition import android.transition.TransitionValues import android.util.AttributeSet import android.view.ViewGroup import com.byoutline.kickmaterial.BuildConfig import com.byoutline.kickmaterial.R /** * Custom transition wrapper that delegates handling to [CircleTransition] for * FAB, and to [ChangeBounds] and [ChangeImageTransform] for other elements. * @author Sebastian Kacprzak <sebastian.kacprzak at byoutline.com> */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class SharedElementTransition(context: Context, attrs: AttributeSet) : Transition(context, attrs) { private val fabTransition: CircleTransition = CircleTransition(context, attrs) private val fabTransitionName: String = context.getString(R.string.transition_fab) private val imageTransition: ChangeImageTransform = ChangeImageTransform(context, attrs) private val defaultTransition: ChangeBounds = ChangeBounds(context, attrs) private val transitionProperties: Array<String> = arrayOf(*fabTransition.transitionProperties, *imageTransition.transitionProperties, *defaultTransition.transitionProperties) init { if (BuildConfig.DEBUG && TextUtils.isEmpty(fabTransitionName)) { throw AssertionError("Transition name should not be empty") } } override fun getTransitionProperties(): Array<String> = transitionProperties override fun captureStartValues(transitionValues: TransitionValues) { if (isFabTransition(transitionValues)) { fabTransition.captureStartValues(transitionValues) } else { defaultTransition.captureStartValues(transitionValues) imageTransition.captureStartValues(transitionValues) } } override fun captureEndValues(transitionValues: TransitionValues) { if (isFabTransition(transitionValues)) { fabTransition.captureEndValues(transitionValues) } else { defaultTransition.captureEndValues(transitionValues) imageTransition.captureStartValues(transitionValues) } } private fun isFabTransition(transitionValues: TransitionValues): Boolean { val view = transitionValues.view return fabTransitionName == view.transitionName } override fun createAnimator(sceneRoot: ViewGroup, startValues: TransitionValues?, endValues: TransitionValues?): Animator? { if (startValues == null || endValues == null) { return null } if (isFabTransition(endValues)) { return fabTransition.createAnimator(sceneRoot, startValues, endValues) } else { val imageAnimator = imageTransition.createAnimator(sceneRoot, startValues, endValues) val defaultAnimator = defaultTransition.createAnimator(sceneRoot, startValues, endValues) if (imageAnimator == null) { return defaultAnimator } if (defaultAnimator == null) { return imageAnimator } val set = AnimatorSet() set.playTogether(imageAnimator, defaultAnimator) return set } } }
apache-2.0
580eb2fb2f53941f6abf943acfe0b0ba
40.117647
128
0.723891
5.057887
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/solarsystem/SunAndPlanetsView.kt
1
9326
package au.com.codeka.warworlds.client.game.solarsystem import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import android.view.View.OnClickListener import android.widget.ImageView import android.widget.RelativeLayout import androidx.core.view.ViewCompat import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.game.build.BuildViewHelper import au.com.codeka.warworlds.client.game.world.EmpireManager import au.com.codeka.warworlds.client.game.world.ImageHelper import au.com.codeka.warworlds.client.util.ViewBackgroundGenerator.OnDrawHandler import au.com.codeka.warworlds.client.util.ViewBackgroundGenerator.setBackground import au.com.codeka.warworlds.common.Vector2 import au.com.codeka.warworlds.common.proto.Building import au.com.codeka.warworlds.common.proto.Planet import au.com.codeka.warworlds.common.proto.Star import au.com.codeka.warworlds.common.sim.DesignHelper import com.squareup.picasso.Picasso import java.util.* /** * The view which displays the big star and planets, and allows you to click planets to "select" * them. You can only select one planet at a time. */ class SunAndPlanetsView(context: Context?, attrs: AttributeSet?) : RelativeLayout(context, attrs) { interface PlanetSelectedHandler { fun onPlanetSelected(planet: Planet?) } private val orbitPaint: Paint = Paint() private var star: Star? = null private val planetInfos = ArrayList<PlanetInfo>() private val selectionIndicator: ImageView private var selectedPlanet: Planet? = null private var planetSelectedHandler: PlanetSelectedHandler? = null init { orbitPaint.setARGB(255, 255, 255, 255) orbitPaint.style = Paint.Style.STROKE selectionIndicator = ImageView(context) selectionIndicator.setImageResource(R.drawable.planet_selection) selectionIndicator.visibility = View.GONE // Set ourselves to be clickable so that touch event don't go through to the starfield under us. isClickable = true } fun setPlanetSelectedHandler(handler: PlanetSelectedHandler?) { planetSelectedHandler = handler } fun getPlanetCentre(planet: Planet): Vector2 { return planetInfos[planet.index].centre } /** Gets the [ImageView] that displays the given planet's icon. */ fun getPlanetView(planetIndex: Int): ImageView { return planetInfos[planetIndex].imageView } fun setStar(star: Star) { if (isInEditMode) { return } setBackground(this, onBackgroundDrawHandler, star.id) removeAllViews() addView(selectionIndicator) this.star = star planetInfos.clear() for (i in star.planets.indices) { planetInfos.add(PlanetInfo(star.planets[i], Vector2(0.0, 0.0), 0.0f)) } val sunImageView = ImageView(context) val lp = LayoutParams( (256 * context.resources.displayMetrics.density).toInt(), (256 * context.resources.displayMetrics.density).toInt()) val yOffset = (20 * context.resources.displayMetrics.density).toInt() lp.topMargin = -lp.height / 2 + +yOffset lp.leftMargin = -lp.width / 2 sunImageView.layoutParams = lp addView(sunImageView) Picasso.get() .load(ImageHelper.getStarImageUrl(context, star, 256, 256)) .into(sunImageView) placePlanets() } /** Selects the planet at the given index. */ fun selectPlanet(planetIndex: Int) { selectedPlanet = planetInfos[planetIndex].planet updateSelection() } private fun getDistanceFromSun(planetIndex: Int): Float { var width = width if (width == 0) { return 0.0f } width -= (16 * context.resources.displayMetrics.density).toInt() val planetStart = 150 * context.resources.displayMetrics.density var distanceBetweenPlanets = width - planetStart distanceBetweenPlanets /= planetInfos.size.toFloat() return planetStart + distanceBetweenPlanets * planetIndex + distanceBetweenPlanets / 2.0f } private fun placePlanets() { val width = width if (width == 0) { post { placePlanets() } return } val density = context.resources.displayMetrics.density for (i in planetInfos.indices) { val planetInfo = planetInfos[i] val distanceFromSun = getDistanceFromSun(i) val y = 0f var angle = 0.5f / (planetInfos.size + 1) angle = (angle * (planetInfos.size - i - 1) * Math.PI + angle * Math.PI).toFloat() val centre = Vector2(distanceFromSun.toDouble(), y.toDouble()) centre.rotate(angle.toDouble()) centre.y += (20 * context.resources.displayMetrics.density).toDouble() planetInfo.centre = centre planetInfo.distanceFromSun = distanceFromSun planetInfo.imageView = ImageView(context) val lp = LayoutParams( (64 * density).toInt(), (64 * density).toInt()) lp.topMargin = centre.y.toInt() - lp.height / 2 lp.leftMargin = centre.x.toInt() - lp.width / 2 planetInfo.imageView.layoutParams = lp planetInfo.imageView.tag = planetInfo planetInfo.imageView.setOnClickListener(planetOnClickListener) ViewCompat.setTransitionName(planetInfo.imageView, "planet_icon_$i") addView(planetInfo.imageView) Picasso.get() .load(ImageHelper.getPlanetImageUrl(context, star!!, i, 64, 64)) .into(planetInfo.imageView) val colony = planetInfo.planet.colony if (colony != null) { for (building in colony.buildings) { val design = DesignHelper.getDesign(building.design_type) if (design.show_in_solar_system!!) { planetInfo.buildings.add(building) } } if (planetInfo.buildings.isNotEmpty()) { planetInfo.buildings.sortWith { lhs: Building, rhs: Building -> lhs.design_type.compareTo(rhs.design_type) } val angleOffset = (Math.PI / 8.0).toFloat() * (planetInfo.buildings.size - 1) / 2.0f for (buildingIndex in planetInfo.buildings.indices) { val building = planetInfo.buildings[buildingIndex] val design = DesignHelper.getDesign(building.design_type) val pt = Vector2(0.0, -56.0 * density) pt.rotate(angleOffset - (Math.PI / 8.0) * buildingIndex) val buildingImageView = if (buildingIndex < planetInfo.buildingImageViews.size) planetInfo.buildingImageViews[buildingIndex] else ImageView(context) val lpBuilding = LayoutParams( (20 * density).toInt(), (20 * density).toInt()) lpBuilding.topMargin = (centre.y + pt.y).toInt() lpBuilding.leftMargin = (centre.x + pt.x).toInt() - lpBuilding.width / 2 buildingImageView.layoutParams = lpBuilding BuildViewHelper.setDesignIcon(design, buildingImageView) addView(buildingImageView) } } val lpColony = LayoutParams( (20 * density).toInt(), (20 * density).toInt()) lpColony.topMargin = (centre.y + lp.height / 2).toInt() lpColony.leftMargin = centre.x.toInt() - lpColony.width / 2 val colonyImageView = ImageView(context) planetInfo.colonyImageView = colonyImageView colonyImageView.layoutParams = lpColony ImageHelper.bindEmpireShield( colonyImageView, EmpireManager.getEmpire(colony.empire_id)) addView(colonyImageView) } } updateSelection() } private fun updateSelection() { val selection = selectedPlanet if (selection != null) { if (selectionIndicator.width == 0) { // If it doesn't have a width, make it visible then re-update the selection once it's width // has been calculated. selectionIndicator.visibility = View.VISIBLE selectionIndicator.post { updateSelection() } return } val params = selectionIndicator.layoutParams as LayoutParams params.leftMargin = (planetInfos[selection.index].centre.x - selectionIndicator.width / 2).toInt() params.topMargin = (planetInfos[selection.index].centre.y - selectionIndicator.height / 2).toInt() selectionIndicator.layoutParams = params selectionIndicator.visibility = View.VISIBLE } else { selectionIndicator.visibility = View.GONE } planetSelectedHandler?.onPlanetSelected(selection) } private val planetOnClickListener = OnClickListener { v -> val planetInfo = v.tag as PlanetInfo selectedPlanet = planetInfo.planet updateSelection() } private val onBackgroundDrawHandler: OnDrawHandler = object : OnDrawHandler { override fun onDraw(canvas: Canvas?) { for (i in planetInfos.indices) { val radius = getDistanceFromSun(i) val y = 20.0f * getContext().resources.displayMetrics.density canvas!!.drawCircle(0.0f, y, radius, orbitPaint) } } } /** This class contains info about the planets we need to render and interact with. */ private class PlanetInfo(val planet: Planet, var centre: Vector2, var distanceFromSun: Float) { lateinit var imageView: ImageView var colonyImageView: ImageView? = null var buildings: MutableList<Building> = ArrayList() var buildingImageViews: MutableList<ImageView> = ArrayList() } }
mit
8464b1c646b28e70c765f8b7831b3d42
37.541322
104
0.690328
4.206585
false
false
false
false
mglukhikh/intellij-community
platform/script-debugger/backend/src/debugger/ScriptBase.kt
6
1384
/* * Copyright 2000-2017 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.debugger import com.intellij.openapi.util.UserDataHolderBase import com.intellij.util.Url import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.sourcemap.SourceMap abstract class ScriptBase(override val type: Script.Type, override val url: Url, line: Int, override val column: Int, override val endLine: Int) : UserDataHolderBase(), Script { override val line = Math.max(line, 0) @SuppressWarnings("UnusedDeclaration") private @Volatile var source: Promise<String>? = null override var sourceMap: SourceMap? = null override fun toString() = "[url=$url, lineRange=[$line;$endLine]]" override val isWorker: Boolean = false }
apache-2.0
ee1a13996f1087cb7d256ba8aa5655e5
35.447368
85
0.700145
4.464516
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/ChangePasswordViewModel.kt
1
6336
package com.kickstarter.viewmodels import UpdateUserPasswordMutation import androidx.annotation.NonNull import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers.errors import com.kickstarter.libs.rx.transformers.Transformers.takeWhen import com.kickstarter.libs.rx.transformers.Transformers.values import com.kickstarter.libs.utils.extensions.isNotEmptyAndAtLeast6Chars import com.kickstarter.libs.utils.extensions.newPasswordValidationWarnings import com.kickstarter.ui.activities.ChangePasswordActivity import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface ChangePasswordViewModel { interface Inputs { /** Call when the user clicks the change password button. */ fun changePasswordClicked() /** Call when the current password field changes. */ fun confirmPassword(confirmPassword: String) /** Call when the current password field changes. */ fun currentPassword(currentPassword: String) /** Call when the new password field changes. */ fun newPassword(newPassword: String) } interface Outputs { /** Emits when the password update was unsuccessful. */ fun error(): Observable<String> /** Emits a string resource to display when the user's new password entries are invalid. */ fun passwordWarning(): Observable<Int> /** Emits when the progress bar should be visible. */ fun progressBarIsVisible(): Observable<Boolean> /** Emits when the save button should be enabled. */ fun saveButtonIsEnabled(): Observable<Boolean> /** Emits when the password update was successful. */ fun success(): Observable<String> } class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<ChangePasswordActivity>(environment), Inputs, Outputs { private val changePasswordClicked = PublishSubject.create<Void>() private val confirmPassword = PublishSubject.create<String>() private val currentPassword = PublishSubject.create<String>() private val newPassword = PublishSubject.create<String>() private val error = BehaviorSubject.create<String>() private val passwordWarning = BehaviorSubject.create<Int>() private val progressBarIsVisible = BehaviorSubject.create<Boolean>() private val saveButtonIsEnabled = BehaviorSubject.create<Boolean>() private val success = BehaviorSubject.create<String>() val inputs: ChangePasswordViewModel.Inputs = this val outputs: ChangePasswordViewModel.Outputs = this private val apolloClient = requireNotNull(this.environment.apolloClient()) private val analytics = this.environment.analytics() init { val changePassword = Observable.combineLatest( this.currentPassword.startWith(""), this.newPassword.startWith(""), this.confirmPassword.startWith(""), { current, new, confirm -> ChangePassword(current, new, confirm) } ) changePassword .map { it.warning() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.passwordWarning) changePassword .map { it.isValid() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.saveButtonIsEnabled) val changePasswordNotification = changePassword .compose(takeWhen<ChangePassword, Void>(this.changePasswordClicked)) .switchMap { cp -> submit(cp).materialize() } .compose(bindToLifecycle()) .share() changePasswordNotification .compose(errors()) .subscribe({ this.error.onNext(it.localizedMessage) }) changePasswordNotification .compose(values()) .map { it.updateUserAccount()?.user()?.email() } .subscribe { this.analytics?.reset() this.success.onNext(it) } } private fun submit(changePassword: ChangePasswordViewModel.ViewModel.ChangePassword): Observable<UpdateUserPasswordMutation.Data> { return this.apolloClient.updateUserPassword(changePassword.currentPassword, changePassword.newPassword, changePassword.confirmPassword) .doOnSubscribe { this.progressBarIsVisible.onNext(true) } .doAfterTerminate { this.progressBarIsVisible.onNext(false) } } override fun changePasswordClicked() { this.changePasswordClicked.onNext(null) } override fun confirmPassword(confirmPassword: String) { this.confirmPassword.onNext(confirmPassword) } override fun currentPassword(currentPassword: String) { this.currentPassword.onNext(currentPassword) } override fun newPassword(newPassword: String) { this.newPassword.onNext(newPassword) } override fun error(): Observable<String> { return this.error } override fun passwordWarning(): Observable<Int> { return this.passwordWarning } override fun progressBarIsVisible(): Observable<Boolean> { return this.progressBarIsVisible } override fun saveButtonIsEnabled(): Observable<Boolean> { return this.saveButtonIsEnabled } override fun success(): Observable<String> { return this.success } data class ChangePassword(val currentPassword: String, val newPassword: String, val confirmPassword: String) { fun isValid(): Boolean { return this.currentPassword.isNotEmptyAndAtLeast6Chars() && this.newPassword.isNotEmptyAndAtLeast6Chars() && this.confirmPassword.isNotEmptyAndAtLeast6Chars() && this.confirmPassword == this.newPassword } fun warning(): Int? = newPassword.newPasswordValidationWarnings(confirmPassword) } } }
apache-2.0
581e8685ba4d289840a45a2a1b54d127
37.871166
147
0.651831
5.692722
false
false
false
false
ingokegel/intellij-community
plugins/settings-sync/tests/com/intellij/settingsSync/MockRemoteCommunicator.kt
3
1330
package com.intellij.settingsSync import org.junit.Assert import java.util.concurrent.CountDownLatch internal class MockRemoteCommunicator : TestRemoteCommunicator() { private var versionOnServer: SettingsSnapshot? = null private var downloadedLatestVersion = false private lateinit var pushedLatch: CountDownLatch override fun prepareFileOnServer(snapshot: SettingsSnapshot) { versionOnServer = snapshot } override fun checkServerState(): ServerState { return if (versionOnServer == null) ServerState.FileNotExists else if (downloadedLatestVersion) ServerState.UpToDate else ServerState.UpdateNeeded } override fun receiveUpdates(): UpdateResult { downloadedLatestVersion = true return versionOnServer?.let { UpdateResult.Success(it) } ?: UpdateResult.Error("Unexpectedly null update result") } override fun awaitForPush(): SettingsSnapshot? { pushedLatch = CountDownLatch(1) Assert.assertTrue("Didn't await until changes are pushed", pushedLatch.await(5, TIMEOUT_UNIT)) return latestPushedSnapshot } override fun push(snapshot: SettingsSnapshot, force: Boolean): SettingsSyncPushResult { latestPushedSnapshot = snapshot if (::pushedLatch.isInitialized) pushedLatch.countDown() return SettingsSyncPushResult.Success } override fun delete() {} }
apache-2.0
eacc5847ed50367035191fe4d24a76d0
32.275
117
0.775188
5.298805
false
true
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/utils/did.kt
1
3077
/* * VoIP.ms SMS * Copyright (C) 2015-2019 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.utils import android.provider.ContactsContract import java.text.MessageFormat /** * Returns a string consisting only of the digits in the specified string. */ fun getDigitsOfString(str: String): String { val stringBuilder = StringBuilder() for (char in str) { if (Character.isDigit(char)) { stringBuilder.append(char) } } return stringBuilder.toString() } /** * Formats the specified phone number in the form (XXX) XXX-XXXX if it is * ten digits in length (or eleven with a leading one). Otherwise, simply * returns the original phone number. */ fun getFormattedPhoneNumber(phoneNumber: String): String { if (phoneNumber.length == 10) { val phoneNumberFormat = MessageFormat("({0}) {1}-{2}") val phoneNumberArray = arrayOf( phoneNumber.substring(0, 3), phoneNumber.substring(3, 6), phoneNumber.substring(6) ) return phoneNumberFormat.format(phoneNumberArray) } else if (phoneNumber.length == 11 && phoneNumber[0] == '1') { val phoneNumberFormat = MessageFormat("({0}) {1}-{2}") val phoneNumberArray = arrayOf( phoneNumber.substring(1, 4), phoneNumber.substring(4, 7), phoneNumber.substring(7) ) return phoneNumberFormat.format(phoneNumberArray) } return phoneNumber } /** * Returns the string representation of the specified phone number type. */ fun getPhoneNumberType(type: Int): String = when (type) { ContactsContract.CommonDataKinds.Phone.TYPE_HOME -> "Home" ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE -> "Mobile" ContactsContract.CommonDataKinds.Phone.TYPE_WORK -> "Work" ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME -> "Home Fax" ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK -> "Work Fax" ContactsContract.CommonDataKinds.Phone.TYPE_MAIN -> "Main" ContactsContract.CommonDataKinds.Phone.TYPE_OTHER -> "Other" ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM -> "Custom" ContactsContract.CommonDataKinds.Phone.TYPE_PAGER -> "Pager" else -> "" } /** * Throws an exception if the specified phone number contains anything other * than numbers. */ fun validatePhoneNumber(value: String) { if (getDigitsOfString(value) != value) { throw IllegalArgumentException( "value must consist only of numbers" ) } }
apache-2.0
efc73d4d927fd02a834aa3c185944297
33.573034
76
0.689633
4.315568
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/Helper.kt
1
3600
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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.ethereum.jsontestsuite.suite import org.ethereum.util.ByteUtil import org.json.simple.JSONArray import org.slf4j.LoggerFactory import org.spongycastle.util.encoders.Hex import java.io.ByteArrayOutputStream import java.io.IOException import java.math.BigInteger import java.util.regex.Pattern /** * @author Roman Mandeleil * * * @since 28.06.2014 */ internal object Helper { private val logger = LoggerFactory.getLogger("misc") fun parseDataArray(valArray: JSONArray): ByteArray { // value can be: // 1. 324234 number // 2. "0xAB3F23A" - hex string // 3. "239472398472" - big number val bos = ByteArrayOutputStream() for (`val` in valArray) { if (`val` is String) { // Hex num val hexVal = Pattern.matches("0[xX][0-9a-fA-F]+", `val`.toString()) if (hexVal) { var number = `val`.substring(2) if (number.length % 2 == 1) number = "0" + number val data = Hex.decode(number) try { bos.write(data) } catch (e: IOException) { logger.error("should not happen", e) } } else { // BigInt num val isNumeric = Pattern.matches("[0-9a-fA-F]+", `val`.toString()) if (!isNumeric) throw Error("Wrong test case JSON format") else { val value = BigInteger(`val`.toString()) try { bos.write(value.toByteArray()) } catch (e: IOException) { logger.error("should not happen", e) } } } } else if (`val` is Long) { // Simple long val data = ByteUtil.bigIntegerToBytes(BigInteger.valueOf(`val`)) try { bos.write(data) } catch (e: IOException) { logger.error("should not happen", e) } } else { throw Error("Wrong test case JSON format") } } return bos.toByteArray() } }
mit
343bd8b4a26d1fe648b2e5247e696b48
33.951456
85
0.565833
4.603581
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinLazyUBlockExpression.kt
4
1298
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtAnonymousInitializer import org.jetbrains.uast.* @ApiStatus.Internal class KotlinLazyUBlockExpression( override val uastParent: UElement?, expressionProducer: (expressionParent: UElement) -> List<UExpression> ) : UBlockExpression { override val psi: PsiElement? get() = null override val javaPsi: PsiElement? get() = null override val sourcePsi: PsiElement? get() = null override val uAnnotations: List<UAnnotation> = emptyList() override val expressions by lz { expressionProducer(this) } companion object { fun create(initializers: List<KtAnonymousInitializer>, uastParent: UElement): UBlockExpression { val languagePlugin = uastParent.getLanguagePlugin() return KotlinLazyUBlockExpression(uastParent) { expressionParent -> initializers.map { languagePlugin.convertOpt(it.body, expressionParent) ?: UastEmptyExpression(expressionParent) } } } } }
apache-2.0
9b0f1d8fc609da14dcfcc42451c3e1ff
40.870968
158
0.718798
5.031008
false
false
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/tv/TvActivity.kt
1
3195
package com.stevenschoen.putionew.tv import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import com.stevenschoen.putionew.LoginActivity import com.stevenschoen.putionew.PutioApplication import com.stevenschoen.putionew.R import com.stevenschoen.putionew.model.files.PutioFile import io.reactivex.subjects.BehaviorSubject import java.util.* class TvActivity : FragmentActivity() { private val displayedFolders = ArrayList<PutioFile>() private val folders by lazy { BehaviorSubject.createDefault<List<PutioFile>>(listOf(PutioFile.makeRootFolder(resources))) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val application = application as PutioApplication if (application.isLoggedIn) { init() } else { val loginIntent = Intent(this, LoginActivity::class.java) startActivity(loginIntent) finish() return } } private fun init() { setContentView(R.layout.tv_activity) val stackView = findViewById<HorizontalStackLayout>(R.id.tv_stack) fun addFolder(folder: PutioFile) { supportFragmentManager.beginTransaction() .add(R.id.tv_stack, TvFolderFragment.newInstance(this@TvActivity, folder), makeFolderFragTag(folder)) .commitNow() displayedFolders.add(folder) } fun removeLastFolder() { val lastFolder = displayedFolders.last() supportFragmentManager.beginTransaction() .remove(supportFragmentManager.findFragmentByTag(makeFolderFragTag(lastFolder))!!) .commitNow() displayedFolders.removeAt(displayedFolders.lastIndex) } addFolder(PutioFile.makeRootFolder(resources)) folders.subscribe { newFolders -> while (displayedFolders.size > newFolders.size) { removeLastFolder() } for ((index, newFolder) in newFolders.withIndex()) { if (index <= displayedFolders.lastIndex) { val displayedFolder = displayedFolders[index] if (newFolder.id != displayedFolder.id) { (index..displayedFolders.lastIndex).forEach { removeLastFolder() } } } else { addFolder(newFolder) } } getLastFolderFragment().requestFocusWhenPossible = true } } override fun onAttachFragment(fragment: Fragment) { super.onAttachFragment(fragment) if (fragment is TvFolderFragment) { fragment.onFolderSelected = { folder -> folders.onNext(folders.value!! + folder) } } } fun getLastFolderFragment() = supportFragmentManager.findFragmentByTag(makeFolderFragTag(displayedFolders.last())) as TvFolderFragment override fun onBackPressed() { if (displayedFolders.size > 1) { val lastFolderFragment = supportFragmentManager.findFragmentByTag(makeFolderFragTag(displayedFolders.last())) if (lastFolderFragment != null && lastFolderFragment is TvFolderFragment) { folders.onNext(folders.value!!.dropLast(1)) } } else { super.onBackPressed() } } companion object { fun makeFolderFragTag(folder: PutioFile) = "folder_${folder.id}" } }
mit
93564d76b73b3836d3aead9e13e5f720
31.272727
136
0.710172
4.603746
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspExecutableParameterElement.kt
3
4605
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.room.compiler.processing.ksp import androidx.room.compiler.processing.XAnnotated import androidx.room.compiler.processing.XExecutableParameterElement import androidx.room.compiler.processing.XMemberContainer import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.ksp.KspAnnotated.UseSiteFilter.Companion.NO_USE_SITE_OR_METHOD_PARAMETER import androidx.room.compiler.processing.ksp.synthetic.KspSyntheticPropertyMethodElement import com.google.devtools.ksp.symbol.KSDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSPropertySetter import com.google.devtools.ksp.symbol.KSType import com.google.devtools.ksp.symbol.KSValueParameter internal class KspExecutableParameterElement( env: KspProcessingEnv, override val enclosingElement: KspExecutableElement, val parameter: KSValueParameter, val parameterIndex: Int ) : KspElement(env, parameter), XExecutableParameterElement, XAnnotated by KspAnnotated.create(env, parameter, NO_USE_SITE_OR_METHOD_PARAMETER) { override val name: String get() = parameter.name?.asString() ?: "_no_param_name" override val hasDefaultValue: Boolean get() = parameter.hasDefault private fun jvmTypeResolver(container: KSDeclaration?): KspJvmTypeResolutionScope { return KspJvmTypeResolutionScope.MethodParameter( kspExecutableElement = enclosingElement, parameterIndex = parameterIndex, annotated = parameter.type, container = container ) } override val type: KspType by lazy { asMemberOf(enclosingElement.enclosingElement.type?.ksType) } override val closestMemberContainer: XMemberContainer by lazy { enclosingElement.closestMemberContainer } override val fallbackLocationText: String get() = "$name in ${enclosingElement.fallbackLocationText}" override fun asMemberOf(other: XType): KspType { if (closestMemberContainer.type?.isSameType(other) != false) { return type } check(other is KspType) return asMemberOf(other.ksType) } private fun asMemberOf(ksType: KSType?): KspType { return env.wrap( originatingReference = parameter.type, ksType = parameter.typeAsMemberOf( functionDeclaration = enclosingElement.declaration, ksType = ksType ) ).withJvmTypeResolver( jvmTypeResolver( container = ksType?.declaration ) ) } override fun kindName(): String { return "function parameter" } companion object { fun create( env: KspProcessingEnv, parameter: KSValueParameter ): XExecutableParameterElement { val parent = checkNotNull(parameter.parent) { "Expected value parameter '$parameter' to contain a parent node." } return when (parent) { is KSFunctionDeclaration -> { val parameterIndex = parent.parameters.indexOf(parameter) check(parameterIndex > -1) { "Cannot find $parameter in $parent" } KspExecutableParameterElement( env = env, enclosingElement = KspExecutableElement.create(env, parent), parameter = parameter, parameterIndex = parameterIndex, ) } is KSPropertySetter -> KspSyntheticPropertyMethodElement.create( env, parent ).parameters.single() else -> error( "Don't know how to create a parameter element whose parent is a " + "'${parent::class}'" ) } } } }
apache-2.0
dcfd40a6dca68c5887a41fb240546824
36.439024
113
0.650163
5.16835
false
false
false
false
MoonlightOwl/Yui
src/main/kotlin/totoro/yui/util/F.kt
1
1137
package totoro.yui.util /** * IRC text formatting codes */ @Suppress("unused", "MemberVisibilityCanBePrivate") object F { const val Bold = "\u0002" const val Italic = "\u001D" const val Underlined = "\u001F" const val Reversed = "\u0016" const val Default = "\u000399" const val White = "\u000300" const val Black = "\u000301" const val Blue = "\u000302" const val Green = "\u000303" const val Red = "\u000304" const val Brown = "\u000305" const val Purple = "\u000306" const val Orange = "\u000307" const val Yellow = "\u000308" const val Lime = "\u000309" const val Teal = "\u000310" const val Cyan = "\u000311" const val Royal = "\u000312" const val Pink = "\u000313" const val Gray = "\u000314" const val Silver = "\u000315" const val Reset = "\u000F" fun mix(foreground: String, background: String): String { return foreground + "," + background.drop(1) } val colors = arrayOf( White, Black, Blue, Green, Red, Brown, Purple, Orange, Yellow, Lime, Teal, Cyan, Royal, Pink, Gray, Silver ) }
mit
c56e7a26dd81f56808eb7ca6ab7cd2d2
26.731707
66
0.610378
3.445455
false
false
false
false
GunoH/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableModuleLibraryTableBridge.kt
1
9801
// 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.ide.impl.legacyBridge.module.roots import com.google.common.collect.HashBiMap import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.openapi.roots.impl.ModuleLibraryTableBase import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.PersistentLibraryKind import com.intellij.openapi.util.Disposer import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntityWithExcludes import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryPropertiesEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryId import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer internal class ModifiableModuleLibraryTableBridge(private val modifiableModel: ModifiableRootModelBridgeImpl) : ModuleLibraryTableBase(), ModuleLibraryTableBridge { private val copyToOriginal = HashBiMap.create<LibraryBridge, LibraryBridge>() init { val storage = modifiableModel.moduleBridge.entityStorage.current libraryEntities() .forEach { libraryEntry -> val originalLibrary = storage.libraryMap.getDataByEntity(libraryEntry) if (originalLibrary != null) { //if a module-level library from ModifiableRootModel is changed, the changes must not be committed to the model until //ModifiableRootModel is committed. So we place copies of LibraryBridge instances to the modifiable model. If the model is disposed //these copies are disposed; if the model is committed they'll be included to the model, and the original instances will be disposed. val modifiableCopy = LibraryBridgeImpl(this, modifiableModel.project, libraryEntry.symbolicId, modifiableModel.entityStorageOnDiff, modifiableModel.diff) copyToOriginal[modifiableCopy] = originalLibrary modifiableModel.diff.mutableLibraryMap.addMapping(libraryEntry, modifiableCopy) } } } private fun libraryEntities(): Sequence<LibraryEntity> { val moduleLibraryTableId = getTableId() return modifiableModel.entityStorageOnDiff.current .entities(LibraryEntity::class.java) .filter { it.tableId == moduleLibraryTableId } } override fun getLibraryIterator(): Iterator<Library> { val storage = modifiableModel.entityStorageOnDiff.current return libraryEntities().mapNotNull { storage.libraryMap.getDataByEntity(it) }.iterator() } override fun createLibrary(name: String?, type: PersistentLibraryKind<*>?, externalSource: ProjectModelExternalSource?): Library { modifiableModel.assertModelIsLive() val tableId = getTableId() val libraryEntityName = LibraryNameGenerator.generateLibraryEntityName(name) { existsName -> LibraryId(existsName, tableId) in modifiableModel.diff } val libraryEntity = modifiableModel.diff.addLibraryEntity( roots = emptyList(), tableId = tableId, name = libraryEntityName, excludedRoots = emptyList(), source = modifiableModel.moduleEntity.entitySource ) if (type != null) { modifiableModel.diff.addLibraryPropertiesEntity( library = libraryEntity, libraryType = type.kindId, propertiesXmlTag = LegacyBridgeModifiableBase.serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG, type.createDefaultProperties()) ) } return createAndAddLibrary(libraryEntity, false, ModuleDependencyItem.DependencyScope.COMPILE) } private fun createAndAddLibrary(libraryEntity: LibraryEntity, exported: Boolean, scope: ModuleDependencyItem.DependencyScope): LibraryBridgeImpl { val libraryId = libraryEntity.symbolicId modifiableModel.appendDependency(ModuleDependencyItem.Exportable.LibraryDependency(library = libraryId, exported = exported, scope = scope)) val library = LibraryBridgeImpl( libraryTable = ModuleRootComponentBridge.getInstance(modifiableModel.module).moduleLibraryTable, project = modifiableModel.project, initialId = libraryEntity.symbolicId, initialEntityStorage = modifiableModel.entityStorageOnDiff, targetBuilder = modifiableModel.diff ) modifiableModel.diff.mutableLibraryMap.addMapping(libraryEntity, library) return library } private fun getTableId() = LibraryTableId.ModuleLibraryTableId(modifiableModel.moduleEntity.symbolicId) internal fun addLibraryCopy(original: LibraryBridgeImpl, exported: Boolean, scope: ModuleDependencyItem.DependencyScope): LibraryBridgeImpl { val tableId = getTableId() val libraryEntityName = LibraryNameGenerator.generateLibraryEntityName(original.name) { existsName -> LibraryId(existsName, tableId) in modifiableModel.diff } val originalEntity = original.librarySnapshot.libraryEntity val libraryEntity = modifiableModel.diff.addLibraryEntityWithExcludes( roots = originalEntity.roots, tableId = tableId, name = libraryEntityName, excludedRoots = originalEntity.excludedRoots, source = modifiableModel.moduleEntity.entitySource ) val originalProperties = originalEntity.libraryProperties if (originalProperties != null) { modifiableModel.diff.addLibraryPropertiesEntity( library = libraryEntity, libraryType = originalProperties.libraryType, propertiesXmlTag = originalProperties.propertiesXmlTag ) } return createAndAddLibrary(libraryEntity, exported, scope) } override fun removeLibrary(library: Library) { modifiableModel.assertModelIsLive() library as LibraryBridge val libraryEntity = modifiableModel.diff.findLibraryEntity(library) ?: run { copyToOriginal.inverse()[library]?.let { libraryCopy -> modifiableModel.diff.findLibraryEntity(libraryCopy) } } if (libraryEntity == null) { LOG.error("Cannot find entity for library ${library.name}") return } val libraryId = libraryEntity.symbolicId modifiableModel.removeDependencies { _, item -> item is ModuleDependencyItem.Exportable.LibraryDependency && item.library == libraryId } modifiableModel.diff.removeEntity(libraryEntity) Disposer.dispose(library) } internal fun restoreLibraryMappingsAndDisposeCopies() { libraryIterator.forEach { val originalLibrary = copyToOriginal[it] //originalLibrary may be null if the library was added after the table was created if (originalLibrary != null) { val mutableLibraryMap = modifiableModel.diff.mutableLibraryMap mutableLibraryMap.addMapping(mutableLibraryMap.getEntities(it as LibraryBridge).single(), originalLibrary) } Disposer.dispose(it) } } internal fun restoreMappingsForUnchangedLibraries(changedLibs: Set<LibraryId>) { if (copyToOriginal.isEmpty()) return libraryIterator.forEach { val originalLibrary = copyToOriginal[it] //originalLibrary may be null if the library was added after the table was created if (originalLibrary != null && !changedLibs.contains(originalLibrary.libraryId) && originalLibrary.hasSameContent(it)) { val mutableLibraryMap = modifiableModel.diff.mutableLibraryMap mutableLibraryMap.addMapping(mutableLibraryMap.getEntities(it as LibraryBridge).single(), originalLibrary) Disposer.dispose(it) } } } internal fun disposeOriginalLibrariesAndUpdateCopies() { if (copyToOriginal.isEmpty()) return val storage = WorkspaceModel.getInstance(modifiableModel.project).entityStorage libraryIterator.forEach { copy -> copy as LibraryBridgeImpl copy.entityStorage = storage copy.libraryTable = ModuleRootComponentBridge.getInstance(module).moduleLibraryTable copy.clearTargetBuilder() val original = copyToOriginal[copy] if (original != null) { Disposer.dispose(original) } } } override fun isChanged(): Boolean { return modifiableModel.isChanged } override val module: Module get() = modifiableModel.module companion object { private val LOG = logger<ModifiableModuleLibraryTableBridge>() } }
apache-2.0
cf37e5b2fc849e70e89713496dd4ca94
44.170507
143
0.744618
5.629523
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/containers/BidirectionalLongMultiMap.kt
5
3523
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl.containers import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap import it.unimi.dsi.fastutil.longs.LongOpenHashSet import it.unimi.dsi.fastutil.longs.LongSet import it.unimi.dsi.fastutil.longs.LongSets import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.* /** * Bidirectional multimap that has longs as keys */ class BidirectionalLongMultiMap<V> { private val keyToValues: Long2ObjectOpenHashMap<ObjectOpenHashSet<V>> private val valueToKeys: Object2ObjectOpenHashMap<V, LongOpenHashSet> constructor() { keyToValues = Long2ObjectOpenHashMap() @Suppress("SSBasedInspection") valueToKeys = Object2ObjectOpenHashMap() } private constructor( keyToValues: Long2ObjectOpenHashMap<ObjectOpenHashSet<V>>, valueToKeys: Object2ObjectOpenHashMap<V, LongOpenHashSet>, ) { this.keyToValues = keyToValues this.valueToKeys = valueToKeys } fun getValues(key: Long): Set<V> = keyToValues.get(key) ?: Collections.emptySet() fun getKeys(value: V): LongSet = valueToKeys.get(value) ?: LongSets.emptySet() fun containsKey(key: Long): Boolean = keyToValues.containsKey(key) fun containsValue(value: V): Boolean = valueToKeys.containsKey(value) fun put(key: Long, value: V): Boolean { var keys: LongSet? = valueToKeys[value] if (keys == null) { keys = LongOpenHashSet() valueToKeys[value] = keys } keys.add(key) var values: MutableSet<V>? = keyToValues[key] if (values == null) { @Suppress("SSBasedInspection") values = ObjectOpenHashSet() keyToValues[key] = values } return values.add(value) } fun removeKey(key: Long): Boolean { val values = keyToValues[key] ?: return false for (v in values) { val keys: LongSet = valueToKeys[v]!! keys.remove(key) if (keys.isEmpty()) { valueToKeys.remove(v) } } keyToValues.remove(key) return true } fun remove(key: Long, value: V) { val values = keyToValues[key] val keys: LongSet? = valueToKeys[value] if (keys != null && values != null) { keys.remove(key) values.remove(value) if (keys.isEmpty()) { valueToKeys.remove(value) } if (values.isEmpty()) { keyToValues.remove(key) } } } fun isEmpty(): Boolean { return keyToValues.isEmpty() && valueToKeys.isEmpty() } fun removeValue(value: V): Boolean { val keys = valueToKeys[value] ?: return false keys.iterator().forEach { k -> val values = keyToValues[k] values.remove(value) if (values.isEmpty()) { keyToValues.remove(k) } } valueToKeys.remove(value) return true } fun clear() { keyToValues.clear() valueToKeys.clear() } val keys: LongSet get() = keyToValues.keys val values: Set<V> get() = valueToKeys.keys fun copy(): BidirectionalLongMultiMap<V> { val newKeyToValues = keyToValues.clone() newKeyToValues.replaceAll { _, value -> value.clone() } val newValuesToKeys = valueToKeys.clone() newValuesToKeys.replaceAll { _, value -> value.clone() } return BidirectionalLongMultiMap(newKeyToValues, newValuesToKeys) } internal fun toMap(): Map<Long, Set<V>> { return keyToValues } }
apache-2.0
bba9dcfab41ed4cbef42837d88b1c5ad
27.885246
158
0.681238
3.90144
false
false
false
false
jwren/intellij-community
java/compiler/tests/com/intellij/compiler/artifacts/workspaceModel/LoadingInvalidProjectTest.kt
3
2118
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.compiler.artifacts.workspaceModel import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.module.ConfigurationErrorDescription import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier import com.intellij.openapi.project.Project import com.intellij.packaging.artifacts.ArtifactManager import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.TemporaryDirectory import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.nio.file.Path import java.nio.file.Paths class LoadingInvalidProjectTest { @JvmField @Rule val tempDirectory = TemporaryDirectory() @JvmField @Rule val disposable = DisposableRule() private val errors = ArrayList<ConfigurationErrorDescription>() @Before fun setUp() { ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(disposable.disposable, errors::add) } @Test fun `test duplicating artifacts`() { loadProjectAndCheckResults("duplicating-artifacts") { project -> val artifactsName = ReadAction.compute<String, Exception> { ArtifactManager.getInstance(project).artifacts.single().name } assertThat(artifactsName).isEqualTo("foo") assertThat(errors).isEmpty() } } private fun loadProjectAndCheckResults(testDataDirName: String, checkProject: suspend (Project) -> Unit) { return com.intellij.testFramework.loadProjectAndCheckResults( listOf(testDataRoot.resolve("common"), testDataRoot.resolve(testDataDirName)), tempDirectory, checkProject) } companion object { @JvmField @ClassRule val appRule = ApplicationRule() private val testDataRoot: Path get() = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("platform/platform-tests/testData/configurationStore/invalid") } }
apache-2.0
4ea59b0b344faf70c50e1b4c51da40f5
34.915254
132
0.794145
4.813636
false
true
false
false
JetBrains/kotlin-native
backend.native/tests/interop/basics/structs.kt
2
1890
import cstructs.* import kotlinx.cinterop.* import kotlin.test.* fun main() { produceComplex().useContents { assertEquals(ui, 128u) ui = 333u assertEquals(ui, 333u) assertEquals(t.i, 1) t.i += 15 assertEquals(t.i, 16) assertEquals(next, null) next = this.ptr assertEquals(next, this.ptr) // Check null pointer because it has Nothing? type. next = null assertEquals(next, null) assertEquals(e, E.R) e = E.G assertEquals(e, E.G) assertEquals(K, nonStrict) nonStrict = S assertEquals(S, nonStrict) assertEquals(arr[0], -51) assertEquals(arr[1], -19) arr[0] = 51 arr[1] = 19 assertEquals(arr[0], 51) assertEquals(arr[1], 19) assertEquals(true, b) b = false assertEquals(false, b) // Check that subtyping via Nothing-returning functions does not break compiler. assertFailsWith<NotImplementedError> { ui = TODO() t.i = TODO() next = TODO() e = TODO() nonStrict = TODO() b = TODO() } } memScoped { val packed = alloc<Packed>() packed.i = -1 assertEquals(-1, packed.i) packed.e = E.R assertEquals(E.R, packed.e) // Check that subtyping via Nothing-returning functions does not break compiler. assertFailsWith<NotImplementedError> { packed.i = TODO() packed.e = TODO() } } // Check that generics doesn't break anything. checkEnumSubTyping(E.R) checkIntSubTyping(630090) } fun <T : E> checkEnumSubTyping(e: T) = memScoped { val s = alloc<Complex>() s.e = e } fun <T : Int> checkIntSubTyping(x: T) = memScoped { val s = alloc<Trivial>() s.i = x }
apache-2.0
83eb9988c87644fd12dcacef000ef7e0
23.881579
88
0.545503
3.929314
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ui/tabs/FileColorsUsagesCollector.kt
10
1654
// 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.ui.tabs import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventId1 import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.project.Project import com.intellij.ui.FileColorManager class FileColorsUsagesCollector : ProjectUsagesCollector() { private val GROUP = EventLogGroup("appearance.file.colors", 2) private val FILE_COLORS: EventId1<Boolean> = GROUP.registerEvent("file.colors", EventFields.Enabled) private val EDITOR_TABS: EventId1<Boolean> = GROUP.registerEvent("editor.tabs", EventFields.Enabled) private val PROJECT_VIEW: EventId1<Boolean> = GROUP.registerEvent("project.view", EventFields.Enabled) override fun getGroup() = GROUP override fun getMetrics(project: Project): MutableSet<MetricEvent> { val set = mutableSetOf<MetricEvent>() val manager = FileColorManager.getInstance(project) ?: return set val enabledFileColors = manager.isEnabled val useInEditorTabs = enabledFileColors && manager.isEnabledForTabs val useInProjectView = enabledFileColors && manager.isEnabledForProjectView if (!enabledFileColors) set.add(FILE_COLORS.metric(false)) if (!useInEditorTabs) set.add(EDITOR_TABS.metric(false)) if (!useInProjectView) set.add(PROJECT_VIEW.metric(false)) return set } }
apache-2.0
2f2ea7c7ae275a81355b82881f6e365f
50.6875
140
0.794438
4.262887
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/BaseCommitExecutorAction.kt
4
1691
// Copyright 2000-2021 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.openapi.vcs.changes.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.vcs.actions.getContextCommitWorkflowHandler import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.util.ui.JButtonAction import com.intellij.vcs.commit.CommitWorkflowHandler import javax.swing.JButton abstract class BaseCommitExecutorAction : JButtonAction(null) { init { isEnabledInModalContext = true } override fun createButton(): JButton = JButton().apply { isOpaque = false } override fun update(e: AnActionEvent) { val workflowHandler = e.getContextCommitWorkflowHandler() val executor = getCommitExecutor(workflowHandler) e.presentation.isVisible = workflowHandler != null && executor != null e.presentation.isEnabled = workflowHandler != null && executor != null && workflowHandler.isExecutorEnabled(executor) } override fun actionPerformed(e: AnActionEvent) { val workflowHandler = e.getContextCommitWorkflowHandler()!! val executor = getCommitExecutor(workflowHandler)!! workflowHandler.execute(executor) } protected open val executorId: String = "" protected open fun getCommitExecutor(handler: CommitWorkflowHandler?) = handler?.getExecutor(executorId) } internal class DefaultCommitExecutorAction(private val executor: CommitExecutor) : BaseCommitExecutorAction() { init { templatePresentation.text = executor.actionText } override fun getCommitExecutor(handler: CommitWorkflowHandler?): CommitExecutor = executor }
apache-2.0
dc8656298c0390e72d1b4ccc50841cce
38.348837
140
0.7877
5.093373
false
false
false
false