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
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/lints/RsBareTraitObjectsInspection.kt
2
2314
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.ide.inspections.RsProblemsHolder import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.dyn import org.rust.lang.core.psi.ext.isAtLeastEdition2018 import org.rust.lang.core.psi.ext.skipParens import org.rust.lang.core.resolve.ref.deepResolve class RsBareTraitObjectsInspection : RsLintInspection() { override fun getLint(element: PsiElement): RsLint = RsLint.BareTraitObjects override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() { override fun visitTypeReference(typeReference: RsTypeReference) { if (!typeReference.isAtLeastEdition2018) return val traitType = typeReference.skipParens() as? RsTraitType val typePath = (typeReference.skipParens() as? RsPathType)?.path val isTraitType = traitType != null || typePath?.reference?.deepResolve() is RsTraitItem val isSelf = typePath?.cself != null val hasDyn = traitType?.dyn != null val hasImpl = traitType?.impl != null if (!isTraitType || isSelf || hasDyn || hasImpl) return holder.registerLintProblem( typeReference, "Trait objects without an explicit 'dyn' are deprecated", fixes = listOf(AddDynKeywordFix()) ) } } private class AddDynKeywordFix : LocalQuickFix { override fun getFamilyName(): String = "Add 'dyn' keyword to trait object" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val target = descriptor.psiElement as RsTypeReference val typeElement = target.skipParens() val traitText = (typeElement as? RsPathType)?.path?.text ?: (typeElement as RsTraitType).text val new = RsPsiFactory(project).createDynTraitType(traitText) target.replace(new) } } }
mit
83225a8b45bff226b60dd0fe7b5f6536
41.851852
105
0.669836
4.741803
false
false
false
false
edx/edx-app-android
OpenEdXMobile/src/main/java/org/edx/mobile/deeplink/PushLinkManager.kt
1
1700
package org.edx.mobile.deeplink import android.app.Activity import android.os.Bundle import com.google.firebase.messaging.RemoteMessage import de.greenrobot.event.EventBus import org.edx.mobile.event.PushLinkReceivedEvent import org.edx.mobile.logger.Logger object PushLinkManager { val logger = Logger(this.javaClass) fun checkAndReactIfFCMNotificationReceived(activity: Activity, bundle: Bundle?) { val screenName = bundle?.getString(DeepLink.Keys.SCREEN_NAME) if (screenName != null && screenName.isNotEmpty()) { // Received FCM background notification onFCMBackgroundNotificationReceived(activity, screenName, bundle) } } private fun onFCMBackgroundNotificationReceived(activity: Activity, screenName: String, bundle: Bundle) { DeepLinkManager.onDeepLinkReceived(activity, DeepLink(screenName, bundle)) } fun onFCMForegroundNotificationReceived(remoteMessage: RemoteMessage?) { // Body of message is mandatory for a notification remoteMessage?.notification?.body?.run { logger.debug("Message Notification Body: " + remoteMessage.notification?.body) val screenName = remoteMessage.data[DeepLink.Keys.SCREEN_NAME] ?: "" val pushLink = PushLink(screenName, remoteMessage.notification?.title, this, remoteMessage.data) // Broadcast the PushLink to all activities and let the foreground activity do the further action EventBus.getDefault().post(PushLinkReceivedEvent(pushLink)) } } fun onPushLinkActionGranted(activity: Activity, pushLink: PushLink) { DeepLinkManager.onDeepLinkReceived(activity, pushLink) } }
apache-2.0
dcf9dcc8c23a3d5ca8ded829a4a866ea
42.589744
109
0.73
4.80226
false
false
false
false
wordpress-mobile/AztecEditor-Android
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecDynamicImageSpan.kt
1
5350
package org.wordpress.aztec.spans import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.Drawable import android.text.style.DynamicDrawableSpan import org.wordpress.aztec.AztecText import java.lang.ref.WeakReference abstract class AztecDynamicImageSpan(val context: Context, protected var imageDrawable: Drawable?) : DynamicDrawableSpan() { var textView: WeakReference<AztecText>? = null var aspectRatio: Double = 1.0 private var measuring = false companion object { @JvmStatic protected fun setInitBounds(drawable: Drawable?) { drawable?.let { if (it.bounds.isEmpty && (it.intrinsicWidth > -1 || it.intrinsicHeight > -1)) { it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight) } } } @JvmStatic protected fun getWidth(drawable: Drawable?): Int { drawable?.let { if (it.intrinsicWidth < 0) { // client may have set the bounds manually so, use those return it.bounds.width() } else { return it.intrinsicWidth } } return 0 } @JvmStatic protected fun getHeight(drawable: Drawable?): Int { drawable?.let { if (it.intrinsicHeight < 0) { // client may have set the bounds manually so, use those return it.bounds.height() } else { return it.intrinsicHeight } } return 0 } } init { computeAspectRatio() setInitBounds(imageDrawable) } fun computeAspectRatio() { if ((imageDrawable?.intrinsicWidth ?: -1) > -1 && (imageDrawable?.intrinsicHeight ?: -1) > -1) { aspectRatio = 1.0 * (imageDrawable?.intrinsicWidth ?: 1) / (imageDrawable?.intrinsicHeight ?: 1) } else if (!(imageDrawable?.bounds?.isEmpty ?: true)) { aspectRatio = 1.0 * (imageDrawable?.bounds?.width() ?: 0) / (imageDrawable?.bounds?.height() ?: 1) } else { aspectRatio = 1.0 } } override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, metrics: Paint.FontMetricsInt?): Int { val sizeRect = adjustBounds(start) if (metrics != null && sizeRect.height() > 0) { metrics.ascent = - sizeRect.height() metrics.descent = 0 metrics.top = metrics.ascent metrics.bottom = 0 } if (sizeRect.width() > 0) { return sizeRect.width() } else { // This block of code was added in order to resolve // span overlap issue on Chromebook devices // -> https://github.com/wordpress-mobile/AztecEditor-Android/issues/836 return super.getSize(paint, text, start, end, metrics) } } fun adjustBounds(start: Int): Rect { if (textView == null || textView?.get()?.widthMeasureSpec == 0) { return Rect(imageDrawable?.bounds ?: Rect(0, 0, 0, 0)) } val layout = textView?.get()?.layout if (measuring || layout == null) { // if we're in pre-layout phase, just return an empty rect // Update: Previous version of this code was: return Rect(0, 0, 1, 1) // but we needed to change it as it caused span overlap issue on Chromebook // devices -> https://github.com/wordpress-mobile/AztecEditor-Android/issues/836 return Rect(0, 0, 0, 0) } val line = layout.getLineForOffset(start) val maxWidth = getMaxWidth(layout.getParagraphRight(line) - layout.getParagraphLeft(line)) // use the original bounds if non-zero, otherwise try the intrinsic sizes. If those are not available then // just assume maximum size. var width = if ((imageDrawable?.intrinsicWidth ?: -1) > -1) imageDrawable?.intrinsicWidth ?: -1 else maxWidth var height = if ((imageDrawable?.intrinsicHeight ?: -1) > -1) imageDrawable?.intrinsicHeight ?: -1 else (width / aspectRatio).toInt() if (width > maxWidth) { width = maxWidth height = (width / aspectRatio).toInt() } imageDrawable?.bounds = Rect(0, 0, width, height) return Rect(imageDrawable?.bounds ?: Rect(0, 0, 0, 0)) } open fun getMaxWidth(editorWidth: Int): Int { return editorWidth } override fun getDrawable(): Drawable? { return imageDrawable } open fun setDrawable(newDrawable: Drawable?) { imageDrawable = newDrawable setInitBounds(newDrawable) computeAspectRatio() } override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) { canvas.save() if (imageDrawable != null) { var transY = top if (mVerticalAlignment == ALIGN_BASELINE) { transY -= paint.fontMetricsInt.descent } canvas.translate(x, transY.toFloat()) imageDrawable!!.draw(canvas) } canvas.restore() } }
mpl-2.0
af07ff4ec274c5ff85b212825c4b63a4
33.076433
136
0.578879
4.668412
false
false
false
false
esofthead/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/view/settings/ComponentUrlResolver.kt
3
4114
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.view.settings import com.mycollab.common.UrlTokenizer import com.mycollab.core.ResourceNotFoundException import com.mycollab.db.arguments.NumberSearchField import com.mycollab.vaadin.EventBusFactory import com.mycollab.module.project.event.ProjectEvent import com.mycollab.module.project.view.ProjectUrlResolver import com.mycollab.module.project.view.parameters.ComponentScreenData import com.mycollab.module.project.view.parameters.ProjectScreenData import com.mycollab.module.project.domain.Component import com.mycollab.module.project.domain.criteria.ComponentSearchCriteria import com.mycollab.module.project.service.ComponentService import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.mvp.PageActionChain /** * @author MyCollab Ltd * @since 6.0.0 */ class ComponentUrlResolver : ProjectUrlResolver() { init { this.addSubResolver("list", ListUrlResolver()) this.addSubResolver("add", AddUrlResolver()) this.addSubResolver("edit", EditUrlResolver()) this.addSubResolver("preview", PreviewUrlResolver()) } private class ListUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val projectId = UrlTokenizer(params[0]).getInt() val searchCriteria = ComponentSearchCriteria() searchCriteria.projectId = NumberSearchField(projectId) val chain = PageActionChain(ProjectScreenData.Goto(projectId), ComponentScreenData.Search(searchCriteria)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } private class AddUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val projectId = UrlTokenizer(params[0]).getInt() val chain = PageActionChain(ProjectScreenData.Goto(projectId), ComponentScreenData.Add(Component())) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } private class PreviewUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val token = UrlTokenizer(params[0]) val projectId = token.getInt() val componentId = token.getInt() val chain = PageActionChain(ProjectScreenData.Goto(projectId), ComponentScreenData.Read(componentId)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } private class EditUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val token = UrlTokenizer(params[0]) val projectId = token.getInt() val componentId = token.getInt() val componentService = AppContextUtil.getSpringBean(ComponentService::class.java) val component = componentService.findById(componentId, AppUI.accountId) if (component != null) { val chain = PageActionChain(ProjectScreenData.Goto(projectId), ComponentScreenData.Edit(component)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } else { throw ResourceNotFoundException("Can not find component $componentId") } } } }
agpl-3.0
5d3e0edb38edc4e2d0ecae0d66ebe098
43.717391
115
0.707999
4.967391
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/mangacatalog/readswordartonlinemangaonline/src/ReadSwordArtOnlineMangaOnline.kt
1
2520
package eu.kanade.tachiyomi.extension.en.readswordartonlinemangaonline import eu.kanade.tachiyomi.multisrc.mangacatalog.MangaCatalog import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.util.asJsoup import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Request import rx.Observable import org.jsoup.nodes.Document import org.jsoup.nodes.Element class ReadSwordArtOnlineMangaOnline : MangaCatalog("Read Sword Art Online Manga Online", "https://manga.watchsao.tv", "en") { override val sourceList = listOf( Pair("SAO", "$baseUrl/manga/sword-art-online/"), Pair("Alicization", "$baseUrl/manga/sword-art-online-project-alicization/"), Pair("Progressive", "$baseUrl/manga/sword-art-online-progressive/"), Pair("Progressive 2", "$baseUrl/manga/sword-art-online-progressive-barcarolle-of-froth/"), Pair("Fairy Dance", "$baseUrl/manga/sword-art-online-fairy-dance/"), Pair("GGO", "$baseUrl/manga/sword-art-online-alternative-gun-gale-online/"), Pair("4-koma", "$baseUrl/manga/sword-art-online-4-koma/"), Pair("Aincrad", "$baseUrl/manga/sword-art-online-aincrad-night-of-kirito/"), Pair("Girls Ops", "$baseUrl/manga/sword-art-online-girls-ops/"), Pair("Anthology", "$baseUrl/manga/sword-art-online-comic-anthology/"), Pair("Lycoris", "$baseUrl/manga/sword-art-online-lycoris/"), Pair("Hollow Realization", "$baseUrl/manga/sword-art-online-hollow-realization/"), Pair("Ordinal Scale", "$baseUrl/manga/sword-art-online-ordinal-scale/"), ).sortedBy { it.first }.distinctBy { it.second } override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { description = document.select("div.card-body > p").text() title = document.select("h2 > span").text() thumbnail_url = document.select(".card-img-right").attr("src") } override fun chapterListSelector(): String = "tbody > tr" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { name = element.select("td:first-child").text() url = element.select("a.btn-primary").attr("abs:href") date_upload = System.currentTimeMillis() //I have no idear how to parse Date stuff } }
apache-2.0
f761389a660ed33a39e01a656f4e2582
55
125
0.715079
3.705882
false
false
false
false
inorichi/tachiyomi-extensions
src/ar/gmanga/src/eu/kanade/tachiyomi/extension/ar/gmanga/GmangaCryptoUtils.kt
1
1383
package eu.kanade.tachiyomi.extension.ar.gmanga import android.util.Base64 import java.security.MessageDigest import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec fun decrypt(responseData: String): String { val enc = responseData.split("|") val secretKey = enc[3].sha256().hexStringToByteArray() return enc[0].aesDecrypt(secretKey, enc[2]) } private fun String.hexStringToByteArray(): ByteArray { val len = this.length val data = ByteArray(len / 2) var i = 0 while (i < len) { data[i / 2] = ( (Character.digit(this[i], 16) shl 4) + Character.digit(this[i + 1], 16) ).toByte() i += 2 } return data } private fun String.sha256(): String { return MessageDigest .getInstance("SHA-256") .digest(this.toByteArray()) .fold("", { str, it -> str + "%02x".format(it) }) } private fun String.aesDecrypt(secretKey: ByteArray, ivString: String): String { val c = Cipher.getInstance("AES/CBC/PKCS5Padding") val sk = SecretKeySpec(secretKey, "AES") val iv = IvParameterSpec(Base64.decode(ivString.toByteArray(Charsets.UTF_8), Base64.DEFAULT)) c.init(Cipher.DECRYPT_MODE, sk, iv) val byteStr = Base64.decode(this.toByteArray(Charsets.UTF_8), Base64.DEFAULT) return String(c.doFinal(byteStr)) }
apache-2.0
8bc0be8e6655a481734e0ed25a62e401
29.733333
97
0.663774
3.639474
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/InfoInterceptor.kt
3
939
package info.nightscout.androidaps.plugins.general.tidepool.comm import info.nightscout.androidaps.logging.L import okhttp3.Interceptor import okhttp3.Response import okio.Buffer import org.slf4j.LoggerFactory import java.io.IOException class InfoInterceptor(tag: String) : Interceptor { private val log = LoggerFactory.getLogger(L.TIDEPOOL) private var tag = "interceptor" init { this.tag = tag } @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() request.body?.let { if (L.isEnabled(L.TIDEPOOL)) { log.debug("Interceptor Body size: " + it.contentLength()) val requestBuffer = Buffer() it.writeTo(requestBuffer) log.debug("Interceptor Body: " + requestBuffer.readUtf8()) } } return chain.proceed(request) } }
agpl-3.0
c413673b552929fc1391b5fba265c8ce
28.34375
74
0.650692
4.287671
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/XPathSpec.kt
1
3483
/* * Copyright (C) 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.xpath.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion import uk.co.reecedunn.intellij.plugin.xpm.lang.impl.W3CSpecification import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmIcons import javax.swing.Icon @Suppress("MemberVisibilityCanBePrivate", "unused") object XPathSpec : ItemPresentation, XpmSpecificationType { // region ItemPresentation override fun getPresentableText(): String = "XML Path Language (XPath)" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = XpmIcons.W3.Product // endregion // region XpmSpecificationType override val id: String = "xpath" override val presentation: ItemPresentation get() = this // endregion // region Versions val REC_1_0_19991116: XpmSpecificationVersion = W3CSpecification( this, "1.0-19991116", "1.0", "https://www.w3.org/TR/1999/REC-xpath-19991116/" ) val WD_2_0_20030502: XpmSpecificationVersion = W3CSpecification( this, "2.0-20030502", "2.0 (Working Draft 02 May 2003)", "https://www.w3.org/TR/2003/WD-xpath20-20030502/" ) val REC_2_0_20070123: XpmSpecificationVersion = W3CSpecification( this, "2.0-20070123", "2.0 (First Edition)", "https://www.w3.org/TR/2007/REC-xpath20-20070123/" ) val REC_2_0_20101214: XpmSpecificationVersion = W3CSpecification( this, "2.0-20101214", "2.0 (Second Edition)", "http://www.w3.org/TR/2010/REC-xpath20-20101214/" ) val REC_3_0_20140408: XpmSpecificationVersion = W3CSpecification( this, "3.0-20140408", "3.0", "http://www.w3.org/TR/2014/REC-xpath-30-20140408/" ) val CR_3_1_20151217: XpmSpecificationVersion = W3CSpecification( this, "3.1-20151217", "3.1 (Candidate Recommendation 17 December 2015)", "https://www.w3.org/TR/2015/CR-xpath-31-20151217/" ) val REC_3_1_20170321: XpmSpecificationVersion = W3CSpecification( this, "3.1-20170321", "3.1", "https://www.w3.org/TR/2017/REC-xpath-31-20170321/" ) val ED_4_0_20210113: XpmSpecificationVersion = W3CSpecification( this, "4.0-20210113", "4.0 (Editor's Draft 13 January 2021)", "https://qt4cg.org/branch/master/xquery-40/xpath-40.html" ) val versions: List<XpmSpecificationVersion> = listOf( REC_1_0_19991116, WD_2_0_20030502, REC_2_0_20070123, REC_2_0_20101214, REC_3_0_20140408, CR_3_1_20151217, REC_3_1_20170321, ED_4_0_20210113 ) // endregion }
apache-2.0
0359a783e74e39abf5d3b2283c421a8d
29.552632
75
0.658628
3.500503
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/max_speed/AddMaxSpeed.kt
1
2793
package de.westnordost.streetcomplete.quests.max_speed import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.ANYTHING_UNPAVED import de.westnordost.streetcomplete.data.meta.MAXSPEED_TYPE_KEYS import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.quest.AllCountriesExcept class AddMaxSpeed : OsmFilterQuestType<MaxSpeedAnswer>() { override val elementFilter = """ ways with highway ~ motorway|trunk|primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|unclassified|residential and !maxspeed and !maxspeed:advisory and !maxspeed:forward and !maxspeed:backward and ${MAXSPEED_TYPE_KEYS.joinToString(" and ") { "!$it" }} and surface !~ ${ANYTHING_UNPAVED.joinToString("|")} and cyclestreet != yes and bicycle_road != yes and motor_vehicle !~ private|no and vehicle !~ private|no and area != yes and (access !~ private|no or (foot and foot !~ private|no)) """ override val commitMessage = "Add speed limits" override val wikiLink = "Key:maxspeed" override val icon = R.drawable.ic_quest_max_speed override val hasMarkersAtEnds = true override val isSplitWayEnabled = true // see #813: US has different rules for each different state which need to be respected override val enabledInCountries = AllCountriesExcept("US") override val defaultDisabledMessage = R.string.default_disabled_msg_maxspeed override fun getTitle(tags: Map<String, String>) = if (tags.containsKey("name")) R.string.quest_maxspeed_name_title2 else R.string.quest_maxspeed_title_short2 override fun createForm() = AddMaxSpeedForm() override fun applyAnswerTo(answer: MaxSpeedAnswer, changes: StringMapChangesBuilder) { when(answer) { is MaxSpeedSign -> { changes.add("maxspeed", answer.value.toString()) changes.add("maxspeed:type", "sign") } is MaxSpeedZone -> { changes.add("maxspeed", answer.value.toString()) changes.add("maxspeed:type", answer.countryCode + ":" + answer.roadType) } is AdvisorySpeedSign -> { changes.add("maxspeed:advisory", answer.value.toString()) changes.add("maxspeed:type:advisory", "sign") } is IsLivingStreet -> { changes.modify("highway", "living_street") } is ImplicitMaxSpeed -> { changes.add("maxspeed:type", answer.countryCode + ":" + answer.roadType) } } } }
gpl-3.0
3b25a1c019fe7d9f5fb75cf9d7c13fda
43.333333
136
0.657358
4.433333
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/reified/arraysReification/instanceOfArrays.kt
1
1229
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS // WITH_RUNTIME inline fun <reified T> foo(x: Any?) = Pair(x is T, x is T?) inline fun <reified F> bar(y: Any?) = foo<Array<F>>(y) inline fun <reified F> barNullable(y: Any?) = foo<Array<F>?>(y) fun box(): String { val x1 = bar<String>(arrayOf("")) if (x1.toString() != "(true, true)") return "fail 1" val x3 = bar<String>(null) if (x3.toString() != "(false, true)") return "fail 3" val x4 = bar<String?>(null) if (x4.toString() != "(false, true)") return "fail 4" val x5 = bar<Double?>(arrayOf("")) if (x5.toString() != "(false, false)") return "fail 5" val x6 = bar<Double?>(null) if (x6.toString() != "(false, true)") return "fail 6" // barNullable val x7 = barNullable<String>(arrayOf("")) if (x7.toString() != "(true, true)") return "fail 7" val x9 = barNullable<String>(null) if (x9.toString() != "(true, true)") return "fail 9" val x10 = barNullable<Double?>(arrayOf("")) if (x10.toString() != "(false, false)") return "fail 11" val x12 = barNullable<Double?>(null) if (x12.toString() != "(true, true)") return "fail 12" return "OK" }
apache-2.0
30660d094c603852d9b7991914d43f98
29.725
72
0.588283
3.143223
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_search/model/CourseSearchResult.kt
1
660
package org.stepik.android.domain.course_search.model import org.stepik.android.model.Lesson import org.stepik.android.model.Progress import org.stepik.android.model.SearchResult import org.stepik.android.model.Section import org.stepik.android.model.user.User import org.stepik.android.model.Unit import ru.nobird.android.core.model.Identifiable data class CourseSearchResult( val searchResult: SearchResult, val lesson: Lesson? = null, val progress: Progress? = null, val unit: Unit? = null, val section: Section? = null, val commentOwner: User? = null ) : Identifiable<Long> { override val id: Long = searchResult.id }
apache-2.0
d7b95a4083d378bf723820c1c734ed15
30.428571
53
0.75303
3.75
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/services/version/VersionServiceImpl.kt
1
5992
/*- * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.services.version import com.cognifide.apm.api.scripts.Script import com.cognifide.apm.api.services.ScriptFinder import com.cognifide.apm.core.Property import com.cognifide.apm.core.grammar.ReferenceFinder import com.cognifide.apm.core.grammar.ScriptExecutionException import com.cognifide.apm.core.scripts.MutableScriptWrapper import com.cognifide.apm.core.scripts.ScriptNode import com.day.cq.commons.jcr.JcrUtil import com.day.crx.JcrConstants import org.apache.commons.codec.digest.DigestUtils import org.apache.jackrabbit.commons.JcrUtils import org.apache.sling.api.resource.ResourceResolver import org.osgi.service.component.annotations.Component import org.osgi.service.component.annotations.Reference import org.slf4j.LoggerFactory import javax.jcr.Node import javax.jcr.RepositoryException import javax.jcr.Session @Component( immediate = true, service = [VersionService::class], property = [ Property.DESCRIPTION + "APM Version Service", Property.VENDOR ]) class VersionServiceImpl : VersionService { private val logger = LoggerFactory.getLogger(VersionServiceImpl::class.java) @Reference @Transient private lateinit var scriptFinder: ScriptFinder override fun getScriptVersion(resolver: ResourceResolver, script: Script): ScriptVersion { val scriptVersionPath = getScriptVersionPath(script) return resolver.getResource(scriptVersionPath)?.adaptTo(ScriptVersionModel::class.java) ?: ScriptVersionModel(script.path) } override fun getVersionPath(script: Script): String { return "$versionsRoot/${script.normalizedPath()}/${script.checksum}/$scriptNodeName" } override fun countChecksum(root: Iterable<Script>): String { val checksums = root .asSequence() .filter { it.isValid } .map { it.data } .map { DigestUtils.md5Hex(it) } .reduce { previous, current -> previous + current } return DigestUtils.md5Hex(checksums) } override fun updateVersionIfNeeded(resolver: ResourceResolver, vararg scripts: Script) { val referenceFinder = ReferenceFinder(scriptFinder, resolver) scripts.forEach { script -> try { val subtree = referenceFinder.findReferences(script) val checksum = countChecksum(subtree) val scriptVersion = getScriptVersion(resolver, script) if (checksum != script.checksum) { MutableScriptWrapper(script).apply { setChecksum(checksum) } } if (checksum != scriptVersion.lastChecksum) { createVersion(resolver, script) } } catch (e: ScriptExecutionException) { logger.error(e.message) } } } private fun createVersion(resolver: ResourceResolver, script: Script) { try { val session = resolver.adaptTo(Session::class.java)!! val scriptNode = createScriptNode(script, session) val versionNode = createVersionNode(scriptNode, script, session) copyScriptContent(versionNode, script, session) session.save() resolver.commit() } catch (e: Exception) { logger.error("Issues with saving to repository while logging script execution", e) } } @Throws(RepositoryException::class) private fun createScriptNode(script: Script, session: Session): Node { val path = getScriptVersionPath(script) val scriptHistory = JcrUtils.getOrCreateByPath(path, "sling:OrderedFolder", JcrConstants.NT_UNSTRUCTURED, session, true) scriptHistory.setProperty("scriptPath", script.path) scriptHistory.setProperty("lastChecksum", script.checksum) return scriptHistory } private fun getScriptVersionPath(script: Script) = "$versionsRoot/${script.normalizedPath()}" @Throws(RepositoryException::class) private fun createVersionNode(parent: Node, script: Script, session: Session): Node { val path = parent.path + "/" + script.checksum return JcrUtils.getOrCreateByPath(path, "sling:OrderedFolder", "sling:OrderedFolder", session, true) } @Throws(RepositoryException::class) private fun copyScriptContent(parent: Node, script: Script, session: Session): Node { if (!parent.hasNode(scriptNodeName)) { val source = session.getNode(script.path) val file = JcrUtil.copy(source, parent, scriptNodeName) file.addMixin(ScriptNode.APM_SCRIPT) return file } return parent.getNode(scriptNodeName) } private fun Script.normalizedPath(): String { return path.replace("/", "_").substring(1) } companion object { const val versionsRoot = "/var/apm/versions" const val scriptNodeName = "script" } }
apache-2.0
692515b2406214d6a7d629a19f822f1f
39.054795
128
0.645694
4.714398
false
false
false
false
suchaHassle/kotNES
src/PPU.kt
1
11739
package kotNES import Renderers.IRenderManager import kotNES.ui.CopyImageToClipboard import palette import java.awt.Component import java.awt.Graphics2D import java.awt.image.BufferedImage import java.awt.peer.ComponentPeer import java.util.* import java.awt.image.DataBufferInt class PPU(private var emulator: Emulator) { val gameWidth = 256 val gameHeight = 240 var ppuMemory = PpuMemory(emulator) var ppuFlags = ppuMemory.ppuFlags var bitMap = IntArray(gameWidth * gameHeight) var frame: Long = 0 var spritePositions = IntArray(8) var spritePatterns = IntArray(8) var spritePriorities = IntArray(8) var spriteIndexes = IntArray(8) var tileShiftRegister: Long = 0 var cycle = 340 var scanline = 240 var renderingEnabled: Boolean = false var currentRenderer: IRenderManager? = null lateinit var renderers: List<IRenderManager> var screenBuffer = BufferedImage(gameWidth, gameHeight, BufferedImage.TYPE_INT_RGB) private var attributeTableByte = 0 private var highTileByte = 0 private var lowTileByte = 0 private var nametableByte = 0 private var spriteCount = 0 fun reset() { cycle = 340 scanline = 240 frame = 0 ppuFlags.PPUCTRL = 0 ppuFlags.PPUMASK = 0 ppuFlags.oamAddress = 0 } fun step() { tick() renderingEnabled = ppuFlags.showBackground || ppuFlags.showSprites // Scanline val preLine = scanline == 261 val visibleLine = scanline < 240 val postLine = scanline == 0 val renderLine = preLine || visibleLine // Cycle val prefetchCycle = cycle in 321..336 val visibleCycle = cycle in 1..256 val fetchCycle = prefetchCycle || visibleCycle if (renderingEnabled) { // Background Logic if (visibleLine && visibleCycle) renderPixel() if (renderLine && fetchCycle) { tileShiftRegister = tileShiftRegister shl 4 when (cycle % 8) { 1 -> fetchNametableByte() 3 -> fetchAttributeTableByte() 5 -> fetchTileByte(false) 7 -> fetchTileByte(true) 0 -> storeTileData() } } if (preLine && cycle in 280..304) copyY() if (renderLine) { if (fetchCycle && cycle % 8 == 0) incrementX() if (cycle == 256) incrementY() if (cycle == 257) copyX() } // Sprite Logic if (cycle == 257) { if (renderLine) evaluateSprites() else spriteCount = 0 } } if (scanline == 241 && cycle == 1) { ppuFlags.vBlankStarted = true drawFrame() if (ppuFlags.nmiOutput) emulator.cpu.triggerInterrupt(CPU.Interrupts.NMI) } if (preLine && cycle == 1) { ppuFlags.vBlankStarted = false ppuFlags.spriteZeroHit = false ppuFlags.spriteOverflow = false } } private fun drawFrame() { if (currentRenderer != null) { var graphics: Graphics2D = currentRenderer!!.graphics val dbb = screenBuffer.raster.dataBuffer as DataBufferInt var data = dbb.getData(0) System.arraycopy(bitMap, 0, data, 0, data.size) graphics.drawImage(screenBuffer, 0, 0, emulator.display.width, emulator.display.height, null) emulator.evenOdd = !emulator.evenOdd } } private fun tick() { renderingEnabled = ppuFlags.showBackground || ppuFlags.showSprites if (renderingEnabled) { if (scanline == 261 && ppuFlags.F && cycle == 339) { cycle = -1 scanline = 0 frame++ ppuFlags.F = !ppuFlags.F return } } cycle++ if (cycle > 340) { cycle = -1 scanline++ if (scanline > 261) { scanline = 0 frame++ ppuFlags.F = !ppuFlags.F } } } private fun fetchNametableByte() { nametableByte = ppuMemory[0x2000 or (ppuFlags.V and 0x0FFF)] } private fun fetchAttributeTableByte() { val v = ppuFlags.V val address = 0x23C0 or (v and 0x0C00) or ((v shr 4) and 0x38) or ((v shr 2) and 0x07) val shift = ((v shr 4) and 4) or (v and 2) attributeTableByte = ((ppuMemory[address] shr shift) and 3) shl 2 } private fun fetchSprite(i: Int, row: Int): Int { var row = row var tile = ppuMemory.oam[i*4 + 1] var attributes = ppuMemory.oam[i*4 + 2] val address: Int val table: Int var data = 0 if (ppuFlags.spriteSize) { if (attributes and 0x80 == 0x80) row = 15 - row table = (tile and 1) * 0x1000 tile = tile and 0xFE if (row > 7) { tile++ row -= 8 } } else { if (attributes and 0x80 == 0x80) row = 7 - row table = ppuFlags.spriteTableAddress } address = ((table and 0xFFFF) + (16 * (tile and 0xFFFF)) + (row and 0xFFFF)) and 0xFFFF val a = (attributes and 3) shl 2 lowTileByte = ppuMemory[address] and 0xFF highTileByte = ppuMemory[address + 8] and 0xFF for (i in 0..7) { val p1: Int val p2: Int if (attributes and 0x40 == 0x40) { p1 = (lowTileByte and 1) shl 0 and 0xFF p2 = (highTileByte and 1) shl 1 and 0xFF lowTileByte = lowTileByte shr 1 highTileByte = highTileByte shr 1 } else { p1 = (lowTileByte and 0x80) ushr 7 p2 = (highTileByte and 0x80) ushr 6 lowTileByte = (lowTileByte shl 1) and 0xFF highTileByte = (highTileByte shl 1) and 0xFF } data = (data shl 4) or (a or p1 or p2) } return data } private fun fetchTileByte(hi: Boolean) { val fineY = (ppuFlags.V shr 12) and 7 val address = ((ppuFlags.patternTableAddress) + (16 * nametableByte) + fineY) and 0xFFFF if (hi) highTileByte = ppuMemory[address + 8] and 0xFF else lowTileByte = ppuMemory[address] and 0xFF } private fun storeTileData() { var data: Long = 0 for (i in 0..7) { val p1 = (lowTileByte and 0x80) shr 7 val p2 = (highTileByte and 0x80) shr 6 lowTileByte = (lowTileByte shl 1) highTileByte = (highTileByte shl 1) data = (data shl 4) or (attributeTableByte or p1 or p2).toLong() } tileShiftRegister = tileShiftRegister or data } private fun evaluateSprites() { var h: Int = if (ppuFlags.spriteSize) 16 else 8 var count = 0 for (i in 0..63) { val y = ppuMemory.oam[i*4] and 0xFF val a = ppuMemory.oam[i*4 + 2] and 0xFF val x = ppuMemory.oam[i*4 + 3] and 0xFF val row = scanline - y if (row in 0..(h-1)) { if (count < 8) { spritePatterns[count] = fetchSprite(i, row) spritePositions[count] = x spritePriorities[count] = (a shr 5) and 1 spriteIndexes[count] = i } count++ } } if (count > 8) { count = 8 ppuFlags.spriteOverflow = true } spriteCount = count } private fun renderPixel() { val x = cycle - 1 val y = scanline val background = if (x < 8 && !ppuFlags.showLeftBackground) 0 else backgroundPixel() var (i, spritePixel) = spritePixel() if (x < 8 && !ppuFlags.showLeftSprites) spritePixel = 0 val b = background % 4 != 0 val s = spritePixel % 4 != 0 val color: Int when { !b && !s -> color = 0 !b && s -> color = spritePixel or 0x10 b && !s -> color = background else -> { if (spriteIndexes[i] == 0 && x < 255) ppuFlags.spriteZeroHit = true color = if (spritePriorities[i] == 0) (spritePixel or 0x10) else background } } val c = palette(ppuMemory.readPaletteRam(color) % 64) bitMap[y*256 + x] = c } private fun spritePixel(): Pair<Int, Int> { if (!ppuFlags.showSprites) return Pair(0,0) else { for (i in 0..(spriteCount - 1)) { var offset = (cycle - 1) - spritePositions[i] if (offset in 0..7) { offset = 7 - offset val color = (spritePatterns[i] ushr ((offset * 4) and 0xFF)) and 0x0F if (color % 4 != 0) return Pair(i, color) } } return Pair(0,0) } } private fun backgroundPixel(): Int = when { !ppuFlags.showBackground -> 0 else -> (((tileShiftRegister ushr 32) ushr ((7 - ppuFlags.X) * 4)) and 0x0F).toInt() and 0xFF } private fun copyX() { ppuFlags.V = (ppuFlags.V and 0xFBE0) or (ppuFlags.T and 0x041F) } private fun copyY() { ppuFlags.V = (ppuFlags.V and 0x841F) or (ppuFlags.T and 0x7BE0) } private fun incrementX() { ppuFlags.V = if (ppuFlags.V and 0x001F == 31) ((ppuFlags.V and 0xFFE0) xor 0x0400) else (ppuFlags.V + 1) } private fun incrementY() { if (ppuFlags.V and 0x7000 != 0x7000) ppuFlags.V += 0x1000 else { ppuFlags.V = ppuFlags.V and 0x8FFF var y = (ppuFlags.V and 0x03E0) shr 5 when (y) { 29 -> { y = 0 ppuFlags.V = ppuFlags.V xor 0x0800 } 31 -> y = 0 else -> y++ } ppuFlags.V = (ppuFlags.V and 0xFC1F) or (y shl 5) } } fun initRenderer() { renderers = Collections.unmodifiableList(object : ArrayList<IRenderManager>() { init { for (rendererClass in IRenderManager.RENDERERS) { val renderer: IRenderManager try { System.err.println(rendererClass) // Look up peer reflectively since Container#getPeer is removed in // Java 9; this is still "illegal access" as far as the JRE cares, // but it should work till Java 10 at least. val peer = Component::class.java!!.getDeclaredField("peer") peer.isAccessible = true renderer = rendererClass.getDeclaredConstructor(ComponentPeer::class.java).newInstance(peer.get(emulator.display)) } catch (ignored: ReflectiveOperationException) { // #error failure means we try the next renderer continue } if (renderer.graphics != null) { add(renderer) if (currentRenderer == null) { println("Using " + renderer) currentRenderer = renderer } } else { System.err.println(renderer.toString() + " failed to produce a Graphics2D") } } } }) } }
mit
df30363623ff81148d213ebdfec305f6
31.611111
138
0.515972
4.053522
false
false
false
false
saletrak/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/WykopImageView.kt
1
1324
package io.github.feelfreelinux.wykopmobilny.ui.widgets import android.content.Context import android.util.AttributeSet import android.widget.ImageView import io.github.feelfreelinux.wykopmobilny.models.dataclass.Embed import io.github.feelfreelinux.wykopmobilny.ui.modules.photoview.launchPhotoView import io.github.feelfreelinux.wykopmobilny.utils.isVisible import io.github.feelfreelinux.wykopmobilny.utils.loadImage import io.github.feelfreelinux.wykopmobilny.utils.openBrowser class WykopImageView : ImageView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) init { isVisible = false } fun setEmbed(embed : Embed?) { if (embed == null) isVisible = false embed?.apply { isVisible = true loadImage(preview) // @TODO We should put +18 check here and handle video embed type setOnClickListener { when (type) { "image" -> context.launchPhotoView(url) "video" -> context.openBrowser(url) // @TODO replace with some nice implementation } } } } }
mit
e386d53b5a596bdfa873ea92a747e598
34.810811
111
0.68429
4.779783
false
false
false
false
ccampo133/daily-programmer
220-easy/src/Mangler.kt
1
1005
fun main(args: Array<String>) { println(mangle(readLine() ?: "")) } fun mangle(input: String): String { if (input.isBlank()) return input val parts = ((input split "\\W+".toRegex()) dropLastWhile { it.isEmpty() }).toTypedArray() val sortedParts = parts map { it.toLowerCase().toCharArray() } map { it.sort(); it } map { it joinToString "" } val capitals = input map { it.isUpperCase() } fun replace(i: Int, prevStart: Int, mangled: String): String { if (i == parts.size()) return mangled val word = parts[i] val sorted = sortedParts[i] val sub = input.substring(prevStart) val offset = input.length() - sub.length() val start = offset + sub.indexOf(word) val end = start + sorted.length() val replacement = if (capitals[start]) sorted.capitalize() else sorted val replaced = mangled.replaceRange(start, end, replacement) return replace(i + 1, start, replaced) } return replace(0, 0, input) }
mit
9e86072fe52cb0ad6cadedfab8caed51
42.695652
115
0.621891
3.880309
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/account/KoinModule.kt
2
426
package com.fsck.k9.account import org.koin.dsl.module val accountModule = module { factory { AccountRemover( localStoreProvider = get(), messagingController = get(), backendManager = get(), localKeyStoreManager = get(), preferences = get() ) } factory { BackgroundAccountRemover(get()) } factory { AccountCreator(get(), get()) } }
apache-2.0
ac81e1c1e997da9fb249770aff8643c7
24.058824
47
0.577465
4.580645
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/ComponentDecorations.kt
1
4712
@file:Suppress("RUNTIME_ANNOTATION_NOT_SUPPORTED") package org.hexworks.zircon.api import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer.Alignment import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer.RenderingMode import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer.RenderingMode.NON_INTERACTIVE import org.hexworks.zircon.api.graphics.BoxType import org.hexworks.zircon.api.modifier.Border import org.hexworks.zircon.internal.component.renderer.decoration.* import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic /** * This object contains functions for creating component decorations. */ object ComponentDecorations { /** * Can be used to draw a border around a [Component]. A border is * [RenderingMode.NON_INTERACTIVE] by default. */ @JvmOverloads @JvmStatic fun border( border: Border = Border.newBuilder().build(), renderingMode: RenderingMode = NON_INTERACTIVE ): ComponentDecorationRenderer = BorderDecorationRenderer( border = border, renderingMode = renderingMode ) /** * Can be used to draw a box (using box drawing characters) around a [Component]. * **Note that** the [title] will only be displayed for a [Component] if it is wrapped * with a box. This decoration uses [RenderingMode.NON_INTERACTIVE] by default. */ @JvmOverloads @JvmStatic fun box( boxType: BoxType = BoxType.SINGLE, title: String = "", renderingMode: RenderingMode = NON_INTERACTIVE, titleAlignment: Alignment = Alignment.TOP_LEFT ): ComponentDecorationRenderer = BoxDecorationRenderer( boxType = boxType, titleProperty = title.toProperty(), renderingMode = renderingMode, titleAlignment = titleAlignment ) /** * Wraps a [Component] on the left and the right sides with the given * [leftSideCharacter] and [rightSideCharacter]. This decoration will use * [RenderingMode.INTERACTIVE] by default. */ @JvmOverloads @JvmStatic fun side( leftSideCharacter: Char = '[', rightSideCharacter: Char = ']', renderingMode: RenderingMode = RenderingMode.INTERACTIVE ): ComponentDecorationRenderer = SideDecorationRenderer( leftSideCharacter = leftSideCharacter, rightSideCharacter = rightSideCharacter, renderingMode = renderingMode ) /** * Can be used to draw a shadow around a [Component]. The shadow is drawn * around the bottom and the right sides. */ @JvmStatic fun shadow(): ComponentDecorationRenderer = ShadowDecorationRenderer() /** * Can be used to add a half box decoration (half-height "border") to a [Component]. */ @JvmOverloads @JvmStatic fun halfBlock( renderingMode: RenderingMode = NON_INTERACTIVE ): ComponentDecorationRenderer = HalfBlockDecorationRenderer(renderingMode) /** * Can be used to add margin to a [Component]. Padding is measured in tiles. * @param value the margin to add to all sides (top, right, bottom and left) */ @Beta @JvmStatic fun margin( value: Int ): ComponentDecorationRenderer = MarginDecorationRenderer( top = value, right = value, bottom = value, left = value ) /** * Can be used to add margin to a [Component]. Padding is measured in tiles. */ @Beta @JvmStatic fun margin( top: Int, right: Int, bottom: Int, left: Int ): ComponentDecorationRenderer = MarginDecorationRenderer( top = top, right = right, bottom = bottom, left = left ) /** * Can be used to add margin to a [Component]. Padding is measured in tiles. * @param x horizontal margin (left and right) * @param y vertical margin (top and bottom) */ @Beta @JvmStatic fun margin( y: Int, x: Int ): ComponentDecorationRenderer = MarginDecorationRenderer( top = y, right = x, bottom = y, left = x ) /** * Can be used to explicitly state that a [Component] has no decorations. This is useful * when a [Component] has decorations by default. */ @Beta @JvmStatic fun noDecoration(): ComponentDecorationRenderer = MarginDecorationRenderer( top = 0, right = 0, bottom = 0, left = 0 ) }
apache-2.0
4928ca90e54b4b8cb73766e96989a8df
30.205298
107
0.665747
4.726179
false
false
false
false
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/SeriesListEntity.kt
1
840
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.* @Entity( tableName = "series_list", indices = [Index(value = ["series_list_character_id"], name = "series_list_character_index")], foreignKeys = [ForeignKey( entity = CharacterEntity::class, parentColumns = ["id"], childColumns = ["series_list_character_id"] )] ) data class SeriesListEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "series_list_id") var id: Long = 0L, @ColumnInfo(name = "series_list_available") var available: Int = 0, @ColumnInfo(name = "series_list_returned") var returned: Int = 0, @ColumnInfo(name = "series_list_collection_uri") var collectionURI: String = "", @ColumnInfo(name = "series_list_character_id") var characterId: Long = 0L )
mit
8bf2ae85a10d025a7597a66d84c3d552
27
98
0.653571
3.783784
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/utils/DownloadManagerWrapper.kt
1
2677
package org.wordpress.android.ui.utils import android.app.DownloadManager import android.app.DownloadManager.Query import android.app.DownloadManager.Request import android.content.ActivityNotFoundException import android.content.ContentResolver import android.content.Context import android.content.Intent import android.database.Cursor import android.net.Uri import android.webkit.MimeTypeMap import android.webkit.URLUtil import androidx.core.content.FileProvider import org.wordpress.android.BuildConfig import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import java.io.File import javax.inject.Inject import javax.inject.Singleton @Singleton class DownloadManagerWrapper @Inject constructor(private val context: Context) { fun enqueue(request: Request): Long = downloadManager().enqueue(request) fun buildRequest(fileUrl: String) = Request(Uri.parse(fileUrl)) fun query(query: Query): Cursor = downloadManager().query(query) fun buildQuery() = Query() fun guessUrl(fileUrl: String): String = URLUtil.guessUrl(fileUrl) fun getMimeType(url: String): String? { var type: String? = null val extension = MimeTypeMap.getFileExtensionFromUrl(url) if (extension != null) { val mime = MimeTypeMap.getSingleton() type = mime.getMimeTypeFromExtension(extension) } return type } private fun toPublicUri(fileUrl: String): Uri { val fileUri = Uri.parse(fileUrl) return if (ContentResolver.SCHEME_FILE == fileUri.scheme) { fileUri.path?.let { path -> val file = File(path) FileProvider.getUriForFile( context, "${BuildConfig.APPLICATION_ID}.provider", file ) } ?: fileUri } else { fileUri } } fun openDownloadedAttachment( context: Context, fileUrl: String, attachmentMimeType: String ) { val attachmentUri = toPublicUri(fileUrl) val openAttachmentIntent = Intent(Intent.ACTION_VIEW) openAttachmentIntent.setDataAndType(attachmentUri, attachmentMimeType) openAttachmentIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK try { context.startActivity(openAttachmentIntent) } catch (e: ActivityNotFoundException) { AppLog.e(T.READER, "No browser found on the device: ${e.message}") } } private fun downloadManager() = (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager) }
gpl-2.0
1300b6fc9a81262c93a425e6fe0c123d
32.4625
107
0.678745
4.746454
false
false
false
false
DanielGrech/anko
preview/xml-converter/src/org/jetbrains/kotlin/android/xmlconverter/Util.kt
3
2021
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.xmlconverter import com.google.gson.Gson import org.jetbrains.kotlin.android.attrs.* import com.google.gson.reflect.TypeToken import java.util import java.util.HashMap private val INTENT = " " private val attrs = Gson().fromJson(readResource("attrs.json"), javaClass<Attrs>()) private val viewHierarchy = Gson().fromJson<Map<String, List<String>>>(readResource("views.json"), (object : TypeToken<Map<String, List<String>>>() {}).getType()) public data class KeyValuePair(val key: String, val value: String) { override fun toString() = if (value.isNotEmpty()) "$key = $value" else key } fun String.times(value: String) = KeyValuePair(this, value) public fun <T: Any, R: Any> List<T>.findFirst(transformer: (T) -> R?): R? { for (item in this) { val r = transformer(item) if (r != null) return r } return null } public fun String.indent(width: Int): String { if (isEmpty()) return this val intent = INTENT.repeat(width) return split('\n').map { intent + it }.joinToString("\n") } private fun String.swapCamelCase(): String { val ch = withIndex().firstOrNull { Character.isUpperCase(it.value) } return if (ch == null) this else substring(ch.index).toLowerCase() + substring(0, ch.index).firstCapital() } private fun String.firstCapital(): String = if (isEmpty()) this else Character.toUpperCase(this[0]) + substring(1)
apache-2.0
fe90e69a7d08e6663dff145743f623f7
34.473684
114
0.705591
3.770522
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/dex/AbstractLocalVariableTableTest.kt
4
10145
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.test.dex import com.jetbrains.jdi.MockLocalVariable import com.sun.jdi.LocalVariable import com.sun.jdi.Location import com.sun.jdi.Method import com.sun.jdi.StackFrame import junit.framework.TestCase import org.jetbrains.kotlin.idea.debugger.core.sortedVariablesWithLocation import org.jetbrains.kotlin.idea.debugger.core.stackFrame.computeKotlinStackFrameInfos import org.jetbrains.kotlin.idea.debugger.test.mock.MockMethodInfo import org.jetbrains.kotlin.idea.debugger.test.mock.MockStackFrame import org.jetbrains.kotlin.idea.debugger.test.mock.MockVirtualMachine abstract class AbstractLocalVariableTableTest : TestCase() { private fun LocalVariable.asString(): String = "${name()}: ${typeName()}" private fun printLocalVariableTable(locals: List<LocalVariable>): String = locals.joinToString("\n") { it.asString() } // LVT heuristic regression test. // // Test that local variable tables are the same on jvm and dex after sorting // variables and removing spilled variables. In this case the rest of the debugger // works with the same view of the local variable table, which makes this a // sufficient criterion for correctness. // // However, in many cases this is too strong, since variables may appear in // different order between individual lines. Such differences are not observable, // but would cause test failures. protected fun doLocalVariableTableComparisonTest( jvm: MockMethodInfo, dex: MockMethodInfo, ) { val jvmLocals = jvm.toMockMethod(MockVirtualMachine("JVM Mock")) .sortedVariablesWithLocation().map { it.variable } // Filter repeated appearances of the same variable in the dex LVT. val dexLocals = dex.toMockMethod(MockVirtualMachine("Dalvik")) .sortedVariablesWithLocation().map { it.variable as MockLocalVariable } val filteredDexLocals = dexLocals .zip(dexLocals.drop(1)) .mapNotNullTo(mutableListOf(dexLocals.first())) { (prev, next) -> next.takeIf { prev.name() != next.name() || prev.signature() != next.signature() || prev.startPc + prev.length != next.startPc } } assertEquals(printLocalVariableTable(jvmLocals), printLocalVariableTable(filteredDexLocals)) } // Compare local variable tables, while ignoring differences in the order of // variables that start on the same code index on the JVM. The debugger cannot // rely on the order of these variables anyway and on dex the variables will start // on different lines. private fun compareLocals(jvm: List<MockLocalVariable>, dex: List<MockLocalVariable>) { val blocks = jvm.groupBy { it.startPc }.entries .sortedBy { it.key }.map { it.value.map { variable -> variable.asString() } } val iter = dex.iterator() for (block in blocks) { val target = block.toMutableList() while (target.isNotEmpty()) { assert(iter.hasNext()) { "Missing variables in dex LVT: ${block.joinToString()}" } val nextVariable = iter.next().asString() assert(nextVariable in target) { "Unexpected variable in dex LVT: $nextVariable, expected: ${block.joinToString()}" } target.remove(nextVariable) } } assert(!iter.hasNext()) { "Extra variable in dex LVT: ${iter.next().name()}" } } private data class BreakpointLocation(val source: String, val line: Int) { constructor(location: Location) : this(location.sourceName() ?: "", location.lineNumber()) override fun toString(): String = "$source:$line" } // With a few exceptions, we can only set breakpoints on the first occurrence of a // given line in the debugger. This method returns a map from file, line pairs // to the Location that would be used for a breakpoint request on this line. private fun extractBreakpoints(allLineLocations: List<Location>): Map<BreakpointLocation, Location> = allLineLocations .groupBy(AbstractLocalVariableTableTest::BreakpointLocation) .filterKeys { it.source != "fake.kt" } .mapValues { (_, locations) -> locations.minByOrNull { it.codeIndex() }!! } // Call [block] with each matching pair of jvm and dex breakpoint locations. // With the same caveats as [extractBreakpoints] above. private fun forEachMatchingBreakpoint(jvm: Method, dex: Method, block: (StackFrame, StackFrame) -> Unit) { val jvmBreakpoints = extractBreakpoints(jvm.allLineLocations()) val dexBreakpoints = extractBreakpoints(dex.allLineLocations()) for ((breakpoint, jvmLocation) in jvmBreakpoints.entries) { assert(breakpoint in dexBreakpoints.keys) { "Breakpoint $breakpoint@${jvmLocation.lineNumber("Java")} not found in dex" } val dexLocation = dexBreakpoints.getValue(breakpoint) block(MockStackFrame(jvmLocation), MockStackFrame(dexLocation)) } dexBreakpoints.keys.forEach { breakpoint -> assert(breakpoint in jvmBreakpoints.keys) { "Breakpoint $breakpoint not found in jvm" } } } // LVT heuristic regression tests on breakpoints. // // Test that the visible local variables in dex and jvm code are the same on // every possible breakpoint. This is sufficient for the debugger to behave // the same on dex as on the jvm. // // This test can fail in the following cases: // // - Due to spill code and block reordering we sometimes can't distinguish // between register spilling and newly introduced variables with the same // name. In this case our heuristics simply fail. // - Due to block reordering we can select different breakpoints on dex than // on the jvm, since the chosen breakpoints depend on code indices. // // The second failure case is an artifact of how we identify breakpoints. // In the first case we may still be able to compute correct inline call stacks // so long as no scope introduction variable is reordered with respect to other // scope introduction variables and no inlined variable is moved outside // its original scope. // // --- // // Apart from the above, this test can also fail if we are missing line numbers // on dex or have superfluous lines on dex. Either case would be a bug in D8, not // in the Kotlin compiler or debugger. protected fun doLocalVariableTableBreakpointComparisonTest(jvm: MockMethodInfo, dex: MockMethodInfo) { val jvmMethod = jvm.toMockMethod(MockVirtualMachine("JVM Mock")) val dexMethod = dex.toMockMethod(MockVirtualMachine("Dalvik")) val jvmVariables = jvmMethod.sortedVariablesWithLocation().map { it.variable as MockLocalVariable } val dexVariables = dexMethod.sortedVariablesWithLocation().map { it.variable as MockLocalVariable } forEachMatchingBreakpoint(jvmMethod, dexMethod) { jvmStackFrame, dexStackFrame -> val jvmLocals = jvmVariables.filter { it.isVisible(jvmStackFrame) } val dexLocals = dexVariables.filter { it.isVisible(dexStackFrame) } try { compareLocals(jvmLocals, dexLocals) } catch (e: AssertionError) { val dexLocalVariables = printLocalVariableTable(dexLocals) val jvmLocalVariables = printLocalVariableTable(jvmLocals) assertEquals( e.message, "${jvmStackFrame.location()}\n$jvmLocalVariables", "${dexStackFrame.location()}\n$dexLocalVariables" ) } } } // Print the Kotlin stack frame info for the given stack frame private fun printStackFrame(stackFrame: StackFrame): String = stackFrame.computeKotlinStackFrameInfos().joinToString("\n") { info -> val location = info.callLocation?.let { "${it.sourceName()}:${it.lineNumber()}" } ?: "<no location>" val header = "${info.displayName ?: stackFrame.location().method().name()} at $location depth ${info.depth}:\n" val variables = info.visibleVariables.sortedBy { it.asString() }.joinToString("\n") { variable -> " ${variable.name()}: ${variable.signature()}" } header + variables } // Inline call stack regression test on breakpoints. // // Test that the inline call stacks in dex and jvm code are the same up to the // order of variables in each frame on every possible breakpoint. // // The same caveats as for `doLocalVariableTableBreakpointComparisonTest` apply. protected fun doInlineCallStackComparisonTest(jvm: MockMethodInfo, dex: MockMethodInfo) { val jvmMethod = jvm.toMockMethod(MockVirtualMachine("JVM Mock")) val dexMethod = dex.toMockMethod(MockVirtualMachine("Dalvik")) forEachMatchingBreakpoint(jvmMethod, dexMethod) { jvmStackFrame, dexStackFrame -> assertEquals(printStackFrame(jvmStackFrame), printStackFrame(dexStackFrame)) } } // Manual inline call stack test for a fixed location. protected fun doKotlinInlineStackTest( codeIndex: Int, methodInfo: MockMethodInfo, expectation: String, ) { val method = methodInfo.toMockMethod(MockVirtualMachine("JVM Mock")) val location = method.allLineLocations().first { it.codeIndex().toInt() == codeIndex } assertEquals(expectation, printStackFrame(MockStackFrame(location))) } }
apache-2.0
94c66dd49f9e3e816a938938e0929f36
47.309524
123
0.655692
4.886802
false
true
false
false
GunoH/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/report/FileReportGenerator.kt
2
3264
package com.intellij.cce.report import com.intellij.cce.workspace.SessionSerializer import com.intellij.cce.workspace.info.FileEvaluationInfo import com.intellij.cce.workspace.storages.FeaturesStorage import kotlinx.html.* import kotlinx.html.stream.createHTML import org.apache.commons.codec.binary.Base64OutputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.FileWriter import java.io.OutputStreamWriter import java.nio.file.Path import java.util.zip.GZIPOutputStream abstract class FileReportGenerator( private val featuresStorages: List<FeaturesStorage>, private val dirs: GeneratorDirectories, private val filterName: String, private val comparisonFilterName: String ) : ReportGenerator { override val type: String = "html" val reportReferences: MutableMap<String, ReferenceInfo> = mutableMapOf() abstract fun getHtml(fileEvaluations: List<FileEvaluationInfo>, fileName: String, resourcePath: String, text: String): String override fun generateFileReport(sessions: List<FileEvaluationInfo>) { val fileInfo = sessions.first() val fileName = File(fileInfo.sessionsInfo.filePath).name val (resourcePath, reportPath) = dirs.getPaths(fileName) val sessionsJson = sessionSerializer.serialize(sessions.map { it.sessionsInfo.sessions }.flatten()) val resourceFile = File(resourcePath.toString()) resourceFile.writeText("var sessions = {};\nconst features={};\nsessions = ${parseJsonInJs(sessionsJson)};") for (featuresStorage in featuresStorages) { for (session in featuresStorage.getSessions(fileInfo.sessionsInfo.filePath)) { val featuresJson = featuresStorage.getFeatures(session, fileInfo.sessionsInfo.filePath) resourceFile.appendText("features[\"${session}\"] = `${zipJson(featuresJson)}`;\n") } } val reportTitle = "Code Completion Report for file $fileName ($filterName and $comparisonFilterName filter)" createHTML().html { createHead(reportTitle, resourcePath) body { h1 { +reportTitle } unsafe { +getHtml( sessions.sortedBy { it.evaluationType }, fileName, dirs.filesDir.relativize(resourcePath).toString(), fileInfo.sessionsInfo.text ) } } }.also { html -> FileWriter(reportPath.toString()).use { it.write(html) } } reportReferences[fileInfo.sessionsInfo.filePath] = ReferenceInfo(reportPath, sessions.map { it.metrics }.flatten()) } private fun HTML.createHead(reportTitle: String, resourcePath: Path) { head { title(reportTitle) script { src = "../res/pako.min.js" } script { src = dirs.filesDir.relativize(resourcePath).toString() } link { href = "../res/style.css" rel = "stylesheet" } } } private fun parseJsonInJs(json: String): String { return "JSON.parse(pako.ungzip(atob(`${zipJson(json)}`), { to: 'string' }))" } private fun zipJson(json: String): String { val resultStream = ByteArrayOutputStream() OutputStreamWriter(GZIPOutputStream(Base64OutputStream(resultStream))).use { it.write(json) } return resultStream.toString() } companion object { private val sessionSerializer = SessionSerializer() } }
apache-2.0
7e70b4ead1ca2dd5e4c7834f69929e90
36.953488
127
0.714767
4.334661
false
false
false
false
GunoH/intellij-community
platform/elevation/client/src/com/intellij/execution/process/mediator/client/MediatedProcessHandler.kt
10
1372
// 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.execution.process.mediator.client import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.KillableColoredProcessHandler import com.intellij.openapi.util.SystemInfo import com.intellij.util.io.BaseOutputReader class MediatedProcessHandler( private val process: MediatedProcess, commandLine: GeneralCommandLine ) : KillableColoredProcessHandler( process, commandLine ) { init { super.setShouldKillProcessSoftlyWithWinP(false) } override fun setShouldKillProcessSoftlyWithWinP(shouldKillProcessSoftlyWithWinP: Boolean) { /* not supported */ } // our ChannelInputStream unblocks read() on close() override fun readerOptions(): BaseOutputReader.Options = BaseOutputReader.Options.BLOCKING override fun canKillProcess(): Boolean = true override fun doDestroyProcess() { val gracefulTerminationAttemptedOnWindows = SystemInfo.isWindows && shouldKillProcessSoftly() && destroyProcessGracefully() if (!gracefulTerminationAttemptedOnWindows) { process.destroy(!shouldKillProcessSoftly(), destroyGroup = true) } } override fun killProcess() { process.destroy(true, destroyGroup = true) } }
apache-2.0
6f8698d51fe5ddf60c40136771789211
34.179487
158
0.787901
4.440129
false
false
false
false
robcish/wisisz-mi-hajs
app/src/main/java/rrozanski/wisiszmihajs/DebtPresenter.kt
1
1084
package rrozanski.wisiszmihajs import android.content.Context import android.content.Intent import android.database.Cursor import android.provider.ContactsContract /** * Created by robert on 29.08.2017. */ class DebtPresenter{ lateinit var viewModel: DebtViewModel fun switchEditMode() { viewModel.editMode = !viewModel.editMode } fun contactPicked(data: Intent, context: Context) { val cursor: Cursor? try { val uri = data.data cursor = context.contentResolver.query(uri!!, null, null, null, null) cursor!!.moveToFirst() val phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) viewModel.name.set(cursor.getString(nameIndex)) viewModel.number.set(cursor.getString(phoneIndex)) viewModel.contactFromBook = true cursor.close() } catch (e: Exception) { e.printStackTrace() } } }
apache-2.0
4666de8fe9bfdb186fe2cfcb9c66fd6a
29.138889
102
0.664207
4.57384
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/filter/SectionItems.kt
3
2790
package eu.kanade.tachiyomi.ui.browse.source.filter import eu.davidea.flexibleadapter.items.ISectionable import eu.kanade.tachiyomi.source.model.Filter class TriStateSectionItem(filter: Filter.TriState) : TriStateItem(filter), ISectionable<TriStateItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TriStateSectionItem if (head != other.head) return false return filter == other.filter } override fun hashCode(): Int { return filter.hashCode() + (head?.hashCode() ?: 0) } } class TextSectionItem(filter: Filter.Text) : TextItem(filter), ISectionable<TextItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TextSectionItem if (head != other.head) return false return filter == other.filter } override fun hashCode(): Int { return filter.hashCode() + (head?.hashCode() ?: 0) } } class CheckboxSectionItem(filter: Filter.CheckBox) : CheckboxItem(filter), ISectionable<CheckboxItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as CheckboxSectionItem if (head != other.head) return false return filter == other.filter } override fun hashCode(): Int { return filter.hashCode() + (head?.hashCode() ?: 0) } } class SelectSectionItem(filter: Filter.Select<*>) : SelectItem(filter), ISectionable<SelectItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SelectSectionItem if (head != other.head) return false return filter == other.filter } override fun hashCode(): Int { return filter.hashCode() + (head?.hashCode() ?: 0) } }
apache-2.0
4d256ccd80d9f57f3fbf9d38ef4c3d9f
26.9
121
0.64552
4.31221
false
false
false
false
C6H2Cl2/YukariLib
src/main/java/c6h2cl2/YukariLib/Util/ItemBuilder.kt
1
1060
@file:Suppress("UNUSED") package c6h2cl2.YukariLib.Util import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.Item import net.minecraftforge.event.RegistryEvent /** * @author C6H2Cl2 */ class ItemBuilder(val modId: String) { private val items = emptyList<Item>().toMutableList() fun create(name: String, textureName: String = name, creativeTabs: CreativeTabs? = null, stackSize: Int = 64, /*hasSubType : Boolean = false, maxMeta : Int = 0,*/isFull3D: Boolean = false, containerItem: Item? = null): Item { val item = ItemUtil.CreateItem(name, textureName, modId, creativeTabs, stackSize, isFull3D, containerItem) items.add(item) return item } fun getAllItems(): Array<Item>{ return items.toTypedArray() } fun registerItems(event: RegistryEvent.Register<Item>){ items.forEach { event.registry.register(it) } } fun registerModels() { items.forEach { setCustomModelResourceLocation(it) } } }
mpl-2.0
ed0ef7378332f654ac747d7fac34711f
28.472222
145
0.654717
3.94052
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/InjectorType.kt
1
8121
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.injector import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.demonwav.mcdev.platform.mixin.util.MixinMemberReference import com.demonwav.mcdev.platform.mixin.util.callbackInfoReturnableType import com.demonwav.mcdev.platform.mixin.util.callbackInfoType import com.demonwav.mcdev.util.Parameter import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.constantValue import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationOwner import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier.STATIC import com.intellij.psi.PsiNameHelper import com.intellij.psi.PsiQualifiedReference import com.intellij.psi.PsiType import org.objectweb.asm.Opcodes enum class InjectorType(private val annotation: String) { INJECT(MixinConstants.Annotations.INJECT) { override fun expectedMethodSignature(annotation: PsiAnnotation, targetMethod: PsiMethod): MethodSignature? { val returnType = targetMethod.returnType val result = ArrayList<ParameterGroup>() // Parameters from injected method (optional) result.add(ParameterGroup(collectTargetMethodParameters(targetMethod), required = false, default = true)) // Callback info (required) result.add(ParameterGroup(listOf(if (returnType == null || returnType == PsiType.VOID) { Parameter("ci", callbackInfoType(targetMethod.project)!!) } else { Parameter("cir", callbackInfoReturnableType(targetMethod.project, targetMethod, returnType)!!) }))) // Captured locals (only if local capture is enabled) // Right now we allow any parameters here since we can't easily // detect the local variables that can be captured if (((annotation.findDeclaredAttributeValue("locals") as? PsiQualifiedReference) ?.referenceName ?: "NO_CAPTURE") != "NO_CAPTURE") { result.add(ParameterGroup(null)) } return MethodSignature(result, PsiType.VOID) } }, REDIRECT(MixinConstants.Annotations.REDIRECT) { override fun expectedMethodSignature(annotation: PsiAnnotation, targetMethod: PsiMethod): MethodSignature? { val at = annotation.findDeclaredAttributeValue("at") as? PsiAnnotation ?: return null val target = at.findDeclaredAttributeValue("target") ?: return null if (!TargetReference.usesMemberReference(target)) { return null } // Since the target reference is required to be full qualified, // we don't actually have to resolve the target reference in the // target method. Everything needed to get the method parameters // is included in the reference. val reference = MixinMemberReference.parse(target.constantStringValue) ?: return null if (!reference.qualified || reference.descriptor == null) { // Invalid anyway and we need the qualified reference return null } val (owner, member) = reference.resolve(annotation.project, annotation.resolveScope) ?: return null val (parameters, returnType) = when (member) { is PsiMethod -> collectMethodParameters(owner, member) is PsiField -> collectFieldParameters(at, owner, member) else -> throw AssertionError("Cannot resolve member reference to: $member") } ?: return null val primaryGroup = ParameterGroup(parameters, required = true) // Optionally the target method parameters can be used val targetMethodGroup = ParameterGroup(collectTargetMethodParameters(targetMethod), required = false) return MethodSignature(listOf(primaryGroup, targetMethodGroup), returnType) } private fun getInstanceParameter(owner: PsiClass): Parameter { return Parameter(null, JavaPsiFacade.getElementFactory(owner.project).createType(owner)) } private fun collectMethodParameters(owner: PsiClass, method: PsiMethod): Pair<List<Parameter>, PsiType>? { val parameterList = method.parameterList val parameters = ArrayList<Parameter>(parameterList.parametersCount + 1) val returnType = if (method.isConstructor) { PsiType.VOID } else { if (!method.hasModifierProperty(STATIC)) { parameters.add(getInstanceParameter(owner)) } method.returnType!! } parameterList.parameters.mapTo(parameters, ::Parameter) return Pair(parameters, returnType) } private fun collectFieldParameters(at: PsiAnnotation, owner: PsiClass, field: PsiField): Pair<List<Parameter>, PsiType>? { // TODO: Report if opcode isn't set val opcode = at.findDeclaredAttributeValue("opcode")?.constantValue as? Int ?: return null // TODO: Report if magic value is used instead of a reference to a field (e.g. to ASM's Opcodes interface) // TODO: Report if opcode is invalid (not one of GETSTATIC, GETFIELD, PUTSTATIC, PUTFIELD) val parameters = ArrayList<Parameter>(2) // TODO: Report if GETSTATIC/PUTSTATIC is used for an instance field if (opcode == Opcodes.GETFIELD || opcode == Opcodes.PUTFIELD) { parameters.add(getInstanceParameter(owner)) } val returnType = when (opcode) { Opcodes.GETFIELD, Opcodes.GETSTATIC -> field.type Opcodes.PUTFIELD, Opcodes.PUTSTATIC -> { parameters.add(Parameter("value", field.type)) PsiType.VOID } else -> return null // Invalid opcode } return Pair(parameters, returnType) } }, MODIFY_ARG(MixinConstants.Annotations.MODIFY_ARG), MODIFY_CONSTANT(MixinConstants.Annotations.MODIFY_CONSTANT), MODIFY_VARIABLE(MixinConstants.Annotations.MODIFY_VARIABLE); val annotationName = "@${PsiNameHelper.getShortClassName(annotation)}" open fun expectedMethodSignature(annotation: PsiAnnotation, targetMethod: PsiMethod): MethodSignature? = null companion object { private val injectionPointAnnotations = InjectorType.values().associateBy { it.annotation } private fun collectTargetMethodParameters(targetMethod: PsiMethod): List<Parameter> { val parameters = targetMethod.parameterList.parameters val list = ArrayList<Parameter>(parameters.size) // Special handling for enums: When compiled, the Java compiler // prepends the name and the ordinal to the constructor if (targetMethod.isConstructor) { val containingClass = targetMethod.containingClass if (containingClass != null && containingClass.isEnum) { list.add(Parameter("enumName", PsiType.getJavaLangString(targetMethod.manager, targetMethod.resolveScope))) list.add(Parameter("ordinal", PsiType.INT)) } } // Add method parameters to list parameters.mapTo(list, ::Parameter) return list } fun findAnnotations(element: PsiAnnotationOwner): List<Pair<InjectorType, PsiAnnotation>> { return element.annotations.mapNotNull { val name = it.qualifiedName ?: return@mapNotNull null val type = injectionPointAnnotations[name] ?: return@mapNotNull null Pair(type, it) } } } }
mit
2dd80f2d84743627d2818882875e719f
42.897297
130
0.657801
5.388852
false
false
false
false
ayatk/biblio
app/src/debug/kotlin/com/ayatk/biblio/di/DebugHttpClientModule.kt
1
1951
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.di import android.app.Application import com.ayatk.biblio.BuildConfig import com.facebook.stetho.okhttp3.StethoInterceptor import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import java.io.File import javax.inject.Singleton @Module class DebugHttpClientModule { companion object { private const val CACHE_FILE_NAME = "biblio.cache" private const val MAX_CACHE_SIZE = (4 * 1024 * 1024).toLong() } private val addUserAgentInterceptor = { chain: Interceptor.Chain -> val builder = chain.request().newBuilder() builder.addHeader("User-Agent", "BiblioAndroidApp/" + BuildConfig.VERSION_NAME) chain.proceed(builder.build()) } @Singleton @Provides fun provideHttpClient(application: Application): OkHttpClient { val cacheDir = File(application.cacheDir, CACHE_FILE_NAME) val cache = Cache(cacheDir, MAX_CACHE_SIZE) val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.HEADERS return OkHttpClient .Builder() .addInterceptor(addUserAgentInterceptor) .cache(cache) .addNetworkInterceptor(StethoInterceptor()) .addInterceptor(httpLoggingInterceptor) .build() } }
apache-2.0
bdb689829703347b4d8a5fae3010b17b
30.983607
83
0.751922
4.345212
false
false
false
false
McMoonLakeDev/MoonLake
Core-v1.12-R1/src/main/kotlin/com/mcmoonlake/impl/anvil/AnvilWindowImpl_v1_12_R1.kt
1
2744
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.impl.anvil import net.minecraft.server.v1_12_R1.* import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer import org.bukkit.entity.Player import org.bukkit.inventory.Inventory import org.bukkit.plugin.Plugin open class AnvilWindowImpl_v1_12_R1( plugin: Plugin ) : AnvilWindowBase(plugin) { override fun open(player: Player) { super.open(player) val playerHandle = (player as CraftPlayer).handle val anvilTileContainer = AnvilWindowTileEntity(playerHandle.world) playerHandle.openTileEntity(anvilTileContainer) // add this anvil window id to list addWindowId(playerHandle.activeContainer.windowId) } override fun getInventory(): Inventory { val containerAnvil = handle as ContainerAnvil return containerAnvil.bukkitView.topInventory } private inner class AnvilWindowTileEntity(world: World) : BlockAnvil.TileEntityContainerAnvil(world, BlockPosition.ZERO) { override fun createContainer(playerInventory: PlayerInventory, opener: EntityHuman): Container? { val containerAnvil = object: ContainerAnvil(playerInventory, opener.world, BlockPosition.ZERO, opener) { override fun a(entityHuman: EntityHuman?): Boolean = true override fun a(value: String?) { if(inputHandler == null) { super.a(value) return } val event = callAnvilEvent(inputHandler, value) if(event != null && !event.isCancelled) super.a(event.input) } override fun b(entityHuman: EntityHuman?) { callAnvilEvent(closeHandler) release() super.b(entityHuman) } } handle = containerAnvil callAnvilEvent(openHandler) return containerAnvil } } }
gpl-3.0
d50b0b7c65c9dd27047ff3fbe6ed87de
38.768116
126
0.645773
4.627319
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/AppTextView.kt
2
1521
package org.wikipedia.views import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.MotionEvent import androidx.core.content.withStyledAttributes import org.wikipedia.R import org.wikipedia.util.StringUtil // TODO: Document where it is desirable to use this class vs. a vanilla TextView open class AppTextView constructor(context: Context, attrs: AttributeSet? = null) : ConfigurableTextView(context, attrs) { init { if (attrs != null) { context.withStyledAttributes(attrs, R.styleable.AppTextView) { val htmlText = getString(R.styleable.AppTextView_html) if (htmlText != null) { text = StringUtil.fromHtml(htmlText) } } } } override fun dispatchTouchEvent(event: MotionEvent): Boolean { // Workaround for https://code.google.com/p/android/issues/detail?id=191430 // which only occurs on API 23 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) { if (event.actionMasked == MotionEvent.ACTION_DOWN && selectionStart != selectionEnd) { val text = text setText(null) setText(text) } } try { // Workaround for some obscure AOSP crashes when highlighting text. return super.dispatchTouchEvent(event) } catch (e: Exception) { // ignore } return true } }
apache-2.0
2159e8424c9b12c99d2bca5f107da262
34.372093
122
0.61407
4.723602
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/util/background/BootReceiver.kt
2
3828
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.util.background import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.guerinet.mymartlet.util.Prefs import com.guerinet.mymartlet.util.prefs.UsernamePref import com.guerinet.suitcase.prefs.BooleanPref import com.orhanobut.hawk.Hawk import java.util.Calendar /** * TODO Clean up * Automatically (re)starts the alarm if needed when the device is rebooted or the user opts in. * @author Shabbir Hussain * @author Julien Guerinet * @since 2.0.0 */ class BootReceiver : BroadcastReceiver() { var usernamePref: UsernamePref? = null /** * Seat checker [BooleanPref] */ var seatCheckerPref: BooleanPref? = null /** * Grade checker [BooleanPref] */ var gradeCheckerPref: BooleanPref? = null override fun onReceive(context: Context, intent: Intent) { setAlarm( context, usernamePref?.value, Hawk.get<String>(Prefs.PASSWORD), seatCheckerPref?.value ?: false, gradeCheckerPref?.value ?: false ) } companion object { /** * Starts the alarm receiver if needed * * @param context The app context */ fun setAlarm( context: Context, username: String?, password: String?, seatChecker: Boolean, gradeChecker: Boolean ) { //If we don't need it, don't start it if (username == null || password == null || !seatChecker && !gradeChecker) { //Make sure it's cancelled cancelAlarm(context) return } //Get the alarm manager val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager //Set the alarm to fire at approximately 8:30 AM according to the device's clock, // and to repeat once a day. val calendar = Calendar.getInstance() calendar.timeInMillis = System.currentTimeMillis() calendar.set(Calendar.HOUR_OF_DAY, 8) calendar.set(Calendar.MINUTE, 30) manager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, getPendingIntent(context) ) } /** * Cancels the alarm * * @param context The app context */ fun cancelAlarm(context: Context) { //Get the alarm manager val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager //Cancel the pending intent manager.cancel(getPendingIntent(context)) } /** * Gets the pending intent for the checker alarm * * @param context The app context * @return The pending intent */ private fun getPendingIntent(context: Context): PendingIntent { // TODO val intent = Intent() // Intent(context, CheckerService::class.java) return PendingIntent.getService(context, 0, intent, 0) } } }
apache-2.0
91c68c76c6cc9005ef934ab609690877
31.440678
96
0.628265
4.708487
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/base/activities/SimpleFragmentActivityBase.kt
1
2220
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.base.activities import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment abstract class SimpleFragmentActivityBase : ChildActivityBase() { val childFragment: Fragment get() = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG)!! protected abstract fun instantiateFragment(): Fragment public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { // Create the fragment only when the activity is created for the first time. // ie. not after orientation changes var childFragment: Fragment? = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) if (childFragment == null) { childFragment = instantiateFragment() childFragment.arguments = intent?.extras } supportFragmentManager.beginTransaction() .replace(android.R.id.content, childFragment, FRAGMENT_TAG) .commit() } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setIntent(intent) var childFragment: Fragment? = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) if (childFragment == null && intent?.extras != null) { childFragment = instantiateFragment() childFragment.arguments = intent.extras } supportFragmentManager.beginTransaction() .replace(android.R.id.content, childFragment!!, FRAGMENT_TAG) .commit() } companion object { const val FRAGMENT_TAG = "fragment" } }
gpl-2.0
e621cb2d99b9827d39a9a4daeed57c87
33.6875
97
0.677928
5.103448
false
false
false
false
nico-gonzalez/K-Places
presentation/src/main/java/com/edreams/android/workshops/kotlin/presentation/venues/model/VenuesUiModel.kt
1
606
package com.edreams.android.workshops.kotlin.presentation.venues.model data class VenueUiModel(val title: String, val photoUrl: String, val rating: Float, val formattedAddress: String?, val formattedPhone: String?) class VenuesUiModel private constructor(val venues: List<VenueUiModel> = emptyList(), val progress: Boolean = false, val error: String = "") { companion object { fun progress() = VenuesUiModel(progress = true) fun success(venues: List<VenueUiModel>) = VenuesUiModel(venues = venues) fun error(errorMessage: String) = VenuesUiModel(error = errorMessage) } }
apache-2.0
529e484197a839bd02b4b4083191ed2a
30.947368
85
0.737624
4.150685
false
false
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/impl/GroovyFileImportsImpl.kt
5
4527
// 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 org.jetbrains.plugins.groovy.lang.resolve.imports.impl import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement import org.jetbrains.plugins.groovy.lang.resolve.imports.* import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint import org.jetbrains.plugins.groovy.util.flatten internal class GroovyFileImportsImpl( override val file: GroovyFileBase, private val imports: Map<ImportKind<*>, Collection<GroovyImport>>, private val statementToImport: Map<GrImportStatement, GroovyImport>, private val importToStatement: Map<GroovyImport, GrImportStatement> ) : GroovyFileImports { @Suppress("UNCHECKED_CAST") private fun <T : GroovyImport> getImports(kind: ImportKind<T>): Collection<T> { val collection = imports[kind] ?: return emptyList() return collection as Collection<T> } private val regularImports get() = getImports(ImportKind.Regular) private val staticImports get() = getImports(ImportKind.Static) override val starImports: Collection<StarImport> get() = getImports(ImportKind.Star) override val staticStarImports: Collection<StaticStarImport> get() = getImports(ImportKind.StaticStar) override val allNamedImports: Collection<GroovyNamedImport> = flatten(regularImports, staticImports) private val allStarImports = flatten(starImports, staticStarImports) private val allNamedImportsMap by lazy { allNamedImports.groupBy { it.name } } override fun getImportsByName(name: String): Collection<GroovyNamedImport> = allNamedImportsMap[name] ?: emptyList() private fun ResolveState.putImport(import: GroovyImport): ResolveState { val state = put(importKey, import) val statement = importToStatement[import] ?: return state return state.put(ClassHint.RESOLVE_CONTEXT, statement) } @Suppress("LoopToCallChain") private fun Collection<GroovyImport>.doProcess(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { for (import in this) { if (!import.processDeclarations(processor, state.putImport(import), place, file)) return false } return true } override fun processStaticImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return staticImports.doProcess(processor, state, place) } override fun processAllNamedImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return allNamedImports.doProcess(processor, state, place) } override fun processStaticStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return staticStarImports.doProcess(processor, state, place) } override fun processAllStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return allStarImports.doProcess(processor, state, place) } override fun processDefaultImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return defaultImports.doProcess(processor, state, place) } override fun isImplicit(import: GroovyImport): Boolean = !importToStatement.containsKey(import) override fun findUnnecessaryStatements(): Collection<GrImportStatement> { return statementToImport.filterValues { it.isUnnecessary(this) }.keys } override fun findUnresolvedStatements(names: Collection<String>): Collection<GrImportStatement> { if (names.isEmpty()) return emptyList() val result = HashSet<GrImportStatement>() for (import in starImports) { val statement = importToStatement[import] ?: continue if (import.resolveImport(file) == null) { result += statement } } for (import in allNamedImports) { if (import.name !in names) continue val statement = importToStatement[import] ?: continue if (import.resolveImport(file) == null) { result += statement } } return result } override fun toString(): String = "Regular: ${regularImports.size}; " + "static: ${staticImports.size}; " + "*: ${starImports.size}; " + "static *: ${staticStarImports.size}" }
apache-2.0
3e5d424fcf2ed41968ba013047a95d3c
42.951456
140
0.743981
4.775316
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/WorldMapCacheName.kt
1
886
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.* import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 class WorldMapCacheName : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.interfaces.isEmpty() } .and { it.classInitializer != null } .and { it.classInitializer!!.instructions.any { it.opcode == LDC && it.ldcCst == "compositetexture" } } class name : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == String::class.type } } }
mit
6c47b9735346fcd4d9db2187f59bd1c9
41.238095
115
0.731377
3.885965
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/service/impl/GenreServiceImpl.kt
1
1935
package com.github.vhromada.catalog.service.impl import com.github.vhromada.catalog.common.exception.InputException import com.github.vhromada.catalog.common.provider.UuidProvider import com.github.vhromada.catalog.domain.Genre import com.github.vhromada.catalog.domain.filter.GenreFilter import com.github.vhromada.catalog.repository.GenreRepository import com.github.vhromada.catalog.service.GenreService import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional /** * A class represents implementation of service for genres. * * @author Vladimir Hromada */ @Service("genreService") class GenreServiceImpl( /** * Repository for genres */ private val repository: GenreRepository, /** * Provider for UUID */ private val uuidProvider: UuidProvider ) : GenreService { override fun search(filter: GenreFilter, pageable: Pageable): Page<Genre> { if (filter.isEmpty()) { return repository.findAll(pageable) } return repository.findAll(filter.toBooleanExpression(), pageable) } override fun get(uuid: String): Genre { return repository.findByUuid(uuid = uuid) .orElseThrow { InputException(key = "GENRE_NOT_EXIST", message = "Genre doesn't exist.", httpStatus = HttpStatus.NOT_FOUND) } } @Transactional override fun store(genre: Genre): Genre { return repository.save(genre) } @Transactional override fun remove(genre: Genre) { repository.delete(genre) } @Transactional override fun duplicate(genre: Genre): Genre { return repository.save(genre.copy(id = null, uuid = uuidProvider.getUuid())) } override fun getCount(): Long { return repository.count() } }
mit
b523e4cfee786285c8bca0b14f660603
29.714286
137
0.71938
4.387755
false
false
false
false
mikepenz/Android-Iconics
octicons-typeface-library/src/main/java/com/mikepenz/iconics/typeface/library/octicons/Octicons.kt
1
8515
/* * Copyright 2020 Mike Penz * * 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.mikepenz.iconics.typeface.library.octicons import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.iconics.typeface.ITypeface import java.util.LinkedList @Suppress("EnumEntryName") object Octicons : ITypeface { override val fontRes: Int get() = R.font.octicons_v11_1_0 override val characters: Map<String, Char> by lazy { Icon.values().associate { it.name to it.character } } override val mappingPrefix: String get() = "oct" override val fontName: String get() = "Octicons" override val version: String get() = "11.1.0" override val iconCount: Int get() = characters.size override val icons: List<String> get() = characters.keys.toCollection(LinkedList()) override val author: String get() = "GitHub" override val url: String get() = "https://github.com/primer/octicons" override val description: String get() = "GitHub's icon font https://github.com/primer/octicons" override val license: String get() = "MIT License" override val licenseUrl: String get() = "https://github.com/primer/octicons/blob/master/LICENSE" override fun getIcon(key: String): IIcon = Icon.valueOf(key) enum class Icon constructor(override val character: Char) : IIcon { //Octicons oct_alert('\ue900'), oct_archive('\ue901'), oct_arrow_both('\ue902'), oct_arrow_down('\ue905'), oct_arrow_down_left('\ue903'), oct_arrow_down_right('\ue904'), oct_arrow_left('\ue906'), oct_arrow_right('\ue907'), oct_arrow_switch('\ue908'), oct_arrow_up('\ue90b'), oct_arrow_up_left('\ue909'), oct_arrow_up_right('\ue90a'), oct_beaker('\ue90c'), oct_bell('\ue90f'), oct_bell_fill('\ue90d'), oct_bell_slash('\ue90e'), oct_bold('\ue910'), oct_book('\ue911'), oct_bookmark('\ue915'), oct_bookmark_fill('\ue912'), oct_bookmark_slash('\ue914'), oct_bookmark_slash_fill('\ue913'), oct_briefcase('\ue916'), oct_broadcast('\ue917'), oct_calendar('\ue918'), oct_check('\ue91b'), oct_check_circle('\ue91a'), oct_check_circle_fill('\ue919'), oct_checklist('\ue91c'), oct_chevron_down('\ue91d'), oct_chevron_left('\ue91e'), oct_chevron_right('\ue91f'), oct_chevron_up('\ue920'), oct_circle('\ue922'), oct_circle_slash('\ue921'), oct_clippy('\ue923'), oct_clock('\ue924'), oct_code('\ue927'), oct_code_review('\ue925'), oct_code_square('\ue926'), oct_comment('\ue929'), oct_comment_discussion('\ue928'), oct_commit('\ue92a'), oct_container('\ue92b'), oct_copy('\ue92c'), oct_cpu('\ue92d'), oct_credit_card('\ue92e'), oct_cross_reference('\ue92f'), oct_dash('\ue930'), oct_database('\ue931'), oct_desktop_download('\ue932'), oct_device_camera_video('\ue933'), oct_device_desktop('\ue934'), oct_device_mobile('\ue935'), oct_diff('\ue936'), oct_dot('\ue938'), oct_dot_fill('\ue937'), oct_download('\ue939'), oct_eye('\ue93b'), oct_eye_closed('\ue93a'), oct_file('\ue945'), oct_file_binary('\ue93c'), oct_file_code('\ue93d'), oct_file_diff('\ue93e'), oct_file_directory('\ue940'), oct_file_directory_fill('\ue93f'), oct_file_media('\ue941'), oct_file_submodule('\ue942'), oct_file_symlink_file('\ue943'), oct_file_zip('\ue944'), oct_filter('\ue946'), oct_flame('\ue947'), oct_fold('\ue94a'), oct_fold_down('\ue948'), oct_fold_up('\ue949'), oct_gear('\ue94b'), oct_gift('\ue94c'), oct_git_branch('\ue94d'), oct_git_commit('\ue94e'), oct_git_compare('\ue94f'), oct_git_fork('\ue950'), oct_git_merge('\ue951'), oct_git_pull_request('\ue952'), oct_globe('\ue953'), oct_grabber('\ue954'), oct_graph('\ue955'), oct_heading('\ue956'), oct_heart('\ue958'), oct_heart_fill('\ue957'), oct_history('\ue959'), oct_home('\ue95b'), oct_home_fill('\ue95a'), oct_horizontal_rule('\ue95c'), oct_hourglass('\ue95d'), oct_hubot('\ue95e'), oct_image('\ue95f'), oct_inbox('\ue960'), oct_infinity('\ue961'), oct_info('\ue962'), oct_insights('\ue963'), oct_issue_closed('\ue964'), oct_issue_opened('\ue965'), oct_issue_reopened('\ue966'), oct_italic('\ue967'), oct_kebab_horizontal('\ue968'), oct_key('\ue969'), oct_law('\ue96a'), oct_light_bulb('\ue96b'), oct_link('\ue96d'), oct_link_external('\ue96c'), oct_list_ordered('\ue96e'), oct_list_unordered('\ue96f'), oct_location('\ue970'), oct_lock('\ue971'), oct_mail('\ue972'), oct_megaphone('\ue973'), oct_mention('\ue974'), oct_milestone('\ue975'), oct_mirror('\ue976'), oct_moon('\ue977'), oct_mortar_board('\ue978'), oct_mute('\ue979'), oct_no_entry('\ue97a'), oct_north_star('\ue97b'), oct_note('\ue97c'), oct_octoface('\ue97d'), oct_organization('\ue97e'), oct_package('\ue981'), oct_package_dependencies('\ue97f'), oct_package_dependents('\ue980'), oct_paper_airplane('\ue982'), oct_pencil('\ue983'), oct_people('\ue984'), oct_person('\ue985'), oct_pin('\ue986'), oct_play('\ue987'), oct_plug('\ue988'), oct_plus('\ue98a'), oct_plus_circle('\ue989'), oct_project('\ue98b'), oct_pulse('\ue98c'), oct_question('\ue98d'), oct_quote('\ue98e'), oct_reply('\ue98f'), oct_repo('\ue992'), oct_repo_push('\ue990'), oct_repo_template('\ue991'), oct_report('\ue993'), oct_rocket('\ue994'), oct_rss('\ue995'), oct_ruby('\ue996'), oct_screen_full('\ue997'), oct_screen_normal('\ue998'), oct_search('\ue999'), oct_server('\ue99a'), oct_share('\ue99c'), oct_share_android('\ue99b'), oct_shield('\ue9a0'), oct_shield_check('\ue99d'), oct_shield_lock('\ue99e'), oct_shield_x('\ue99f'), oct_sign_in('\ue9a1'), oct_sign_out('\ue9a2'), oct_skip('\ue9a3'), oct_smiley('\ue9a4'), oct_square('\ue9a6'), oct_square_fill('\ue9a5'), oct_squirrel('\ue9a7'), oct_star('\ue9a9'), oct_star_fill('\ue9a8'), oct_stop('\ue9aa'), oct_stopwatch('\ue9ab'), oct_sun('\ue9ac'), oct_sync('\ue9ad'), oct_tab('\ue9ae'), oct_tag('\ue9af'), oct_tasklist('\ue9b0'), oct_telescope('\ue9b1'), oct_terminal('\ue9b2'), oct_thumbsdown('\ue9b3'), oct_thumbsup('\ue9b4'), oct_tools('\ue9b5'), oct_trash('\ue9b6'), oct_triangle_down('\ue9b7'), oct_triangle_left('\ue9b8'), oct_triangle_right('\ue9b9'), oct_triangle_up('\ue9ba'), oct_typography('\ue9bb'), oct_unfold('\ue9bc'), oct_unlock('\ue9bd'), oct_unmute('\ue9be'), oct_unverified('\ue9bf'), oct_upload('\ue9c0'), oct_verified('\ue9c1'), oct_versions('\ue9c2'), oct_workflow('\ue9c3'), oct_x('\ue9c6'), oct_x_circle('\ue9c5'), oct_x_circle_fill('\ue9c4'), oct_zap('\ue9c7'); override val typeface: ITypeface by lazy { Octicons } } }
apache-2.0
d3f4b81486c9ee0a76fd5e17b91f1fa4
30.654275
75
0.537287
3.47551
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/EditorMidi.kt
2
3068
package io.github.chrislo27.rhre3.editor import com.badlogic.gdx.Gdx import io.github.chrislo27.rhre3.PreferenceKeys import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.entity.Entity import io.github.chrislo27.rhre3.entity.model.IRepitchable import io.github.chrislo27.rhre3.entity.model.cue.CueEntity import io.github.chrislo27.rhre3.midi.MidiHandler import io.github.chrislo27.rhre3.sfxdb.SFXDatabase import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.Cue import io.github.chrislo27.rhre3.track.PlayState import io.github.chrislo27.rhre3.track.PlaybackCompletion import io.github.chrislo27.rhre3.track.Remix data class BuildingNote(val note: MidiHandler.MidiReceiver.Note, val entity: Entity) class EditorMidiListener(val editor: Editor) : MidiHandler.MidiNoteListener { private val remix: Remix get() = editor.remix var numberOfNotes = 0 override fun noteOn(note: MidiHandler.MidiReceiver.Note) { Gdx.app.postRunnable { val selection = editor.selection if (remix.playState == PlayState.STOPPED) { if (editor.clickOccupation == ClickOccupation.None && selection.isNotEmpty()) { editor.changePitchOfSelection(note.semitone, false, true, selection) } } else if (RHRE3.midiRecording && remix.playState == PlayState.PLAYING) { val defaultCue = SFXDatabase.data.objectMap[Remix.DEFAULT_MIDI_NOTE]!! as Cue val noteCue = SFXDatabase.data.objectMap[remix.main.preferences.getString(PreferenceKeys.MIDI_NOTE)] ?: defaultCue val ent = noteCue.createEntity(remix, null).apply { updateBounds { bounds.set(remix.beat, (numberOfNotes % remix.trackCount).toFloat(), 0f, 1f) } if (this is IRepitchable) { semitone = note.semitone (this as? CueEntity)?.stopAtEnd = true } } ent.updateInterpolation(true) ent.playbackCompletion = PlaybackCompletion.FINISHED remix.addEntity(ent) val bn = BuildingNote(note, ent) editor.buildingNotes[bn.note] = bn numberOfNotes++ } } } override fun noteOff(note: MidiHandler.MidiReceiver.Note) { if (RHRE3.midiRecording && editor.buildingNotes.containsKey(note)) editor.buildingNotes.remove(note) } var pedalDown = false override fun controlChange(ccNumber: Int, data: Int) { if (ccNumber == 64) { if (RHRE3.midiRecording && data < 64 && pedalDown) { val state = remix.playState if (state == PlayState.STOPPED || state == PlayState.PAUSED) { remix.playState = PlayState.PLAYING } else if (state == PlayState.PLAYING) { remix.playState = PlayState.PAUSED } } pedalDown = data >= 64 } } }
gpl-3.0
ba9f1072626e0bf56b17cfc061df2bab
39.906667
130
0.624837
4.208505
false
false
false
false
ursjoss/sipamato
public/public-persistence-jooq/src/test/kotlin/ch/difty/scipamato/publ/persistence/paper/JooqPublicPaperServiceTest.kt
2
2698
package ch.difty.scipamato.publ.persistence.paper import ch.difty.scipamato.common.persistence.paging.PaginationContext import ch.difty.scipamato.publ.entity.PublicPaper import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldHaveSize import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test internal class JooqPublicPaperServiceTest { private val publicPaper: PublicPaper = PublicPaper(id = ID) private val mockRepo = mockk<PublicPaperRepository>() private val filterMock = mockk<PublicPaperFilter>() private val paginationContextMock = mockk<PaginationContext>() private val papers = listOf(publicPaper, PublicPaper(id = ID + 1)) private val service = JooqPublicPaperService(mockRepo) @AfterEach fun tearDown() { confirmVerified(mockRepo) } @Test fun findingByNumber_withRepoFindingRecord_returnsItWrappedAsOptional() { every { mockRepo.findByNumber(NUMBER) } returns publicPaper val paperOp = service.findByNumber(NUMBER) paperOp shouldBeEqualTo publicPaper verify { mockRepo.findByNumber(NUMBER) } } @Test fun findingByNumber_withRepoNotFindingRecord_returnsEmptyOptional() { every { mockRepo.findByNumber(NUMBER) } returns null val paperOp = service.findByNumber(NUMBER) paperOp.shouldBeNull() verify { mockRepo.findByNumber(NUMBER) } } @Test fun findingPageByFilter_delegatesToRepo() { every { mockRepo.findPageByFilter(filterMock, paginationContextMock) } returns papers service.findPageByFilter(filterMock, paginationContextMock) shouldHaveSize 2 verify { mockRepo.findPageByFilter(filterMock, paginationContextMock) } } @Test fun countingByFilter_delegatesToRepo() { every { mockRepo.countByFilter(filterMock) } returns 2 service.countByFilter(filterMock) shouldBeEqualTo 2 verify { mockRepo.countByFilter(filterMock) } } @Test fun findingPageOfIdsByFilter_delegatesToRepo() { val idList = listOf(3L, 5L) every { mockRepo.findPageOfNumbersByFilter(filterMock, paginationContextMock) } returns idList service.findPageOfNumbersByFilter(filterMock, paginationContextMock) shouldBeEqualTo idList verify { mockRepo.findPageOfNumbersByFilter(filterMock, paginationContextMock) } } companion object { private const val ID: Long = 5 private const val NUMBER: Long = 15 } }
gpl-3.0
18cd4a0104e3b02aa796e7ff0d13b156
33.151899
102
0.742772
4.572881
false
true
false
false
Homes-MinecraftServerMod/Homes
src/test/java/com/masahirosaito/spigot/homes/testutils/MockWorldFactory.kt
1
1376
package com.masahirosaito.spigot.homes.testutils import org.bukkit.Chunk import org.bukkit.Location import org.bukkit.World import org.mockito.Matchers.any import org.powermock.api.mockito.PowerMockito.mock import java.util.* import org.powermock.api.mockito.PowerMockito.`when` as pwhen object MockWorldFactory { val worlds: MutableMap<UUID, World> = mutableMapOf() fun makeNewMockWorld(name: String): World { return mock(World::class.java).apply { val uuid = UUID.randomUUID() pwhen(uid).thenReturn(uuid) pwhen(getName()).thenReturn(name) pwhen(getChunkAt(any(Location::class.java))) .then { makeNewChunk() } MockWorldFactory.register(this) } } fun makeNewChunk(): Chunk { return mock(Chunk::class.java).apply { pwhen(isLoaded).thenReturn(false) } } fun makeRandomLocation() = Location(makeNewMockWorld("world"), randomDouble(), randomDouble(), randomDouble(), randomFloat(), randomFloat()) private fun register(world: World) { MockWorldFactory.worlds.put(world.uid, world) } fun clear() { MockWorldFactory.worlds.clear() } private fun randomDouble(): Double = Random().nextDouble() * 100 private fun randomFloat(): Float = Random().nextFloat() * 100 }
apache-2.0
2520b56b189dba5f2d5ae16118d61b8d
28.913043
68
0.648256
4.286604
false
false
false
false
fluidsonic/fluid-json
annotation-processor/test-cases/1/output-expected/json/encoding/DefaultJsonCodec.kt
1
2126
package json.encoding import codecProvider.CustomCodingContext import io.fluidsonic.json.AbstractJsonCodec import io.fluidsonic.json.JsonCodingType import io.fluidsonic.json.JsonDecoder import io.fluidsonic.json.JsonEncoder import io.fluidsonic.json.missingPropertyError import io.fluidsonic.json.readBooleanOrNull import io.fluidsonic.json.readByteOrNull import io.fluidsonic.json.readCharOrNull import io.fluidsonic.json.readDoubleOrNull import io.fluidsonic.json.readFloatOrNull import io.fluidsonic.json.readFromMapByElementValue import io.fluidsonic.json.readIntOrNull import io.fluidsonic.json.readLongOrNull import io.fluidsonic.json.readShortOrNull import io.fluidsonic.json.readStringOrNull import io.fluidsonic.json.readValueOfType import io.fluidsonic.json.readValueOfTypeOrNull import io.fluidsonic.json.writeBooleanOrNull import io.fluidsonic.json.writeByteOrNull import io.fluidsonic.json.writeCharOrNull import io.fluidsonic.json.writeDoubleOrNull import io.fluidsonic.json.writeFloatOrNull import io.fluidsonic.json.writeIntOrNull import io.fluidsonic.json.writeIntoMap import io.fluidsonic.json.writeLongOrNull import io.fluidsonic.json.writeMapElement import io.fluidsonic.json.writeShortOrNull import io.fluidsonic.json.writeStringOrNull import io.fluidsonic.json.writeValueOrNull import json.encoding.value9 import kotlin.String import kotlin.Unit internal object DefaultJsonCodec : AbstractJsonCodec<Default, CustomCodingContext>() { public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<Default>): Default { var _value1: String? = null readFromMapByElementValue { key -> when (key) { "value1" -> _value1 = readString() else -> skipValue() } } return Default( value1 = _value1 ?: missingPropertyError("value1") ) } public override fun JsonEncoder<CustomCodingContext>.encode(`value`: Default): Unit { writeIntoMap { writeMapElement("value1", string = value.value1) writeMapElement("value2", string = value.value2) writeMapElement("value6", string = value.value6) writeMapElement("value9", string = value.value9) } } }
apache-2.0
d9614c6c5ca9ac2cbff7411251297887
33.290323
97
0.819849
4.392562
false
false
false
false
xranby/modern-jogl-examples
src/main/kotlin/main/tut05/depthBuffer.kt
1
10315
package main.tut05 import buffer.destroy import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL2ES3.GL_DEPTH import com.jogamp.opengl.GL3 import extensions.floatBufferBig import extensions.intBufferBig import extensions.toFloatBuffer import extensions.toShortBuffer import glsl.programOf import main.* import main.framework.Framework import main.framework.Semantic import vec._3.Vec3 import vec._4.Vec4 /** * Created by elect on 22/02/17. */ fun main(args: Array<String>) { DepthBuffer_() } class DepthBuffer_ : Framework("Tutorial 05 - Depth Buffering") { object Buffer { val VERTEX = 0 val INDEX = 1 val MAX = 2 } var theProgram = 0 var offsetUniform = 0 var perspectiveMatrixUnif = 0 val numberOfVertices = 36 val perspectiveMatrix = floatBufferBig(16) val frustumScale = 1.0f val bufferObject = intBufferBig(Buffer.MAX) val vao = intBufferBig(1) val RIGHT_EXTENT = 0.8f val LEFT_EXTENT = -RIGHT_EXTENT val TOP_EXTENT = 0.20f val MIDDLE_EXTENT = 0.0f val BOTTOM_EXTENT = -TOP_EXTENT val FRONT_EXTENT = -1.25f val REAR_EXTENT = -1.75f val GREEN_COLOR = floatArrayOf(0.75f, 0.75f, 1.0f, 1.0f) val BLUE_COLOR = floatArrayOf(0.0f, 0.5f, 0.0f, 1.0f) val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f) val GREY_COLOR = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f) val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f) val vertexData = floatArrayOf( //Object 1 positions LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, //Object 2 positions TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, //Object 1 colors GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], //Object 2 colors RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3]) val indexData = shortArrayOf( 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14) override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeBuffers(gl) glGenVertexArrays(1, vao) glBindVertexArray(vao[0]) val colorData = Float.BYTES * 3 * numberOfVertices glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX]) glEnableVertexAttribArray(Semantic.Attr.POSITION) glEnableVertexAttribArray(Semantic.Attr.COLOR) glVertexAttribPointer(Semantic.Attr.POSITION, 3, GL_FLOAT, false, Vec3.SIZE, 0) glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_FLOAT, false, Vec4.SIZE, colorData.L) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObject[Buffer.INDEX]) glBindVertexArray(0) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthMask(true) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) } fun initializeProgram(gl: GL3) = with(gl) { theProgram = programOf(gl, this::class.java, "tut05", "standard.vert", "standard.frag") offsetUniform = glGetUniformLocation(theProgram, "offset") perspectiveMatrixUnif = glGetUniformLocation(theProgram, "perspectiveMatrix") val zNear = 1.0f val zFar = 3.0f perspectiveMatrix[0] = frustumScale perspectiveMatrix[5] = frustumScale perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar) perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar) perspectiveMatrix[11] = -1.0f glUseProgram(theProgram) glUniformMatrix4fv(perspectiveMatrixUnif, 1, false, perspectiveMatrix) glUseProgram(0) } fun initializeBuffers(gl: GL3) = with(gl) { val vertexBuffer = vertexData.toFloatBuffer() val indexBuffer = indexData.toShortBuffer() glGenBuffers(Buffer.MAX, bufferObject) glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX]) glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.INDEX]) glBufferData(GL_ARRAY_BUFFER, indexBuffer.SIZE.L, indexBuffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) vertexBuffer.destroy() indexBuffer.destroy() } override fun display(gl: GL3) = with(gl) { glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0.0f).put(1, 0.0f).put(2, 0.0f).put(3, 0.0f)) glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1.0f)) glUseProgram(theProgram) glBindVertexArray(vao[0]) glUniform3f(offsetUniform, 0.0f, 0.0f, 0.0f) glDrawElements(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT, 0) glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f) glDrawElementsBaseVertex(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT, 0, numberOfVertices / 2) glBindVertexArray(0) glUseProgram(0) } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { perspectiveMatrix.put(0, frustumScale * (h / w.f)) perspectiveMatrix.put(5, frustumScale) glUseProgram(theProgram) glUniformMatrix4fv(perspectiveMatrixUnif, 1, false, perspectiveMatrix) glUseProgram(0) glViewport(0, 0, w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(Buffer.MAX, bufferObject) glDeleteVertexArrays(1, vao) vao.destroy() bufferObject.destroy() perspectiveMatrix.destroy() } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> { animator.remove(window) window.destroy() } } } }
mit
05dbaed30d2b959cb4478a6d9038acfb
34.450172
106
0.609695
3.541023
false
false
false
false
jankotek/elsa
src/test/java/org/mapdb/elsa/CyclicReferenceTest.kt
1
8940
package org.mapdb.elsa import org.junit.Assert.* import org.junit.Test import java.io.Serializable import java.util.* /** * Randomly generates data, tests that cyclic reference (Object Stack) works correctly. */ class CyclicReferenceTest{ companion object { class NotSeriazable1 {} class NotSeriazable2 {} val SINGLETON1 = NotSeriazable1() val SINGLETON2 = NotSeriazable2() interface Container<A> : Generator<A> { fun add(a: A, content: Array<Any?>): A fun getContent(a: A): Array<Any?> } interface Generator<A> { fun random(): A } object NULL : Generator<Any?> { override fun random() = null } object STRING : Generator<String> { override fun random() = TT.randomString() } object INTEGER : Generator<Int> { override fun random() = Random().nextInt() } object SINGLETON : Generator<Any> { override fun random() = if (Random().nextBoolean()) SINGLETON1 else SINGLETON2 } object ARRAY : Container<Array<Any?>> { override fun add(a: Array<Any?>, content: Array<Any?>): Array<Any?> { val origSize = a.size; val a = Arrays.copyOf(a, a.size + content.size) System.arraycopy(content, 0, a, origSize, content.size) return a; } override fun getContent(a: Array<Any?>): Array<Any?> { return a } override fun random(): Array<Any?> { return Array<Any?>(0,{null}) } } class ArrayWrapper(var obj:Array<Any?>) : Serializable { override fun equals(other: Any?): Boolean { return other is ArrayWrapper && Arrays.deepEquals(this.obj,other.obj) } override fun hashCode(): Int { return Arrays.deepHashCode(this.obj) } } object ARRAY_WRAPPER : Container<ArrayWrapper>{ override fun random(): ArrayWrapper { return ArrayWrapper(ARRAY.random()) } override fun add(a: ArrayWrapper, content: Array<Any?>): ArrayWrapper { a.obj = ARRAY.add(a.obj, content) return a } override fun getContent(a: ArrayWrapper): Array<Any?> { return a.obj } } abstract class CollectionContainer :Container<MutableCollection<Any?>>{ override fun add(a: MutableCollection<Any?>, content: Array<Any?>): MutableCollection<Any?> { a.addAll(content) return a } override fun getContent(a: MutableCollection<Any?>): Array<Any?> { return a.toTypedArray() } } object ARRAYLIST: CollectionContainer(){ override fun random() = ArrayList<Any?>() } abstract class MapContainer:Container<MutableMap<Any?,Any?>>{ override fun add(a: MutableMap<Any?, Any?>, content: Array<Any?>): MutableMap<Any?, Any?> { for(i in 0 until content.size step 2){ val key = content[i] val value = if(i+1>=content.size) null else content[i+1] a.put(key, value) } return a } override fun getContent(a: MutableMap<Any?, Any?>): Array<Any?> { return (a.keys.toList()+a.values.toList()).toTypedArray() } } object TREEMAP: MapContainer(){ override fun random() = TreeMap<Any?,Any?>() } object HASHMAP: MapContainer(){ override fun random() = HashMap<Any?,Any?>() } object LINKEDHASHMAP: MapContainer(){ override fun random() = LinkedHashMap<Any?,Any?>() } object TREESET: CollectionContainer(){ override fun random() = TreeSet<Any?>() } object HASHSET: CollectionContainer(){ override fun random() = HashSet<Any?>() } object LINKEDHASHSET: CollectionContainer(){ override fun random() = LinkedHashSet<Any?>() } object LINKEDLIST: CollectionContainer(){ override fun random() = LinkedList<Any?>() } val cc = arrayOf(NULL, STRING, INTEGER, SINGLETON, ARRAY, ARRAYLIST, TREEMAP, HASHMAP, LINKEDHASHMAP, TREESET, HASHSET, LINKEDHASHSET, LINKEDLIST ) val ccNoNullArray = cc.filter{it!=ARRAY && it!=NULL} val ccObj = ccNoNullArray+ARRAY_WRAPPER val singletons = arrayOf(SINGLETON1, SINGLETON2) val ser = ElsaSerializerBase(null, 0, singletons, null, null, null) val serPojo = ElsaSerializerPojo(null, 0, singletons, null, null, null, null, null) } fun eq(v1:Any?, v2:Any?){ if(v1 is Array<*>) assertArrayEquals(v1, v2 as Array<*>) else assertEquals(v1,v2) } @Test fun run() { for(c in cc){ val v1 = c.random() eq(v1, ElsaSerializerBaseTest.clonePojo(v1, ser)) } } @Test fun run2() { for(c in ccObj){ val v1 = c.random() eq(v1, ElsaSerializerBaseTest.clonePojo(v1, serPojo)) } } @Test fun cyclic() { for(c in ccNoNullArray.filter{it is Container}) { for (c2 in ccNoNullArray) try{ var v = c.random() v = (c as Container<Any?>).add(v, arrayOf(c2.random(), c2.random(), c2.random())) val cloned = ElsaSerializerBaseTest.clonePojo(v,ser) eq(v, cloned) }catch(e:ClassCastException){ if(e.message!!.contains("Comparable").not()) throw e } } } @Test fun cyclic2() { for(c in ccObj.filter{it is Container}) { for (c2 in ccObj) try{ var v = c.random() v = (c as Container<Any?>).add(v, arrayOf(c2.random(), c2.random(), c2.random())) val cloned = ElsaSerializerBaseTest.clonePojo(v,serPojo) eq(v, cloned) }catch(e:ClassCastException){ if(e.message!!.contains("Comparable").not()) throw e } } } @Test fun selfReference() { for (c in ccNoNullArray.filter { it is Container }) try { val v = c.random() (c as Container<Any?>).add(v, arrayOf(v)) val cloned = ElsaSerializerBaseTest.clonePojo(v,ser) assertTrue(cloned=== c.getContent(cloned)[0]) }catch(e:ClassCastException){ if(e.message!!.contains("Comparable").not()) throw e } } @Test fun selfReference2() { for (c in ccObj.filter { it is Container }) try { val v = c.random() (c as Container<Any?>).add(v, arrayOf(v)) val cloned = ElsaSerializerBaseTest.clonePojo(v,serPojo) assertTrue(cloned=== c.getContent(cloned)[0]) }catch(e:ClassCastException){ if(e.message!!.contains("Comparable").not()) throw e } } @Test fun doubleRef() { for (c in ccNoNullArray.filter { it is Container }){ for (c2 in ccNoNullArray) try { val v = c.random() if(v is Set<*>) continue val v2 = c2.random() (c as Container<Any?>).add(v, arrayOf(v2, v2)) val cloned = ElsaSerializerBaseTest.clonePojo(v, ser) val clonedContent = c.getContent(cloned) assertEquals(2,clonedContent.size) assertTrue(clonedContent[0]===clonedContent[1]) } catch(e: ClassCastException) { if (e.message!!.contains("Comparable").not()) throw e } } } @Test fun doubleRef2() { for (c in ccObj.filter { it is Container }){ for (c2 in ccObj) try { val v = c.random() if(v is Set<*>) continue val v2 = c2.random() (c as Container<Any?>).add(v, arrayOf(v2,v2)) val cloned = ElsaSerializerBaseTest.clonePojo(v, serPojo) val clonedContent = c.getContent(cloned) assertEquals(2,clonedContent.size) assertTrue(clonedContent[0]===clonedContent[1]) } catch(e: ClassCastException) { if (e.message!!.contains("Comparable").not()) throw e } } } }
apache-2.0
516db78bcfc1fc36e77779f9d7d43d89
29.305085
105
0.509843
4.399606
false
true
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/src/DefaultExecutor.kt
1
6544
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.internal.* import java.util.concurrent.* import kotlin.coroutines.* private val defaultMainDelayOptIn = systemProp("kotlinx.coroutines.main.delay", false) internal actual val DefaultDelay: Delay = initializeDefaultDelay() private fun initializeDefaultDelay(): Delay { // Opt-out flag if (!defaultMainDelayOptIn) return DefaultExecutor val main = Dispatchers.Main /* * When we already are working with UI and Main threads, it makes * no sense to create a separate thread with timer that cannot be controller * by the UI runtime. */ return if (main.isMissing() || main !is Delay) DefaultExecutor else main } @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") internal actual object DefaultExecutor : EventLoopImplBase(), Runnable { const val THREAD_NAME = "kotlinx.coroutines.DefaultExecutor" init { incrementUseCount() // this event loop is never completed } private const val DEFAULT_KEEP_ALIVE_MS = 1000L // in milliseconds private val KEEP_ALIVE_NANOS = TimeUnit.MILLISECONDS.toNanos( try { java.lang.Long.getLong("kotlinx.coroutines.DefaultExecutor.keepAlive", DEFAULT_KEEP_ALIVE_MS) } catch (e: SecurityException) { DEFAULT_KEEP_ALIVE_MS }) @Suppress("ObjectPropertyName") @Volatile private var _thread: Thread? = null override val thread: Thread get() = _thread ?: createThreadSync() private const val FRESH = 0 private const val ACTIVE = 1 private const val SHUTDOWN_REQ = 2 private const val SHUTDOWN_ACK = 3 private const val SHUTDOWN = 4 @Volatile private var debugStatus: Int = FRESH private val isShutDown: Boolean get() = debugStatus == SHUTDOWN private val isShutdownRequested: Boolean get() { val debugStatus = debugStatus return debugStatus == SHUTDOWN_REQ || debugStatus == SHUTDOWN_ACK } actual override fun enqueue(task: Runnable) { if (isShutDown) shutdownError() super.enqueue(task) } override fun reschedule(now: Long, delayedTask: DelayedTask) { // Reschedule on default executor can only be invoked after Dispatchers.shutdown shutdownError() } private fun shutdownError() { throw RejectedExecutionException("DefaultExecutor was shut down. " + "This error indicates that Dispatchers.shutdown() was invoked prior to completion of exiting coroutines, leaving coroutines in incomplete state. " + "Please refer to Dispatchers.shutdown documentation for more details") } override fun shutdown() { debugStatus = SHUTDOWN super.shutdown() } /** * All event loops are using DefaultExecutor#invokeOnTimeout to avoid livelock on * ``` * runBlocking(eventLoop) { withTimeout { while(isActive) { ... } } } * ``` * * Livelock is possible only if `runBlocking` is called on internal default executed (which is used by default [delay]), * but it's not exposed as public API. */ override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle = scheduleInvokeOnTimeout(timeMillis, block) override fun run() { ThreadLocalEventLoop.setEventLoop(this) registerTimeLoopThread() try { var shutdownNanos = Long.MAX_VALUE if (!notifyStartup()) return while (true) { Thread.interrupted() // just reset interruption flag var parkNanos = processNextEvent() if (parkNanos == Long.MAX_VALUE) { // nothing to do, initialize shutdown timeout val now = nanoTime() if (shutdownNanos == Long.MAX_VALUE) shutdownNanos = now + KEEP_ALIVE_NANOS val tillShutdown = shutdownNanos - now if (tillShutdown <= 0) return // shut thread down parkNanos = parkNanos.coerceAtMost(tillShutdown) } else shutdownNanos = Long.MAX_VALUE if (parkNanos > 0) { // check if shutdown was requested and bail out in this case if (isShutdownRequested) return parkNanos(this, parkNanos) } } } finally { _thread = null // this thread is dead acknowledgeShutdownIfNeeded() unregisterTimeLoopThread() // recheck if queues are empty after _thread reference was set to null (!!!) if (!isEmpty) thread // recreate thread if it is needed } } @Synchronized private fun createThreadSync(): Thread { return _thread ?: Thread(this, THREAD_NAME).apply { _thread = this isDaemon = true start() } } // used for tests @Synchronized internal fun ensureStarted() { assert { _thread == null } // ensure we are at a clean state assert { debugStatus == FRESH || debugStatus == SHUTDOWN_ACK } debugStatus = FRESH createThreadSync() // create fresh thread while (debugStatus == FRESH) (this as Object).wait() } @Synchronized private fun notifyStartup(): Boolean { if (isShutdownRequested) return false debugStatus = ACTIVE (this as Object).notifyAll() return true } @Synchronized // used _only_ for tests fun shutdownForTests(timeout: Long) { val deadline = System.currentTimeMillis() + timeout if (!isShutdownRequested) debugStatus = SHUTDOWN_REQ // loop while there is anything to do immediately or deadline passes while (debugStatus != SHUTDOWN_ACK && _thread != null) { _thread?.let { unpark(it) } // wake up thread if present val remaining = deadline - System.currentTimeMillis() if (remaining <= 0) break (this as Object).wait(timeout) } // restore fresh status debugStatus = FRESH } @Synchronized private fun acknowledgeShutdownIfNeeded() { if (!isShutdownRequested) return debugStatus = SHUTDOWN_ACK resetAll() // clear queues (this as Object).notifyAll() } internal val isThreadPresent get() = _thread != null }
apache-2.0
71d4539e9f1e2e94ef4350a07fd98cc0
34.372973
160
0.626681
4.876304
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/functions/defaultargs1.kt
5
514
fun <T> T.toPrefixedString(prefix: String = "", suffix: String="") = prefix + this.toString() + suffix fun box() : String { if("mama".toPrefixedString(suffix="321", prefix="papa") != "papamama321") return "fail" if("mama".toPrefixedString(prefix="papa") != "papamama") return "fail" if("mama".toPrefixedString("papa", "239") != "papamama239") return "fail" if("mama".toPrefixedString("papa") != "papamama") return "fail" if("mama".toPrefixedString() != "mama") return "fail" return "OK" }
apache-2.0
d14b2eea46404d997930a394b47c7fc3
50.4
102
0.643969
3.04142
false
false
false
false
LouisCAD/Splitties
plugin/src/main/kotlin/com/louiscad/splitties/MigrateAndroidxTask.kt
1
12739
package com.louiscad.splitties import AndroidX import Google import JakeWharton import Kotlin import KotlinX import Splitties import Square import Testing import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.Incubating import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency import org.gradle.api.tasks.TaskAction import java.io.File import kotlin.reflect.KClass import kotlin.reflect.KVisibility import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.javaField import kotlin.reflect.typeOf @Incubating open class MigrateAndroidxTask : DefaultTask() { init { group = "help" description = "Migrate package to AndroidX" } @TaskAction fun migratePackages() = with(AndroidxMigrator) { println() println("## Searching Android Support Dependencies") println("$OK Parsing file androidx-artifact-mapping.csv") val artifacts: List<ArtifactMapping> = readArtifactMappings() val androidSupportDependencies = findAndroidSupportDependencies(project, artifacts) println(gradleSyntax(androidSupportDependencies.map { "${it.group}:${it.name}:${it.version}" }, emptyMap())) println("## Checking that you use compileSdkVersion 28") val detected = tryDetectCompileSdkVersion(project.rootDir) val version = detected.mapNotNull { detectVersion(it) }.firstOrNull() println( when (version) { null -> "⚠️ Make sure you are using compileSdkVersion 28. See $MIGRATE_TO_28" 28 -> "$OK You are using compileSdkVersion 28" else -> throw GradleException("You should migrate first to compileSdkVersion 28. See $MIGRATE_TO_28") } ) println() println("## Migrating classes from support libraries to AndroidX.") println("$OK Parsing file androidx-class-mapping.csv") val androidxClassMappings: List<String> = readAndroidxClassMappings() val moduleDirectories: List<File> = project.subprojects.map { it.projectDir } println("$OK Modules: ${moduleDirectories.map { it.relativeTo(project.rootDir) }}") val sourceFiles = sourceFiles(moduleDirectories) val gradleFiles = gradleFiles(moduleDirectories) println("$OK Found ${sourceFiles.size} source files that may need migration") val supportLibsToAndroidXMappings = supportLibsToAndroidXMappings(androidxClassMappings) val rawSupportLibsToAndroidXPackageMappings = rawSupportLibsToAndroidXPackageMappings(supportLibsToAndroidXMappings) val supportLibsToAndroidXStarImportMappings = supportLibsToAndroidXStarImportMappings(rawSupportLibsToAndroidXPackageMappings) println("$OK File androidx-class-mapping.csv parsed correctly") val replaces: List<Pair<String, String>> = supportLibsToAndroidXMappings + supportLibsToAndroidXStarImportMappings println("$OK Starting batch migration...") val editedSourceFilesCount = sourceFiles.count { it.migrateToAndroidX(replaces) } val editedGradleFilesCount = gradleFiles.count { it.migrateToAndroidX(replaces) } println( "\n$OK $editedSourceFilesCount source files (${sourceExtensions.joinToString(",") { it }}) " + "have been migrated (${sourceFiles.count() - editedSourceFilesCount} didn't need it)." ) println( "$OK $editedGradleFilesCount gradle files have been migrated " + "(${gradleFiles.count() - editedGradleFilesCount} didn't need it)." ) println() println("## Detecting Gradle properties") val hasProperties = PROPERTIES.all { project.hasProperty(it) } if (hasProperties) { println("$OK gradle.properties already contains $PROPERTIES") } else { val file = project.rootProject.file("gradle.properties") file.appendText(GRADLE_PROPERTIES) println("$OK Added ${PROPERTIES} to file gradle.properties") } println() println("## Your turn: use instead those Androidx libraries") val map = artifacts.associate { it.supportArtifact to it.androidXArtifact } val splitties = getArtifactNameToSplittiesConstantMapping() println(gradleSyntax(androidSupportDependencies.mapNotNull { map[it.artifact] }, splitties)) } } private data class ArtifactMapping( val supportArtifact: String, val androidXArtifact: String ) private object AndroidxMigrator { const val OK = "✔ \uD83C\uDD97" val PROPERTIES = listOf("android.useAndroidX", "android.enableJetifier") val GRADLE_PROPERTIES = PROPERTIES.joinToString(separator = "\n", prefix = "\n", postfix = "\n") { "$it=true" } const val MIGRATE_TO_28 = "https://developer.android.com/about/versions/pie/android-9.0-migration" val Dependency.artifact: String get() = "$group:$name" fun gradleSyntax(artifacts: List<String>, splitties: Map<String, String>): String { if (artifacts.isEmpty()) { return "$OK No Android support dependency needs to be migrated" } return artifacts.joinToString("\n", prefix = "\n", postfix = "\n") { artifact -> val configuration = if (artifact.contains("test")) "androidTestImplementation" else "implementation" if (artifact in splitties) { "$configuration(${splitties[artifact]})" } else { """$configuration("$artifact")""" } } } fun readArtifactMappings(): List<ArtifactMapping> { val lines: List<String> = this::class.java.getResourceAsStream("/androidx-artifact-mapping.csv").reader().readLines() return lines .drop(1) .filter { it.contains(",") } .map { val (old, new) = it.split(",") ArtifactMapping(old, new) } } fun tryDetectCompileSdkVersion(rootDir: File): List<String> { return rootDir.walk() .filter { it.isFile } .filter { it.name.endsWith(".gradle.kts") || it.name.endsWith(".gradle") } .flatMap { it.readLines().mapNotNull { containsCompileSdkVersion(it) }.asSequence() } .toList() } /*** * Convert one of those lines to 28 or null * * compileSdkVersion 28 * compileSdkVersion(28) * compileSdkVersion = 28 */ fun detectVersion(line: String): Int? { var input = line.trim() listOf("compileSdkVersion", "(", ")", "=").forEach { input = input.replace(it, " ") } return input.trim().substringAfterLast(" ").toIntOrNull() } fun containsCompileSdkVersion(line: String) = when { line.contains("compileSdkVersion") -> line else -> null } fun readAndroidxClassMappings(): List<String> { return this::class.java.getResourceAsStream("/androidx-class-mapping.csv").reader().readLines() } fun findAndroidSupportDependencies(project: Project, artifacts: List<ArtifactMapping>): List<Dependency> { val supportArtifacts = artifacts.map(ArtifactMapping::supportArtifact) val allConfigurations: Set<Configuration> = project.rootProject.allprojects.flatMap { it.configurations }.toSet() return allConfigurations .flatMap { configuration -> configuration.allDependencies .filter { it.artifact in supportArtifacts } }.distinctBy { it.artifact } } val sourceExtensions = listOf("kt", "java", "xml") const val gradleExtension = "gradle" fun File.findSourceFiles(): List<File> { val filesWithExtension = listFiles { file: File -> file.extension in sourceExtensions }?.asList() ?: emptyList() val sourceFiles = listFiles { file: File -> file.isDirectory }?.flatMap { it.findSourceFiles() } ?: emptyList() return filesWithExtension + sourceFiles } fun sourceFiles(moduleDirectories: List<File>): List<File> = moduleDirectories.map { File(it, "src") }.flatMap { it.findSourceFiles() } fun gradleFiles(moduleDirectories: List<File>): List<File> = moduleDirectories.flatMap { it.listFiles { file: File -> file.extension == gradleExtension }?.asIterable() ?: emptyList() } fun supportLibsToAndroidXMappings(androidXClassMapping: List<String>): List<Pair<String, String>> { return androidXClassMapping.asSequence().drop(1) .map { line -> val (supportLibClassName, androidXClassName) = line.split(",").also { check(it.size == 2) } check(supportLibClassName.isLegalClassName()) { "Illegal entry in csv: $supportLibClassName" } check(androidXClassName.isLegalClassName()) { "Illegal entry in csv: $androidXClassName" } supportLibClassName to androidXClassName }.sortedByDescending { (supportLibClassName, _) -> supportLibClassName }.toList() } fun rawSupportLibsToAndroidXPackageMappings( supportLibsToAndroidXMappings: List<Pair<String, String>> ): List<Pair<String, String>> = supportLibsToAndroidXMappings.asSequence().map { (supportLibClassName, androidXClassName) -> supportLibClassName.packageNameFromClassName() to androidXClassName.packageNameFromClassName() }.distinct().toList() fun supportLibsToAndroidXStarImportMappings( rawSupportLibsToAndroidXPackageMappings: List<Pair<String, String>> ): List<Pair<String, String>> = rawSupportLibsToAndroidXPackageMappings.map { (supportLibPackageName, _/*androidXPackageName*/) -> val supportLibStarImport = "import $supportLibPackageName.*" val androidXStarImports = rawSupportLibsToAndroidXPackageMappings.filter { (slpn, _) -> supportLibPackageName == slpn }.joinToString("\n") { (_, axpn) -> "import $axpn.*" } supportLibStarImport to androidXStarImports } fun String.simpleNameFromFullyQualified(): String = substring(indexOfFirst { it.isUpperCase() }) fun String.packageNameFromClassName(): String = substring(0, indexOfFirst { it.isUpperCase() } - 1) fun String.isLegalClassName() = first().isJavaIdentifierStart() && all { it.isJavaIdentifierPart() || it == '.' } val supportedExtensions = sourceExtensions + gradleExtension fun File.migrateToAndroidX(replaces: List<Pair<String, String>>): Boolean { check(extension in supportedExtensions) val sourceCode = readText() var editedSourceCode = sourceCode val migratingMsg = "Migrating file \"$name\" … " print(migratingMsg) replaces.forEach { (supportLibSnippet, androidXSnippet) -> editedSourceCode = editedSourceCode.replace(supportLibSnippet, androidXSnippet) } return if (editedSourceCode == sourceCode) { print("\b".repeat(migratingMsg.length)) false } else { print("overwriting file… ") writeText(editedSourceCode) println(" Done. ✔🆗") // Emojis can be cut off by terminal line breaks, hence the checkmark. true } } fun getArtifactNameToSplittiesConstantMapping(): Map<String, String> { return listOf( AndroidX, Google, JakeWharton, Kotlin, KotlinX, Splitties, Square, Testing ).flatMap { objectInstance -> (objectInstance::class).getArtifactNameToSplittiesConstantMapping(objectInstance::class.simpleName!!) }.toMap() } @OptIn(ExperimentalStdlibApi::class) private fun KClass<*>.getArtifactNameToSplittiesConstantMapping(prefix: String): List<Pair<String, String>> { return nestedClasses.filter { it.visibility == KVisibility.PUBLIC }.flatMap { kClass -> val propertyName = kClass.simpleName!!.let { c -> "${c.first().toLowerCase()}${c.substring(1)}"} kClass.getArtifactNameToSplittiesConstantMapping("$prefix.$propertyName") } + this.memberProperties.filter { it.isConst && it.visibility == KVisibility.PUBLIC && it.returnType == typeOf<String>() }.map { val artifactName = it.javaField!!.get(null).toString().substringBeforeLast(':') val constantName = "$prefix.${it.name}" artifactName to constantName } } }
apache-2.0
7c9e640e48545ef81bded592562b8eda
40.311688
117
0.649874
4.805136
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeObjectToClassFix.kt
5
1678
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject class ChangeObjectToClassFix(element: KtObjectDeclaration) : KotlinQuickFixAction<KtObjectDeclaration>(element) { override fun getText(): String = KotlinBundle.message("fix.change.object.to.class") override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val objectDeclaration = element ?: return val psiFactory = KtPsiFactory(objectDeclaration) objectDeclaration.getObjectKeyword()?.replace(psiFactory.createClassKeyword()) objectDeclaration.replace(psiFactory.createClass(objectDeclaration.text)) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtObjectDeclaration>? { val element = diagnostic.psiElement as? KtConstructor<*> ?: return null val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return null return ChangeObjectToClassFix(containingObject) } } }
apache-2.0
f7059bf9251871478845b208104c9c04
48.352941
158
0.777116
5.115854
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/purchases/GemsPurchaseFragment.kt
1
6608
package com.habitrpg.android.habitica.ui.fragments.purchases import android.content.Intent import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import androidx.core.view.isVisible import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.databinding.FragmentGemPurchaseBinding import com.habitrpg.android.habitica.extensions.addCancelButton import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.PurchaseHandler import com.habitrpg.android.habitica.helpers.PurchaseTypes import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.proxy.CrashlyticsProxy import com.habitrpg.android.habitica.ui.GemPurchaseOptionsView import com.habitrpg.android.habitica.ui.activities.GemPurchaseActivity import com.habitrpg.android.habitica.ui.activities.GiftGemsActivity import com.habitrpg.android.habitica.ui.activities.GiftSubscriptionActivity import com.habitrpg.android.habitica.ui.fragments.BaseFragment import com.habitrpg.android.habitica.ui.helpers.dismissKeyboard import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import io.reactivex.functions.Consumer import javax.inject.Inject class GemsPurchaseFragment : BaseFragment(), GemPurchaseActivity.CheckoutFragment { private lateinit var binding: FragmentGemPurchaseBinding @Inject lateinit var crashlyticsProxy: CrashlyticsProxy @Inject lateinit var userRepository: UserRepository @Inject lateinit var appConfigManager: AppConfigManager private var purchaseHandler: PurchaseHandler? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) binding = FragmentGemPurchaseBinding.inflate(inflater, container, false) return binding.root } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.gems4View?.setOnPurchaseClickListener(View.OnClickListener { purchaseGems(PurchaseTypes.Purchase4Gems) }) binding.gems21View?.setOnPurchaseClickListener(View.OnClickListener { purchaseGems(PurchaseTypes.Purchase21Gems) }) binding.gems42View?.setOnPurchaseClickListener(View.OnClickListener { purchaseGems(PurchaseTypes.Purchase42Gems) }) binding.gems84View?.setOnPurchaseClickListener(View.OnClickListener { purchaseGems(PurchaseTypes.Purchase84Gems) }) val heartDrawable = BitmapDrawable(resources, HabiticaIconsHelper.imageOfHeartLarge()) binding.supportTextView?.setCompoundDrawablesWithIntrinsicBounds(null, null, null, heartDrawable) compositeSubscription.add(userRepository.getUser().subscribe(Consumer { binding.subscriptionPromo.visibility = if (it.isSubscribed) View.GONE else View.VISIBLE }, RxErrorHandler.handleEmptyError())) binding.giftGemsButton?.setOnClickListener { showGiftGemsDialog() } binding.giftSubscriptionContainer?.isVisible = appConfigManager.enableGiftOneGetOne() binding.giftSubscriptionContainer.setOnClickListener { showGiftSubscriptionDialog() } } override fun setupCheckout() { purchaseHandler?.getAllGemSKUs { skus -> for (sku in skus) { updateButtonLabel(sku.id.code, sku.price) } } } override fun setPurchaseHandler(handler: PurchaseHandler?) { this.purchaseHandler = handler } private fun updateButtonLabel(sku: String, price: String) { val matchingView: GemPurchaseOptionsView? = when (sku) { PurchaseTypes.Purchase4Gems -> binding.gems4View PurchaseTypes.Purchase21Gems -> binding.gems21View PurchaseTypes.Purchase42Gems -> binding.gems42View PurchaseTypes.Purchase84Gems -> binding.gems84View else -> return } if (matchingView != null) { matchingView.setPurchaseButtonText(price) matchingView.sku = sku } } private fun purchaseGems(identifier: String) { purchaseHandler?.purchaseGems(identifier) } private fun showGiftGemsDialog() { val chooseRecipientDialogView = this.activity?.layoutInflater?.inflate(R.layout.dialog_choose_message_recipient, null) this.activity?.let { thisActivity -> val alert = HabiticaAlertDialog(thisActivity) alert.setTitle(getString(R.string.gift_title)) alert.addButton(getString(R.string.action_continue), true) { _, _ -> val usernameEditText = chooseRecipientDialogView?.findViewById<View>(R.id.uuidEditText) as? EditText val intent = Intent(thisActivity, GiftGemsActivity::class.java).apply { putExtra("username", usernameEditText?.text.toString()) } startActivity(intent) } alert.addCancelButton { _, _ -> thisActivity.dismissKeyboard() } alert.setAdditionalContentView(chooseRecipientDialogView) alert.show() } } private fun showGiftSubscriptionDialog() { val chooseRecipientDialogView = this.activity?.layoutInflater?.inflate(R.layout.dialog_choose_message_recipient, null) this.activity?.let { thisActivity -> val alert = HabiticaAlertDialog(thisActivity) alert.setTitle(getString(R.string.gift_title)) alert.addButton(getString(R.string.action_continue), true) { _, _ -> val usernameEditText = chooseRecipientDialogView?.findViewById<View>(R.id.uuidEditText) as? EditText val intent = Intent(thisActivity, GiftSubscriptionActivity::class.java).apply { putExtra("username", usernameEditText?.text.toString()) } startActivity(intent) } alert.addCancelButton { _, _ -> thisActivity.dismissKeyboard() } alert.setAdditionalContentView(chooseRecipientDialogView) alert.show() } } }
gpl-3.0
1e8cf5ee2f50b7b7c664c9c40c45f80a
43.952381
126
0.724576
4.938714
false
false
false
false
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/textValidator/ValidatingEditTextPreference.kt
1
3059
package info.nightscout.androidaps.utils.textValidator import android.content.Context import android.util.AttributeSet import androidx.preference.EditTextPreference import androidx.preference.PreferenceViewHolder import info.nightscout.androidaps.core.R class ValidatingEditTextPreference(ctx: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : EditTextPreference(ctx, attrs, defStyleAttr, defStyleRes) { private val validatorParameters: DefaultEditTextValidator.Parameters = obtainValidatorParameters(attrs) private var validator: DefaultEditTextValidator? = null init { setOnBindEditTextListener { editText -> validator = DefaultEditTextValidator(editText, validatorParameters, context) } setOnPreferenceChangeListener { _, _ -> validator?.testValidity(false) ?: true } } constructor(ctx: Context, attrs: AttributeSet, defStyle: Int) : this(ctx, attrs, defStyle, 0) constructor(ctx: Context, attrs: AttributeSet) : this(ctx, attrs, R.attr.editTextPreferenceStyle) override fun onBindViewHolder(holder: PreferenceViewHolder?) { super.onBindViewHolder(holder) holder?.isDividerAllowedAbove = false holder?.isDividerAllowedBelow = false } private fun obtainValidatorParameters(attrs: AttributeSet): DefaultEditTextValidator.Parameters { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.FormEditText, 0, 0) return DefaultEditTextValidator.Parameters( emptyAllowed = typedArray.getBoolean(R.styleable.FormEditText_emptyAllowed, false), testType = typedArray.getInt(R.styleable.FormEditText_testType, EditTextValidator.TEST_NOCHECK), testErrorString = typedArray.getString(R.styleable.FormEditText_testErrorString), classType = typedArray.getString(R.styleable.FormEditText_classType), customRegexp = typedArray.getString(R.styleable.FormEditText_customRegexp), emptyErrorStringDef = typedArray.getString(R.styleable.FormEditText_emptyErrorString), customFormat = typedArray.getString(R.styleable.FormEditText_customFormat)).also { params -> if (params.testType == EditTextValidator.TEST_MIN_LENGTH) params.minLength = typedArray.getInt(R.styleable.FormEditText_minLength, 0) if (params.testType == EditTextValidator.TEST_NUMERIC_RANGE) { params.minNumber = typedArray.getInt(R.styleable.FormEditText_minNumber, Int.MIN_VALUE) params.maxNumber = typedArray.getInt(R.styleable.FormEditText_maxNumber, Int.MAX_VALUE) } if (params.testType == EditTextValidator.TEST_FLOAT_NUMERIC_RANGE) { params.floatminNumber = typedArray.getFloat(R.styleable.FormEditText_floatminNumber, Float.MIN_VALUE) params.floatmaxNumber = typedArray.getFloat(R.styleable.FormEditText_floatmaxNumber, Float.MAX_VALUE) } typedArray.recycle() } } }
agpl-3.0
745f4005a5bf95070ac9769a668797a4
50.847458
117
0.720497
4.824921
false
true
false
false
jwren/intellij-community
platform/execution/src/com/intellij/execution/target/TargetEnvironment.kt
4
6345
// 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.execution.target import com.intellij.execution.ExecutionException import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.nio.file.Path /** * Represents created target environment. It might be local machine, * local or remote Docker container, SSH machine or any other machine * that is able to run processes on it. */ @ApiStatus.Experimental abstract class TargetEnvironment( open val request: TargetEnvironmentRequest ) { sealed class TargetPath { /** * Request for a certain path on the target machine. If the [absolutePath] does not exist, it should be created. */ data class Persistent(val absolutePath: String) : TargetPath() /** * Request for any not used random path. */ class Temporary @JvmOverloads constructor( /** Any string. An environment implementation may reuse previously created directories for the same hint. */ val hint: String? = null, /** Prefix for the randomly generated directory name */ val prefix: String? = null, /** If null, use `/tmp` or something similar, autodetected. */ val parentDirectory: String? = null ) : TargetPath() { override fun toString(): String = "Temporary(hint=$hint, prefix=$prefix, parentDirectory=$parentDirectory)" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Temporary // instance with null hint considered unique thus differs from any other instance if (hint == null) return false if (hint != other.hint) return false if (prefix != other.prefix) return false if (parentDirectory != other.parentDirectory) return false return true } override fun hashCode(): Int { // instance with null hint considered unique if (hint == null) return super.hashCode() var result = hint.hashCode() result = 31 * result + (prefix?.hashCode() ?: 0) result = 31 * result + (parentDirectory?.hashCode() ?: 0) return result } } } data class UploadRoot @JvmOverloads constructor( val localRootPath: Path, val targetRootPath: TargetPath, /** * If true, IDE should try to remove the directory when [shutdown] is being called. * TODO maybe get rid of it? It causes a race between two environments using the same upload root. */ val removeAtShutdown: Boolean = false ) { var volumeData: TargetEnvironmentType.TargetSpecificVolumeData? = null // excluded from equals / hashcode } data class DownloadRoot @JvmOverloads constructor( /** * A certain path on the local machine or null for creating a temporary directory. * The temporary directory should be deleted with [shutdown]. */ val localRootPath: Path?, /** TODO Should [Temprorary] paths with the same hint point on the same directory for uploads and downloads? */ val targetRootPath: TargetPath, /** * If not null, target should try to persist the contents of the folder between the sessions, * and make it available for the next session requests with the same persistentId */ val persistentId: String? = null ) /** Target TCP port forwardings. */ data class TargetPortBinding( val local: Int?, /** There is no robust way to get a random free port inside the Docker target. */ val target: Int ) /** Local TCP port forwardings. */ data class LocalPortBinding( val local: Int, val target: Int? ) interface Volume { val localRoot: Path val targetRoot: String /** * Returns the resulting remote path (even if it's predictable, many tests rely on specific, usually relative paths) * of uploading `"$localRootPath/$relativePath"` to `"$targetRoot/$relativePath"`. * Does not perform any kind of bytes transfer. */ @Throws(IOException::class) fun resolveTargetPath(relativePath: String): String } /** * TODO Do we really need to have two different kinds of bind mounts? * Docker and SSH provides bi-directional access to the target files. */ interface UploadableVolume : Volume { /** * Upload `"$localRootPath/$relativePath"` to `"$targetRoot/$relativePath"` */ @Throws(IOException::class) fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) } interface DownloadableVolume : Volume { @Throws(IOException::class) fun download(relativePath: String, progressIndicator: ProgressIndicator) } open val uploadVolumes: Map<UploadRoot, UploadableVolume> get() = throw UnsupportedOperationException() open val downloadVolumes: Map<DownloadRoot, DownloadableVolume> get() = throw UnsupportedOperationException() /** Values are local ports. */ open val targetPortBindings: Map<TargetPortBinding, Int> get() = throw UnsupportedOperationException() open val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding> get() = throw UnsupportedOperationException() // TODO There are planned further modifications related to this method: // 1. Get rid of any `Promise` in `TargetedCommandLine`. // Likely, there will be a completely new class similar to the `GeneralCommandLine` with adapter from `TargetedCommandLine`. // 2. Call of this method should consume the environment, i.e. there will be no need in the `shutdown` method. // Therefore, to indicate the disposable nature of environments, the method might be moved to the `TargetEnvironmentFactory`. @Throws(ExecutionException::class) abstract fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process abstract val targetPlatform: TargetPlatform //FIXME: document abstract fun shutdown() interface BatchUploader { fun canUploadInBatches(): Boolean @Throws(IOException::class) fun runBatchUpload(uploads: List<Pair<UploadableVolume, String>>, targetProgressIndicator: TargetProgressIndicator) } }
apache-2.0
6f9c97880febbc80fb9aa78d90948b94
34.452514
140
0.6974
4.910991
false
false
false
false
androidx/androidx
graphics/graphics-core/src/androidTest/java/androidx/graphics/opengl/GLTestActivity.kt
3
1548
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.graphics.opengl import android.app.Activity import android.os.Bundle import android.view.SurfaceView import android.view.TextureView import android.widget.LinearLayout class GLTestActivity : Activity() { companion object { const val TARGET_WIDTH = 30 const val TARGET_HEIGHT = 20 } lateinit var surfaceView: SurfaceView lateinit var textureView: TextureView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this) textureView = TextureView(this) val ll = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL weightSum = 2f } val layoutParams = LinearLayout.LayoutParams(TARGET_WIDTH, TARGET_HEIGHT) ll.addView(surfaceView, layoutParams) ll.addView(textureView, layoutParams) setContentView(ll) } }
apache-2.0
1e00ccf1f9cd78715f25e3fc20eecef3
29.98
81
0.713178
4.719512
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/resources/ResourceTasks.kt
3
5875
/* * 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.build.resources import androidx.build.AndroidXImplPlugin.Companion.TASK_GROUP_API import androidx.build.addToBuildOnServer import androidx.build.addToCheckTask import androidx.build.checkapi.ApiLocation import androidx.build.checkapi.getRequiredCompatibilityApiLocation import androidx.build.metalava.UpdateApiTask import androidx.build.uptodatedness.cacheEvenIfNoOutputs import org.gradle.api.Project import java.util.Locale object ResourceTasks { private const val GENERATE_RESOURCE_API_TASK = "generateResourceApi" private const val CHECK_RESOURCE_API_RELEASE_TASK = "checkResourceApiRelease" private const val CHECK_RESOURCE_API_TASK = "checkResourceApi" private const val UPDATE_RESOURCE_API_TASK = "updateResourceApi" fun setupProject( project: Project, variantName: String, builtApiLocation: ApiLocation, outputApiLocations: List<ApiLocation> ) { val packageResTask = project.tasks .named( "package${variantName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.US) else it.toString() }}Resources" ) val builtApiFile = packageResTask.flatMap { task -> (task as com.android.build.gradle.tasks.MergeResources).publicFile } val outputApiFiles = outputApiLocations.map { location -> location.resourceFile } val generateResourceApi = project.tasks.register( GENERATE_RESOURCE_API_TASK, GenerateResourceApiTask::class.java ) { task -> task.group = "API" task.description = "Generates resource API files from source" task.builtApi.set(builtApiFile) task.apiLocation.set(builtApiLocation) } // Policy: If the artifact has previously been released, e.g. has a beta or later API file // checked in, then we must verify "release compatibility" against the work-in-progress // API file. val checkResourceApiRelease = project.getRequiredCompatibilityApiLocation()?.let { lastReleasedApiFile -> project.tasks.register( CHECK_RESOURCE_API_RELEASE_TASK, CheckResourceApiReleaseTask::class.java ) { task -> task.referenceApiFile.set(lastReleasedApiFile.resourceFile) task.apiLocation.set(generateResourceApi.flatMap { it.apiLocation }) // Since apiLocation isn't a File, we have to manually set up the dependency. task.dependsOn(generateResourceApi) task.cacheEvenIfNoOutputs() } } // Policy: All changes to API surfaces for which compatibility is enforced must be // explicitly confirmed by running the updateApi task. To enforce this, the implementation // checks the "work-in-progress" built API file against the checked in current API file. val checkResourceApi = project.tasks.register( CHECK_RESOURCE_API_TASK, CheckResourceApiTask::class.java ) { task -> task.group = TASK_GROUP_API task.description = "Checks that the resource API generated from source matches the " + "checked in resource API file" task.apiLocation.set(generateResourceApi.flatMap { it.apiLocation }) // Since apiLocation isn't a File, we have to manually set up the dependency. task.dependsOn(generateResourceApi) task.cacheEvenIfNoOutputs() task.checkedInApiFiles.set(outputApiFiles) checkResourceApiRelease?.let { task.dependsOn(it) } } val updateResourceApi = project.tasks.register( UPDATE_RESOURCE_API_TASK, UpdateResourceApiTask::class.java ) { task -> task.group = TASK_GROUP_API task.description = "Updates the checked in resource API files to match source code API" task.apiLocation.set(generateResourceApi.flatMap { it.apiLocation }) // Since apiLocation isn't a File, we have to manually set up the dependency. task.dependsOn(generateResourceApi) task.outputApiLocations.set(outputApiLocations) task.forceUpdate.set(project.providers.gradleProperty("force").isPresent) checkResourceApiRelease?.let { // If a developer (accidentally) makes a non-backwards compatible change to an // API, the developer will want to be informed of it as soon as possible. // So, whenever a developer updates an API, if backwards compatibility checks are // enabled in the library, then we want to check that the changes are backwards // compatible task.dependsOn(it) } } // Ensure that this task runs as part of "updateApi" task from MetalavaTasks. project.tasks.withType(UpdateApiTask::class.java).configureEach { task -> task.dependsOn(updateResourceApi) } project.addToCheckTask(checkResourceApi) project.addToBuildOnServer(checkResourceApi) } }
apache-2.0
ad712477ea4ae7eb0389d5957b7b841d
43.847328
99
0.661106
4.749394
false
false
false
false
oldcwj/iPing
app/src/main/java/com/wpapper/iping/ui/helpers/RootHelpers.kt
1
3122
package com.wpapper.iping.ui.helpers import android.text.TextUtils import com.simplemobiletools.commons.extensions.areDigitsOnly import com.simplemobiletools.commons.extensions.showErrorToast import com.simplemobiletools.commons.models.FileDirItem import com.stericson.RootShell.execution.Command import com.stericson.RootTools.RootTools import com.wpapper.iping.ui.folder.SimpleActivity import com.wpapper.iping.ui.utils.exts.config import java.util.* class RootHelpers { fun askRootIFNeeded(activity: SimpleActivity, callback: (success: Boolean) -> Unit) { val command = object : Command(0, "ls -la | awk '{ print $2 }'") { override fun commandOutput(id: Int, line: String) { activity.config.lsHasHardLinksColumn = line.areDigitsOnly() callback(true) super.commandOutput(id, line) } } try { RootTools.getShell(true).add(command) } catch (exception: Exception) { activity.showErrorToast(exception) callback(false) } } fun getFiles(activity: SimpleActivity, path: String, callback: (fileDirItems: ArrayList<FileDirItem>) -> Unit) { val files = ArrayList<FileDirItem>() val showHidden = activity.config.shouldShowHidden val sizeColumnIndex = if (activity.config.lsHasHardLinksColumn) 5 else 4 val cmd = "ls -la $path | awk '{ system(\"echo \"\$1\" \"\$$sizeColumnIndex\" `find ${path.trimEnd('/')}/\"\$NF\" -mindepth 1 -maxdepth 1 | wc -l` \"\$NF\" \")}'" val command = object : Command(0, cmd) { override fun commandOutput(id: Int, line: String) { val parts = line.split(" ") if (parts.size >= 4) { val permissions = parts[0].trim() val isDirectory = permissions.startsWith("d") val isFile = permissions.startsWith("-") val size = if (isFile) parts[1].trim() else "0" val childrenCnt = if (isFile) "0" else parts[2].trim() val filename = TextUtils.join(" ", parts.subList(3, parts.size)).trimStart('/') if ((!showHidden && filename.startsWith(".")) || (!isDirectory && !isFile) || !size.areDigitsOnly() || !childrenCnt.areDigitsOnly()) { super.commandOutput(id, line) return } val fileSize = size.toLong() val filePath = "${path.trimEnd('/')}/$filename" val fileDirItem = FileDirItem(filePath, filename, isDirectory, childrenCnt.toInt(), fileSize) files.add(fileDirItem) } super.commandOutput(id, line) } override fun commandCompleted(id: Int, exitcode: Int) { callback(files) super.commandCompleted(id, exitcode) } } try { RootTools.getShell(true).add(command) } catch (e: Exception) { activity.showErrorToast(e) } } }
gpl-3.0
182188ce56cfcd3ba8987de9bead438a
41.189189
170
0.574952
4.51809
false
true
false
false
Yusspy/Jolt-Sphere
core/src/org/joltsphere/scenes/Scene2.kt
1
2639
package org.joltsphere.scenes import org.joltsphere.main.JoltSphereMain import org.joltsphere.mechanics.WorldEntities import org.joltsphere.mechanics.StreamBeamContactListener import org.joltsphere.mechanics.StreamBeamPlayer import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input.Keys import com.badlogic.gdx.Screen import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer import com.badlogic.gdx.physics.box2d.World class Scene2(internal val game: JoltSphereMain) : Screen { internal var world: World internal var debugRender: Box2DDebugRenderer internal var contLis: StreamBeamContactListener internal var ent: WorldEntities internal var streamBeam: StreamBeamPlayer internal var otherPlayer: StreamBeamPlayer internal var ppm = JoltSphereMain.ppm init { world = World(Vector2(0f, -9.8f), false) //ignore inactive objects false debugRender = Box2DDebugRenderer() ent = WorldEntities() contLis = StreamBeamContactListener() ent.createFlatPlatform(world) ent.createPlatform4(world) world.setContactListener(contLis) streamBeam = StreamBeamPlayer(world, 200f, 200f, Color.RED) otherPlayer = StreamBeamPlayer(world, 1600f, 200f, Color.BLUE) } private fun update(dt: Float) { streamBeam.input(Keys.UP, Keys.DOWN, Keys.LEFT, Keys.RIGHT, Keys.K, Keys.SEMICOLON, Keys.O) otherPlayer.input(Keys.W, Keys.S, Keys.A, Keys.D, Keys.F, Keys.H, Keys.T) } override fun render(dt: Float) { update(dt) Gdx.gl.glClearColor(0f, 0f, 0f, 1f) Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) world.step(dt, 6, 2) streamBeam.update(dt, 1) otherPlayer.update(dt, 1) game.shapeRender.begin(ShapeType.Filled) streamBeam.shapeRender(game.shapeRender) otherPlayer.shapeRender(game.shapeRender) game.shapeRender.end() debugRender.render(world, game.phys2DCam.combined) game.batch.begin() game.font.draw(game.batch, "" + Gdx.graphics.framesPerSecond, game.width * 0.27f, game.height * 0.85f) game.batch.end() game.cam.update() game.phys2DCam.update() } override fun dispose() { } override fun resize(width: Int, height: Int) { game.resize(width, height) } override fun show() {} override fun pause() {} override fun resume() {} override fun hide() {} }
agpl-3.0
8f6f40d779ff68a4c1cbabaa35ef7c8c
25.4
110
0.694581
3.605191
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/BodyWaterMassRecord.kt
3
2356
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Mass import androidx.health.connect.client.units.kilograms import java.time.Instant import java.time.ZoneOffset /** * Captures the user's body water mass. Each record represents a single instantaneous measurement. */ public class BodyWaterMassRecord( override val time: Instant, override val zoneOffset: ZoneOffset?, /** Mass in [Mass] unit. Required field. Valid range: 0-1000 kilograms. */ public val mass: Mass, override val metadata: Metadata = Metadata.EMPTY, ) : InstantaneousRecord { init { mass.requireNotLess(other = mass.zero(), name = "mass") mass.requireNotMore(other = MAX_BODY_WATER_MASS, name = "mass") } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is BodyWaterMassRecord) return false if (mass != other.mass) return false if (time != other.time) return false if (zoneOffset != other.zoneOffset) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = mass.hashCode() result = 31 * result + time.hashCode() result = 31 * result + (zoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } private companion object { private val MAX_BODY_WATER_MASS = 1000.kilograms } }
apache-2.0
a0e7324b2668934b87ae5f629bc9db96
33.144928
98
0.675297
4.245045
false
false
false
false
GunoH/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/api/page/GraphQLPagesLoader.kt
2
1135
// 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.collaboration.api.page import com.intellij.collaboration.api.data.GraphQLRequestPagination import com.intellij.collaboration.api.dto.GraphQLPagedResponseDataDTO class GraphQLPagesLoader<EntityDTO>( private val pageLoader: suspend (GraphQLRequestPagination) -> GraphQLPagedResponseDataDTO<EntityDTO>? ) { suspend fun loadAll(): List<EntityDTO> { val firstResponse = pageLoader(GraphQLRequestPagination.DEFAULT) ?: return emptyList() val loadedData = firstResponse.nodes.toMutableList() var pageInfo = firstResponse.pageInfo while (pageInfo.hasNextPage) { val page = GraphQLRequestPagination(pageInfo.endCursor) val response = pageLoader(page) ?: break loadedData.addAll(response.nodes) pageInfo = response.pageInfo } return loadedData } companion object { fun arguments(pagination: GraphQLRequestPagination): Map<String, Any?> = mapOf( "pageSize" to pagination.pageSize, "cursor" to pagination.afterCursor ) } }
apache-2.0
282ba33e70652b63f2ba2d4d8bedc5a4
35.645161
120
0.755947
4.670782
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/GradleScriptListener.kt
3
3687
// 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.gradleJava.scripting import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener.Companion.installAsyncVirtualFileListener import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileEvent import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangeListener import org.jetbrains.kotlin.idea.gradleJava.scripting.legacy.GradleLegacyScriptListener import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager class GradleScriptListener(project: Project) : ScriptChangeListener(project) { // todo(gradle6): remove private val legacy = GradleLegacyScriptListener(project) private val buildRootsManager: GradleBuildRootsManager get() = GradleBuildRootsManager.getInstance(project) ?: error("GradleBuildRootsManager not found") init { // listen changes using VFS events, including gradle-configuration related files val listener = GradleScriptFileChangeListener(this, buildRootsManager) installAsyncVirtualFileListener(listener, KotlinPluginDisposable.getInstance(project)) } // cache buildRootsManager service for hot path under vfs changes listener val fileChangesProcessor: (filePath: String, ts: Long) -> Unit get() { val buildRootsManager = buildRootsManager return { filePath, ts -> buildRootsManager.fileChanged(filePath, ts) } } fun fileChanged(filePath: String, ts: Long) = fileChangesProcessor(filePath, ts) override fun isApplicable(vFile: VirtualFile) = // todo(gradle6): replace with `isCustomScriptingSupport(vFile)` legacy.isApplicable(vFile) private fun isCustomScriptingSupport(vFile: VirtualFile) = buildRootsManager.isApplicable(vFile) override fun editorActivated(vFile: VirtualFile) { if (isCustomScriptingSupport(vFile)) { buildRootsManager.updateNotifications(restartAnalyzer = false) { it == vFile.path } } else { legacy.editorActivated(vFile) } } override fun documentChanged(vFile: VirtualFile) { fileChanged(vFile.path, System.currentTimeMillis()) if (!isCustomScriptingSupport(vFile)) { legacy.documentChanged(vFile) } } } private class GradleScriptFileChangeListener( private val watcher: GradleScriptListener, private val buildRootsManager: GradleBuildRootsManager ) : VirtualFileChangesListener { val changedFiles = mutableListOf<String>() override fun init() { changedFiles.clear() } override fun isRelevant(file: VirtualFile, event: VFileEvent): Boolean { return buildRootsManager.maybeAffectedGradleProjectFile(file.path) } override fun updateFile(file: VirtualFile, event: VFileEvent) { changedFiles.add(event.path) } override fun apply() { val fileChangesProcessor = watcher.fileChangesProcessor changedFiles.forEach { LocalFileSystem.getInstance().findFileByPath(it)?.let { f -> watcher.fileChanged(f.path, f.timeStamp) fileChangesProcessor(f.path, f.timeStamp) } } } }
apache-2.0
0a17fdc3c049f9dbc59d9b2fa78032b0
39.086957
158
0.731489
4.955645
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.kt
2
4065
// 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.codeInsight.documentation.actions import com.intellij.codeInsight.documentation.DocumentationManager import com.intellij.codeInsight.documentation.QuickDocUtil.isDocumentationV2Enabled import com.intellij.codeInsight.hint.HintManagerImpl.ActionToIgnore import com.intellij.codeInsight.lookup.LookupManager import com.intellij.featureStatistics.FeatureUsageTracker import com.intellij.lang.documentation.ide.actions.DOCUMENTATION_TARGETS import com.intellij.lang.documentation.ide.impl.DocumentationManager.Companion.instance import com.intellij.openapi.actionSystem.* import com.intellij.openapi.editor.EditorGutter import com.intellij.openapi.project.DumbAware import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.PsiUtilBase open class ShowQuickDocInfoAction : AnAction(), ActionToIgnore, DumbAware, PopupAction, PerformWithDocumentsCommitted { init { isEnabledInModalContext = true @Suppress("LeakingThis") setInjectedContext(true) } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { if (isDocumentationV2Enabled()) { e.presentation.isEnabled = e.dataContext.getData(DOCUMENTATION_TARGETS)?.isNotEmpty() ?: false return } val presentation = e.presentation val dataContext = e.dataContext presentation.isEnabled = false val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(dataContext) val element = CommonDataKeys.PSI_ELEMENT.getData(dataContext) if (editor == null && element == null) return if (LookupManager.getInstance(project).activeLookup != null) { presentation.isEnabled = true } else { if (editor != null) { if (e.getData(EditorGutter.KEY) != null) return val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) if (file == null && element == null) return } presentation.isEnabled = true } } override fun actionPerformed(e: AnActionEvent) { if (isDocumentationV2Enabled()) { actionPerformedV2(e.dataContext) return } val dataContext = e.dataContext val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(dataContext) if (editor != null) { val activeLookup = LookupManager.getActiveLookup(editor) if (activeLookup != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_LOOKUP_FEATURE) } val psiFile = PsiUtilBase.getPsiFileInEditor(editor, project) ?: return val documentationManager = DocumentationManager.getInstance(project) val hint = documentationManager.docInfoHint documentationManager.showJavaDocInfo(editor, psiFile, hint != null || activeLookup == null) return } val element = CommonDataKeys.PSI_ELEMENT.getData(dataContext) if (element != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE) val documentationManager = DocumentationManager.getInstance(project) val hint = documentationManager.docInfoHint documentationManager.showJavaDocInfo(element, null, hint != null, null) } } private fun actionPerformedV2(dataContext: DataContext) { val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return instance(project).actionPerformed(dataContext) } @Suppress("SpellCheckingInspection") companion object { const val CODEASSISTS_QUICKJAVADOC_FEATURE = "codeassists.quickjavadoc" const val CODEASSISTS_QUICKJAVADOC_LOOKUP_FEATURE = "codeassists.quickjavadoc.lookup" const val CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE = "codeassists.quickjavadoc.ctrln" } }
apache-2.0
f620ea73927d7653a6bdddfe0e8742a5
41.34375
120
0.731857
4.748832
false
false
false
false
GunoH/intellij-community
java/execution/impl/src/com/intellij/execution/vmOptions/VMOptionsServiceImpl.kt
1
2825
// 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.execution.vmOptions import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessRunner import com.intellij.execution.process.OSProcessHandler import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.containers.CollectionFactory import java.io.File import java.nio.file.Path import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentMap class VMOptionsServiceImpl : VMOptionsService { companion object { private val ourData: ConcurrentMap<String, CompletableFuture<JdkOptionsData>> = CollectionFactory.createConcurrentSoftValueMap() } override fun getOrComputeOptionsForJdk(javaHome: String): CompletableFuture<JdkOptionsData> { val future = ourData.computeIfAbsent(javaHome) { CompletableFuture.supplyAsync { computeOptionsData(it) } } if (future.isDone) { // sometimes the timeout may appear and in order not to block the possibility to get the completion afterwards, it is better to retry val data = future.get() if (data == null) { ourData.remove(javaHome) } } return future } // when null is returned, it was a timeout private fun computeOptionsData(javaHome: String): JdkOptionsData? { return JdkOptionsData(getOptionsForJdk(javaHome) ?: return null) } private fun getOptionsForJdk(javaHome: String): List<VMOption>? { val vmPath = getVmPath(javaHome) val generalCommandLine = GeneralCommandLine(vmPath) generalCommandLine.addParameters("-XX:+PrintFlagsFinal", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", "-X") val runner = CapturingProcessRunner(OSProcessHandler(generalCommandLine)) val output = runner.runProcess(1000) if (output.isTimeout) { return null } val xxOptions = VMOptionsParser.parseXXOptions(output.stdout) val xOptions = VMOptionsParser.parseXOptions(output.stderr) if (xOptions != null) { return xOptions + xxOptions } return xxOptions } private fun getVmPath(javaHome: String): String { val vmExeName = if (SystemInfo.isWindows) "java.exe" else "java" // do not use JavaW.exe because of issues with encoding return Path.of(getConvertedPath(javaHome), "bin", vmExeName).toString() } private fun getConvertedPath(javaHome: String): String { // it is copied from com.intellij.openapi.projectRoots.impl.JavaSdkImpl.getConvertedHomePath var systemDependentName = FileUtil.toSystemDependentName(javaHome) if (javaHome.endsWith(File.separator)) { systemDependentName += File.separator } return systemDependentName } }
apache-2.0
145aedd747fd30629daa701d42c23847
41.179104
139
0.761062
4.441824
false
false
false
false
GunoH/intellij-community
plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/GitLabApi.kt
2
2161
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.api import com.intellij.collaboration.api.HttpApiHelper import com.intellij.collaboration.api.graphql.GraphQLApiHelper import com.intellij.collaboration.api.httpclient.AuthorizationConfigurer import com.intellij.collaboration.api.httpclient.CommonHeadersConfigurer import com.intellij.collaboration.api.httpclient.CompoundRequestConfigurer import com.intellij.collaboration.api.httpclient.RequestTimeoutConfigurer import com.intellij.collaboration.api.json.JsonHttpApiHelper import com.intellij.openapi.diagnostic.logger import com.intellij.util.io.HttpSecurityUtil class GitLabApi private constructor(httpHelper: HttpApiHelper) : HttpApiHelper by httpHelper, JsonHttpApiHelper by JsonHttpApiHelper(logger<GitLabApi>(), httpHelper, GitLabRestJsonDataDeSerializer, GitLabRestJsonDataDeSerializer), GraphQLApiHelper by GraphQLApiHelper(logger<GitLabApi>(), httpHelper, GitLabGQLQueryLoader, GitLabGQLDataDeSerializer, GitLabGQLDataDeSerializer) { constructor(tokenSupplier: () -> String) : this(httpHelper(tokenSupplier)) companion object { private fun httpHelper(tokenSupplier: () -> String): HttpApiHelper { val authConfigurer = object : AuthorizationConfigurer() { override val authorizationHeaderValue: String get() = HttpSecurityUtil.createBearerAuthHeaderValue(tokenSupplier()) } val requestConfigurer = CompoundRequestConfigurer(RequestTimeoutConfigurer(), CommonHeadersConfigurer(), authConfigurer) return HttpApiHelper(logger = logger<GitLabApi>(), requestConfigurer = requestConfigurer) } } }
apache-2.0
5814cc82f5594ec27e7cd96bac6e0c2b
50.47619
120
0.652476
5.856369
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinFunctionParametersFixer.kt
4
1588
// 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.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.psi.KtNamedFunction import kotlin.math.max class KotlinFunctionParametersFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) { if (psiElement !is KtNamedFunction) return val parameterList = psiElement.valueParameterList if (parameterList == null) { val identifier = psiElement.nameIdentifier ?: return // Insert () after name or after type parameters list when it placed after name val offset = max(identifier.range.end, psiElement.typeParameterList?.range?.end ?: psiElement.range.start) editor.document.insertString(offset, "()") processor.registerUnresolvedError(offset + 1) } else { val rParen = parameterList.lastChild ?: return if (")" != rParen.text) { val params = parameterList.parameters val offset = if (params.isEmpty()) parameterList.range.start + 1 else params.last().range.end editor.document.insertString(offset, ")") } } } }
apache-2.0
8cde66778f6063cb0e221d23aeb658cc
44.371429
158
0.701511
4.993711
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/CollapsibleRowImpl.kt
1
2784
// 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.ui.dsl.builder.impl import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.NlsContexts import com.intellij.ui.Expandable import com.intellij.ui.dsl.builder.CollapsibleRow import com.intellij.ui.dsl.builder.DslComponentProperty import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.RowLayout import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import org.jetbrains.annotations.ApiStatus import javax.swing.border.EmptyBorder @ApiStatus.Internal internal class CollapsibleRowImpl(dialogPanelConfig: DialogPanelConfig, panelContext: PanelContext, parent: PanelImpl, @NlsContexts.BorderTitle title: String, init: Panel.() -> Unit) : RowImpl(dialogPanelConfig, panelContext, parent, RowLayout.INDEPENDENT), CollapsibleRow { private val collapsibleTitledSeparator = CollapsibleTitledSeparator(title) override var expanded by collapsibleTitledSeparator::expanded override fun setText(@NlsContexts.Separator text: String) { collapsibleTitledSeparator.text = text } override fun addExpandedListener(action: (Boolean) -> Unit) { collapsibleTitledSeparator.expandedProperty.afterChange { action(it) } } init { collapsibleTitledSeparator.setLabelFocusable(true) (collapsibleTitledSeparator.label.border as? EmptyBorder)?.borderInsets?.let { collapsibleTitledSeparator.putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps(top = it.top, left = it.left, bottom = it.bottom)) } collapsibleTitledSeparator.label.putClientProperty(Expandable::class.java, object : Expandable { override fun expand() { expanded = true } override fun collapse() { expanded = false } override fun isExpanded(): Boolean { return expanded } }) val action = DumbAwareAction.create { expanded = !expanded } action.registerCustomShortcutSet(ActionUtil.getShortcutSet("CollapsiblePanel-toggle"), collapsibleTitledSeparator.label) val collapsibleTitledSeparator = this.collapsibleTitledSeparator panel { row { cell(collapsibleTitledSeparator).horizontalAlign(HorizontalAlign.FILL) } val expandablePanel = panel { init() } collapsibleTitledSeparator.onAction { expandablePanel.visible(it) } } } }
apache-2.0
eb9ea45ef18a4a1e1e87851524c7dc63
37.666667
158
0.710129
5.136531
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/GroupNode.kt
1
1923
// 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.ide.bookmark.ui.tree import com.intellij.icons.AllIcons import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkBundle.message import com.intellij.ide.bookmark.BookmarkGroup import com.intellij.ide.bookmark.BookmarkProvider import com.intellij.ide.bookmark.LineBookmark import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.ide.util.treeView.AbstractTreeNodeCache import com.intellij.openapi.project.Project import com.intellij.ui.SimpleTextAttributes internal class GroupNode(project: Project, group: BookmarkGroup) : AbstractTreeNode<BookmarkGroup>(project, group) { private val cache = AbstractTreeNodeCache<Bookmark, AbstractTreeNode<*>>(this) { it.createNode() } override fun getChildren(): List<AbstractTreeNode<*>> { var bookmarks = value.getBookmarks() // shows line bookmarks only in the popup if (parentRootNode?.value?.isPopup == true) { bookmarks = bookmarks.filterIsInstance<LineBookmark>() } // reuse cached nodes var nodes = cache.getNodes(bookmarks).onEach { if (it is BookmarkNode) it.bookmarkGroup = value } BookmarkProvider.EP.getExtensions(project).sortedByDescending { it.weight }.forEach { nodes = it.prepareGroup(nodes) } return nodes } override fun update(presentation: PresentationData) { presentation.presentableText = value.name // configure speed search presentation.setIcon(AllIcons.Nodes.BookmarkGroup) if (value.isDefault) { presentation.addText("${presentation.presentableText} ", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) presentation.addText(message("default.group.marker"), SimpleTextAttributes.GRAYED_ATTRIBUTES) } } }
apache-2.0
54d5088343c967dd5669196c472b95c9
45.902439
158
0.780031
4.524706
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/pof/POFAdventureVitalStatsFragment.kt
1
2511
package pt.joaomneto.titancompanion.adventure.impl.fragments.pof import android.app.AlertDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.TextView import kotlinx.android.synthetic.main.fragment_28pof_adventure_vitalstats.* import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.impl.POFAdventure import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureVitalStatsFragment class POFAdventureVitalStatsFragment : AdventureVitalStatsFragment() { private var powerValue: TextView? = null private var increasePowerButton: Button? = null private var decreasePowerButton: Button? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreate(savedInstanceState) val rootView = inflater.inflate( R.layout.fragment_28pof_adventure_vitalstats, container, false ) // CHECKTHIS initialize(rootView); decreasePowerButton = rootView .findViewById(R.id.minusPowerButton) increasePowerButton = rootView .findViewById(R.id.plusPowerButton) powerValue = rootView.findViewById(R.id.statsPowerValue) val adv = activity as POFAdventure powerValue!!.setOnClickListener { val alert = createAlertForInitialStatModification(R.string.setInitialPower) { dialog, _ -> val input = (dialog as AlertDialog).findViewById<EditText>(R.id.alert_editText_field) val value = Integer.parseInt(input.text.toString()) adv.initialPower = value } alert.show() } decreasePowerButton!!.setOnClickListener { if (adv.currentPower > 0) adv.currentPower = adv.currentPower - 1 refreshScreensFromResume() } increasePowerButton!!.setOnClickListener { if (adv.currentPower < adv.initialPower) adv.currentPower = adv.currentPower + 1 refreshScreensFromResume() } refreshScreensFromResume() return rootView } override fun refreshScreensFromResume() { super.refreshScreensFromResume() val adv = activity as POFAdventure powerValue?.text = adv.currentPower.toString() } }
lgpl-3.0
d8354b516e9d633c185e75e602c46ca6
31.61039
102
0.686977
4.866279
false
false
false
false
h0tk3y/better-parse
src/commonMain/kotlin/com/github/h0tk3y/betterParse/lexer/TokenMatchesSequence.kt
1
2075
package com.github.h0tk3y.betterParse.lexer /** Stateful producer of tokens that yields [Token]s from some inputs sequence that it is based upon, one by one */ public interface TokenProducer { public fun nextToken(): TokenMatch? } public class TokenMatchesSequence( private val tokenProducer: TokenProducer, private val matches: ArrayList<TokenMatch> = arrayListOf() ) : Sequence<TokenMatch> { private inline fun ensureReadPosition(position: Int): Boolean { while (position >= matches.size) { val next = tokenProducer.nextToken() ?: return false matches.add(next) } return true } public operator fun get(position: Int): TokenMatch? { if (!ensureReadPosition(position)) { return null } return matches[position] } public fun getNotIgnored(position: Int): TokenMatch? { if (!ensureReadPosition(position)) { return null } var pos = position while (true) { val value = if (pos < matches.size) matches[pos] else { val next = tokenProducer.nextToken() if (next == null) return null else { matches.add(next) next } } if (!value.type.ignored) return value pos++ } } override fun iterator(): Iterator<TokenMatch> = object : AbstractIterator<TokenMatch>() { var position = 0 var noneMatchedAtThisPosition = false override fun computeNext() { if (noneMatchedAtThisPosition) { done() } val nextMatch = get(position) ?: run { done(); return } setNext(nextMatch) if (nextMatch.type == noneMatched) { noneMatchedAtThisPosition = true } ++position } } }
apache-2.0
582c11eae5b91ea544a14c052469cdc0
27.819444
115
0.520482
5.110837
false
false
false
false
marktony/ZhiHuDaily
app/src/main/java/com/marktony/zhihudaily/data/source/remote/GuokrHandpickNewsRemoteDataSource.kt
1
5046
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.data.source.remote import android.support.annotation.VisibleForTesting import com.marktony.zhihudaily.BuildConfig import com.marktony.zhihudaily.data.GuokrHandpickNews import com.marktony.zhihudaily.data.GuokrHandpickNewsResult import com.marktony.zhihudaily.data.source.RemoteDataNotFoundException import com.marktony.zhihudaily.data.source.Result import com.marktony.zhihudaily.data.source.datasource.GuokrHandpickDataSource import com.marktony.zhihudaily.retrofit.RetrofitService import com.marktony.zhihudaily.util.AppExecutors import kotlinx.coroutines.experimental.withContext import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Created by lizhaotailang on 2017/5/24. * * * Implementation of the [GuokrHandpickNews] data source that accesses network. */ class GuokrHandpickNewsRemoteDataSource private constructor(private val mAppExecutors: AppExecutors) : GuokrHandpickDataSource { private val mGuokrHandpickService: RetrofitService.GuokrHandpickService by lazy { val httpClientBuilder = OkHttpClient.Builder() if (BuildConfig.DEBUG) { httpClientBuilder.addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) } httpClientBuilder.retryOnConnectionFailure(true) val retrofit = Retrofit.Builder() .baseUrl(RetrofitService.GUOKR_HANDPICK_BASE) .addConverterFactory(GsonConverterFactory.create()) .client(httpClientBuilder.build()) .build() retrofit.create(RetrofitService.GuokrHandpickService::class.java) } companion object { private var INSTANCE: GuokrHandpickNewsRemoteDataSource? = null @JvmStatic fun getInstance(appExecutors: AppExecutors): GuokrHandpickNewsRemoteDataSource { if (INSTANCE == null) { synchronized(GuokrHandpickNewsRemoteDataSource::javaClass) { INSTANCE = GuokrHandpickNewsRemoteDataSource(appExecutors) } } return INSTANCE!! } @VisibleForTesting fun clearInstance() { INSTANCE = null } } override suspend fun getGuokrHandpickNews(forceUpdate: Boolean, clearCache: Boolean, offset: Int, limit: Int): Result<List<GuokrHandpickNewsResult>> = withContext(mAppExecutors.ioContext) { try { val response = mGuokrHandpickService.getGuokrHandpick(offset, limit).execute() if (response.isSuccessful) { response.body()?.let { if (it.result.isNotEmpty()) { Result.Success(it.result) } else { Result.Error(RemoteDataNotFoundException()) } } ?: run { Result.Error(RemoteDataNotFoundException()) } } else { Result.Error(RemoteDataNotFoundException()) } } catch (e: Exception) { Result.Error(RemoteDataNotFoundException()) } } // Not required because the [com.marktony.zhihudaily.data.source.repository.GuokrHandpickNewsRepository] handles the logic of refreshing the // news from all the available data sources. override suspend fun getFavorites(): Result<List<GuokrHandpickNewsResult>> = Result.Error(RemoteDataNotFoundException()) // Not required because the [com.marktony.zhihudaily.data.source.repository.GuokrHandpickNewsRepository] handles the logic of refreshing the // news from all the available data sources. override suspend fun getItem(itemId: Int): Result<GuokrHandpickNewsResult> = Result.Error(RemoteDataNotFoundException()) override suspend fun favoriteItem(itemId: Int, favorite: Boolean) { // Not required because the [com.marktony.zhihudaily.data.source.repository.GuokrHandpickNewsRepository] handles the logic of refreshing the // news from all the available data sources. } override suspend fun saveAll(list: List<GuokrHandpickNewsResult>) { // Not required because the [com.marktony.zhihudaily.data.source.repository.GuokrHandpickNewsRepository] handles the logic of refreshing the // news from all the available data sources. } }
apache-2.0
d4516df7866edf843caceb82cf69ab4a
39.693548
193
0.701744
5.345339
false
false
false
false
Duke1/UnrealMedia
UnrealMedia/app/src/main/java/com/qfleng/um/view/VectorView.kt
1
5685
package com.qfleng.um.view import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.graphics.PointF import android.util.AttributeSet import android.view.View /** * Created by Duke */ class VectorView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr), View.OnClickListener { private val mPaint = Paint() private var mCenterX: Int = 0 private var mCenterY: Int = 0 private val mCenter = PointF(0f, 0f) private val mCircleRadius = 200f // 圆的半径 private val mDifference = mCircleRadius * C // 圆形的控制点与数据点的差值 private val mData = FloatArray(8) // 顺时针记录绘制圆形的四个数据点 private val mCtrl = FloatArray(16) // 顺时针记录绘制圆形的八个控制点 private val mDuration = 1000f // 变化总时长 private var mCurrent = 0f // 当前已进行时长 private val mCount = 100f // 将时长总共划分多少份 private val mPiece = mDuration / mCount // 每一份的时长 init { mPaint.color = Color.BLACK mPaint.strokeWidth = 8f mPaint.style = Paint.Style.STROKE mPaint.textSize = 60f mPaint.isAntiAlias = true // 初始化数据点 mData[0] = 0f mData[1] = mCircleRadius mData[2] = mCircleRadius mData[3] = 0f mData[4] = 0f mData[5] = -mCircleRadius mData[6] = -mCircleRadius mData[7] = 0f // 初始化控制点 mCtrl[0] = mData[0] + mDifference mCtrl[1] = mData[1] mCtrl[2] = mData[2] mCtrl[3] = mData[3] + mDifference mCtrl[4] = mData[2] mCtrl[5] = mData[3] - mDifference mCtrl[6] = mData[4] + mDifference mCtrl[7] = mData[5] mCtrl[8] = mData[4] - mDifference mCtrl[9] = mData[5] mCtrl[10] = mData[6] mCtrl[11] = mData[7] - mDifference mCtrl[12] = mData[6] mCtrl[13] = mData[7] + mDifference mCtrl[14] = mData[0] - mDifference mCtrl[15] = mData[1] setOnClickListener(this) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) mCenterX = w / 2 mCenterY = h / 2 } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) drawCoordinateSystem(canvas) // 绘制坐标系 canvas.translate(mCenterX.toFloat(), mCenterY.toFloat()) // 将坐标系移动到画布中央 canvas.scale(1f, -1f) // 翻转Y轴 drawAuxiliaryLine(canvas) // 绘制贝塞尔曲线 mPaint.color = Color.RED mPaint.strokeWidth = 8f val path = Path() path.moveTo(mData[0], mData[1]) path.cubicTo(mCtrl[0], mCtrl[1], mCtrl[2], mCtrl[3], mData[2], mData[3]) path.cubicTo(mCtrl[4], mCtrl[5], mCtrl[6], mCtrl[7], mData[4], mData[5]) path.cubicTo(mCtrl[8], mCtrl[9], mCtrl[10], mCtrl[11], mData[6], mData[7]) path.cubicTo(mCtrl[12], mCtrl[13], mCtrl[14], mCtrl[15], mData[0], mData[1]) canvas.drawPath(path, mPaint) mCurrent += mPiece if (mCurrent < mDuration) { // mData[1] -= 120 / mCount; // mCtrl[7] += 80 / mCount; // mCtrl[9] += 80 / mCount; // // mCtrl[4] -= 20 / mCount; // mCtrl[10] += 20 / mCount; postInvalidateDelayed(mPiece.toLong()) } } // 绘制辅助线 private fun drawAuxiliaryLine(canvas: Canvas) { // 绘制数据点和控制点 mPaint.color = Color.GRAY mPaint.strokeWidth = 20f run { var i = 0 while (i < 8) { canvas.drawPoint(mData[i], mData[i + 1], mPaint) i += 2 } } run { var i = 0 while (i < 16) { canvas.drawPoint(mCtrl[i], mCtrl[i + 1], mPaint) i += 2 } } // 绘制辅助线 mPaint.strokeWidth = 4f var i = 2 var j = 2 while (i < 8) { canvas.drawLine(mData[i], mData[i + 1], mCtrl[j], mCtrl[j + 1], mPaint) canvas.drawLine(mData[i], mData[i + 1], mCtrl[j + 2], mCtrl[j + 3], mPaint) i += 2 j += 4 } canvas.drawLine(mData[0], mData[1], mCtrl[0], mCtrl[1], mPaint) canvas.drawLine(mData[0], mData[1], mCtrl[14], mCtrl[15], mPaint) } // 绘制坐标系 private fun drawCoordinateSystem(canvas: Canvas) { canvas.save() // 绘制做坐标系 canvas.translate(mCenterX.toFloat(), mCenterY.toFloat()) // 将坐标系移动到画布中央 canvas.scale(1f, -1f) // 翻转Y轴 val fuzhuPaint = Paint() fuzhuPaint.color = Color.RED fuzhuPaint.strokeWidth = 5f fuzhuPaint.style = Paint.Style.STROKE canvas.drawLine(0f, -2000f, 0f, 2000f, fuzhuPaint) canvas.drawLine(-2000f, 0f, 2000f, 0f, fuzhuPaint) canvas.restore() } override fun onClick(v: View) { } companion object { const val C = 0.551915024494f // 一个常量,用来计算绘制圆形贝塞尔曲线控制点的位置 } }
mit
68d5249ab8a55773a9a551d21b57f81f
25.748744
173
0.530904
3.403453
false
false
false
false
ethauvin/kobalt-property-file
example/kobalt/src/Build.kt
1
2703
import com.beust.kobalt.* import com.beust.kobalt.plugin.packaging.* import com.beust.kobalt.plugin.application.* import com.beust.kobalt.plugin.kotlin.* import net.thauvin.erik.kobalt.plugin.propertyfile.* // ./kobaltw propertyFile antExamples val bs = buildScript { repos(localMaven()) plugins("net.thauvin.erik:kobalt-property-file:0.9.1") } val p = project { name = "example" group = "com.example" artifactId = name version = "0.1" dependencies { } dependenciesTest { compile("org.testng:testng:6.13.1") } assemble { jar { } } application { mainClass = "com.example.MainKt" } propertyFile { // parameters file = "version.properties" comment = "##Generated file - do not modify!" //failOnWarning = true entry(key = "version.fail", value = "a", type = Types.INT) // Version properties with patch increment entry(key = "version.major", value = "1") entry(key = "version.minor", value = "0") entry(key = "version.patch", value = "1", default = "-1", type = Types.INT, operation = Operations.ADD) entry(key = "version.date", value = "now", type = Types.DATE) // ISO8601 date entry(key = "version.dateISO", value = "now", type = Types.DATE, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") // Set date to now, then add a month entry(key = "date.nextMonth", value = "now", type = Types.DATE) entry(key = "date.nextMonth", value = "0", type = Types.DATE, unit = Units.MONTH, operation = Operations.ADD) } propertyFile { // task name taskName = "antExamples" // dependencies dependsOn = listOf("run") // parameters file = "version.properties" // Examples from: https://ant.apache.org/manual/Tasks/propertyfile.html entry(key = "akey", value = "avalue") entry(key = "adate", type = Types.DATE, value = "now") entry(key = "anint", type = Types.INT, default = "0", operation = Operations.ADD) entry(key = "formated.int", type = Types.INT, default = "0013", operation = Operations.ADD, pattern = "0000") entry(key = "formated.date", type = Types.DATE, value = "now", pattern = "DDD HH:mm") entry(key = "formated.date-1", type = Types.DATE, default = "now", pattern = "DDD", operation = Operations.SUBTRACT, value = "1") entry(key = "formated.tomorrow", type = Types.DATE, default = "now", pattern = "DDD", operation = Operations.ADD, value = "1") entry(key = "progress", default = "", operation = Operations.ADD, value = ".") } }
bsd-3-clause
08b66780f700b608cc85b440ae8e3cfc
33.21519
117
0.591195
3.677551
false
false
false
false
seventhroot/elysium
bukkit/rpk-banks-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/bank/RPKBankProviderImpl.kt
1
2788
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.banks.bukkit.bank import com.rpkit.banks.bukkit.RPKBanksBukkit import com.rpkit.banks.bukkit.database.table.RPKBankTable import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.economy.bukkit.currency.RPKCurrency import com.rpkit.economy.bukkit.economy.RPKEconomyProvider import com.rpkit.economy.bukkit.exception.NegativeBalanceException /** * Bank provider implementation. */ class RPKBankProviderImpl(private val plugin: RPKBanksBukkit): RPKBankProvider { override fun getBalance(character: RPKCharacter, currency: RPKCurrency): Int { return plugin.core.database.getTable(RPKBankTable::class).get(character, currency).balance } override fun setBalance(character: RPKCharacter, currency: RPKCurrency, amount: Int) { if (amount < 0) throw NegativeBalanceException() val bank = plugin.core.database.getTable(RPKBankTable::class).get(character, currency) bank.balance = amount plugin.core.database.getTable(RPKBankTable::class).update(bank) } override fun deposit(character: RPKCharacter, currency: RPKCurrency, amount: Int) { val economyProvider = plugin.core.serviceManager.getServiceProvider(RPKEconomyProvider::class) if (economyProvider.getBalance(character, currency) >= amount) { economyProvider.setBalance(character, currency, economyProvider.getBalance(character, currency) - amount) setBalance(character, currency, getBalance(character, currency) + amount) } } override fun withdraw(character: RPKCharacter, currency: RPKCurrency, amount: Int) { val economyProvider = plugin.core.serviceManager.getServiceProvider(RPKEconomyProvider::class) if (getBalance(character, currency) >= amount) { economyProvider.setBalance(character, currency, economyProvider.getBalance(character, currency) + amount) setBalance(character, currency, getBalance(character, currency) - amount) } } override fun getRichestCharacters(currency: RPKCurrency, amount: Int): List<RPKCharacter> { return plugin.core.database.getTable(RPKBankTable::class).getTop(amount, currency) } }
apache-2.0
7d1cec736aff68c22ba52a7c47d7e94a
43.983871
117
0.746055
4.383648
false
false
false
false
paoloach/zdomus
cs5463/app/src/main/java/it/achdjian/paolo/cs5463/zigbee/ZEndpoint.kt
1
1039
package it.achdjian.paolo.cs5463.zigbee import java.util.HashMap /** * Created by Paolo Achdjian on 7/9/17. */ data class ZEndpointJSon(val short_address: String, val endpoint_id: String, val profile_id: Int, val device_id: Int, val device_version: Int) { constructor():this("0","0",0,0,0) var input_clusters: Map<Int, String> = HashMap() var output_clusters: Map<Int, String> = HashMap() } data class ZEndpoint(val short_address: Int, val endpoint_id: Int, val profile_id: Int, val device_id: Int, val device_version: Int) { constructor(endpoint: ZEndpointJSon) : this( endpoint.short_address.toInt(16), endpoint.endpoint_id.toInt(16), endpoint.profile_id, endpoint.device_id, endpoint.device_version) { input_clusters = endpoint.input_clusters.mapValues { it.value.toInt(16) } output_clusters = endpoint.output_clusters.mapValues { it.value.toInt(16) } } var input_clusters: Map<Int, Int> = HashMap() var output_clusters: Map<Int, Int> = HashMap() }
gpl-2.0
03e0892f4bf57a80c69e6270046fdce0
37.518519
144
0.680462
3.429043
false
false
false
false
aspanu/KibarDataApi
src/main/kotlin/id/kibar/api/data/entity/User.kt
1
1756
package id.kibar.api.data.entity import java.sql.ResultSet data class User( var id: Int = 0, val email: String, val firstName: String = "", val lastName: String = "", val sub: String = "", // The unique Id provided by google from the Oauth process val type: UserType = UserType.PARTICIPANT, val company: String = "", val position: String = "" ) { fun mergeUser(onTop: User): User { val newId = if (id != 0 ) id else onTop.id val newEmail = if (email != "") email else onTop.email val newFirstName = if (firstName != "") firstName else onTop.firstName val newLastName = if (lastName != "") lastName else onTop.lastName val newSub = if (sub != "") sub else onTop.sub val newType = onTop.type val newCompany = if (company != "") company else onTop.company val newPosition = if (position != "") position else onTop.position return User( id = newId, email = newEmail, firstName = newFirstName, lastName = newLastName, sub = newSub, type = newType, company = newCompany, position = newPosition ) } } enum class UserType { PARTICIPANT, ADMIN, } class UserFactory { fun fromRow(row: ResultSet): User { return User( id = row.getInt("id"), email = row.getString("email"), firstName = row.getString("first_name"), lastName = row.getString("last_name"), sub = row.getString("google_sub_id"), type = UserType.valueOf(row.getString("user_type")), company = row.getString("company"), position = row.getString("position") ) } }
gpl-3.0
ca5a33f174a6efb055aaeb3d94f86ec2
30.945455
84
0.569476
4.251816
false
false
false
false
luks91/Team-Bucket
app/src/main/java/com/github/luks91/teambucket/main/base/PullRequestViewHolder.kt
2
4511
/** * Copyright (c) 2017-present, Team Bucket Contributors. * * 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.luks91.teambucket.main.base import android.support.annotation.DrawableRes import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import android.widget.TextView import com.github.luks91.teambucket.R import com.github.luks91.teambucket.model.* import com.github.luks91.teambucket.util.ImageViewTarget import com.github.luks91.teambucket.util.childImageView import com.github.luks91.teambucket.util.childTextView import com.github.luks91.teambucket.util.toMMMddDateString import io.reactivex.functions.Consumer class PullRequestViewHolder internal constructor(itemView: View, private val avatarRequestsConsumer: Consumer<AvatarLoadRequest>) : RecyclerView.ViewHolder(itemView) { private val authorName: TextView by lazy { itemView.childTextView(R.id.reviewAuthor) } private val authorAvatar: ImageView by lazy { itemView.childImageView(R.id.authorAvatar) } private val pullRequestUpdateDate: TextView by lazy {itemView.childTextView(R.id.pullRequestUpdateDate) } private val dividerView: View by lazy { itemView.findViewById(R.id.card_divider) } private val reviewers: Array<Pair<ImageView, ImageView>> by lazy { arrayOf(itemView.childImageView(R.id.firstReviewer) to itemView.childImageView(R.id.firstReviewerState), itemView.childImageView(R.id.secondReviewer) to itemView.childImageView(R.id.secondReviewerState), itemView.childImageView(R.id.thirdReviewer) to itemView.childImageView(R.id.thirdReviewerState), itemView.childImageView(R.id.fourthReviewer) to itemView.childImageView(R.id.fourthReviewerState)) } private val reviewTitle: TextView by lazy { itemView.findViewById(R.id.reviewTitle) as TextView } private val reviewBranch: TextView by lazy { itemView.findViewById(R.id.reviewBranch) as TextView } private val targetBranch: TextView by lazy { itemView.findViewById(R.id.targetBranch) as TextView } fun showDivider(display: Boolean) { dividerView.visibility = if (display) View.VISIBLE else View.INVISIBLE } fun fillIn(pullRequest: PullRequest) { authorName.text = pullRequest.author.user.displayName reviewTitle.text = pullRequest.title reviewBranch.text = pullRequest.sourceBranch.displayId targetBranch.text = pullRequest.targetBranch.displayId avatarRequestsConsumer.accept(AvatarLoadRequest(pullRequest.author.user, ImageViewTarget(authorAvatar))) val pullRequestReviewers = pullRequest.reviewers for ((index, reviewViews) in reviewers.withIndex()) { if (pullRequestReviewers.size > index) { val pullRequestMember = pullRequestReviewers[index] reviewViews.apply { avatarRequestsConsumer.accept(AvatarLoadRequest(pullRequestMember.user, ImageViewTarget(first))) first.visibility = View.VISIBLE second.visibility = View.VISIBLE second.setImageResource(resourceFromReviewerState(pullRequestMember)) } } else { reviewViews.apply { first.visibility = View.GONE second.visibility = View.GONE } } } pullRequestUpdateDate.text = pullRequest.updatedDate.toMMMddDateString() pullRequestUpdateDate.setTextColor( if (pullRequest.isLazilyReviewed()) itemView.context.getColor(R.color.warning_red_text) else itemView.context.getColor(R.color.secondary_text)) } private @DrawableRes fun resourceFromReviewerState(member: PullRequestMember): Int { when (member.status) { APPROVED -> return R.drawable.ic_approved_24dp NEEDS_WORK -> return R.drawable.ic_needs_work_24dp else -> return 0 } } }
apache-2.0
dba326b0c091930310c7f5ed93b59c0a
49.133333
129
0.721126
4.565789
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/KotlinInitScript.kt
3
17155
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.gradle.api.Action import org.gradle.api.PathValidation import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.ConfigurableFileTree import org.gradle.api.file.CopySpec import org.gradle.api.file.DeleteSpec import org.gradle.api.file.FileTree import org.gradle.api.initialization.dsl.ScriptHandler import org.gradle.api.internal.ProcessOperations import org.gradle.api.internal.file.FileOperations import org.gradle.api.invocation.Gradle import org.gradle.api.logging.Logger import org.gradle.api.logging.Logging import org.gradle.api.logging.LoggingManager import org.gradle.api.plugins.ObjectConfigurationAction import org.gradle.api.resources.ResourceHandler import org.gradle.api.tasks.WorkResult import org.gradle.kotlin.dsl.resolver.KotlinBuildScriptDependenciesResolver import org.gradle.kotlin.dsl.support.KotlinScriptHost import org.gradle.kotlin.dsl.support.delegates.GradleDelegate import org.gradle.kotlin.dsl.support.internalError import org.gradle.kotlin.dsl.support.serviceOf import org.gradle.kotlin.dsl.support.unsafeLazy import org.gradle.process.ExecResult import org.gradle.process.ExecSpec import org.gradle.process.JavaExecSpec import java.io.File import java.net.URI import kotlin.script.extensions.SamWithReceiverAnnotations import kotlin.script.templates.ScriptTemplateAdditionalCompilerArguments import kotlin.script.templates.ScriptTemplateDefinition /** * Script template for Kotlin init scripts. */ @ScriptTemplateDefinition( resolver = KotlinBuildScriptDependenciesResolver::class, scriptFilePattern = "(?:.+\\.)?init\\.gradle\\.kts" ) @ScriptTemplateAdditionalCompilerArguments( [ "-language-version", "1.4", "-api-version", "1.4", "-jvm-target", "1.8", "-Xjvm-default=all", "-Xjsr305=strict", "-XXLanguage:+DisableCompatibilityModeForNewInference", ] ) @SamWithReceiverAnnotations("org.gradle.api.HasImplicitReceiver") abstract class KotlinInitScript( private val host: KotlinScriptHost<Gradle> ) : @Suppress("deprecation") InitScriptApi(host.target) /* TODO:kotlin-dsl configure implicit receiver */ { /** * The [ScriptHandler] for this script. */ val initscript get() = host.scriptHandler /** * Applies zero or more plugins or scripts. * <p> * The given action is used to configure an [ObjectConfigurationAction], which “builds” the plugin application. * <p> * @param action the action to configure an [ObjectConfigurationAction] with before “executing” it * @see [PluginAware.apply] */ override fun apply(action: Action<in ObjectConfigurationAction>) = host.applyObjectConfigurationAction(action) override val fileOperations get() = host.fileOperations override val processOperations get() = host.processOperations } /** * Standard implementation of the API exposed to all types of [Gradle] scripts, * precompiled and otherwise. */ @Deprecated( "Kept for compatibility with precompiled script plugins published with Gradle versions prior to 6.0", replaceWith = ReplaceWith("Gradle", "org.gradle.api.invocation.Gradle") ) abstract class InitScriptApi( override val delegate: Gradle ) : GradleDelegate() { protected abstract val fileOperations: FileOperations protected abstract val processOperations: ProcessOperations /** * Configures the classpath of the init script. */ @Suppress("unused") open fun initscript(@Suppress("unused_parameter") block: ScriptHandlerScope.() -> Unit): Unit = internalError() /** * Logger for init scripts. You can use this in your init script to write log messages. */ @Suppress("unused") val logger: Logger by unsafeLazy { Logging.getLogger(Gradle::class.java) } /** * The [LoggingManager] which can be used to receive logging and to control the standard output/error capture for * this script. By default, `System.out` is redirected to the Gradle logging system at the `QUIET` log level, * and `System.err` is redirected at the `ERROR` log level. */ @Suppress("unused") val logging by unsafeLazy { gradle.serviceOf<LoggingManager>() } /** * Provides access to resource-specific utility methods, for example factory methods that create various resources. */ @Suppress("unused") val resources: ResourceHandler by unsafeLazy { fileOperations.resources } /** * Returns the relative path from this script's target base directory to the given path. * * The given path object is (logically) resolved as described for [KotlinInitScript.file], * from which a relative path is calculated. * * @param path The path to convert to a relative path. * @return The relative path. */ @Suppress("unused") fun relativePath(path: Any): String = fileOperations.relativePath(path) /** * Resolves a file path to a URI, relative to this script's target base directory. * * Evaluates the provided path object as described for [KotlinInitScript.file], * with the exception that any URI scheme is supported, not just `file:` URIs. */ @Suppress("unused") fun uri(path: Any): URI = fileOperations.uri(path) /** * Resolves a file path relative to this script's target base directory. * * If this script targets [org.gradle.api.Project], * then `path` is resolved relative to the project directory. * * If this script targets [org.gradle.api.initialization.Settings], * then `path` is resolved relative to the build root directory. * * Otherwise the file is resolved relative to the script itself. * * This method converts the supplied path based on its type: * * - A [CharSequence], including [String]. * A string that starts with `file:` is treated as a file URL. * - A [File]. * If the file is an absolute file, it is returned as is. Otherwise it is resolved. * - A [java.nio.file.Path]. * The path must be associated with the default provider and is treated the same way as an instance of `File`. * - A [URI] or [java.net.URL]. * The URL's path is interpreted as the file path. Only `file:` URLs are supported. * - A [org.gradle.api.file.Directory] or [org.gradle.api.file.RegularFile]. * - A [org.gradle.api.provider.Provider] of any supported type. * The provider's value is resolved recursively. * - A [java.util.concurrent.Callable] that returns any supported type. * The callable's return value is resolved recursively. * * @param path The object to resolve as a `File`. * @return The resolved file. */ @Suppress("unused") fun file(path: Any): File = fileOperations.file(path) /** * Resolves a file path relative to this script's target base directory. * * @param path The object to resolve as a `File`. * @param validation The validation to perform on the file. * @return The resolved file. * @see KotlinInitScript.file */ @Suppress("unused") fun file(path: Any, validation: PathValidation): File = fileOperations.file(path, validation) /** * Creates a [ConfigurableFileCollection] containing the given files. * * You can pass any of the following types to this method: * * - A [CharSequence], including [String] as defined by [KotlinInitScript.file]. * - A [File] as defined by [KotlinInitScript.file]. * - A [java.nio.file.Path] as defined by [KotlinInitScript.file]. * - A [URI] or [java.net.URL] as defined by [KotlinInitScript.file]. * - A [org.gradle.api.file.Directory] or [org.gradle.api.file.RegularFile] * as defined by [KotlinInitScript.file]. * - A [Sequence], [Array] or [Iterable] that contains objects of any supported type. * The elements of the collection are recursively converted to files. * - A [org.gradle.api.file.FileCollection]. * The contents of the collection are included in the returned collection. * - A [org.gradle.api.provider.Provider] of any supported type. * The provider's value is recursively converted to files. If the provider represents an output of a task, * that task is executed if the file collection is used as an input to another task. * - A [java.util.concurrent.Callable] that returns any supported type. * The callable's return value is recursively converted to files. * A `null` return value is treated as an empty collection. * - A [org.gradle.api.Task]. * Converted to the task's output files. * The task is executed if the file collection is used as an input to another task. * - A [org.gradle.api.tasks.TaskOutputs]. * Converted to the output files the related task. * The task is executed if the file collection is used as an input to another task. * - Anything else is treated as a failure. * * The returned file collection is lazy, so that the paths are evaluated only when the contents of the file * collection are queried. The file collection is also live, so that it evaluates the above each time the contents * of the collection is queried. * * The returned file collection maintains the iteration order of the supplied paths. * * The returned file collection maintains the details of the tasks that produce the files, * so that these tasks are executed if this file collection is used as an input to some task. * * This method can also be used to create an empty collection, which can later be mutated to add elements. * * @param paths The paths to the files. May be empty. * @return The file collection. */ @Suppress("unused") fun files(vararg paths: Any): ConfigurableFileCollection = fileOperations.configurableFiles(paths) /** * Creates a [ConfigurableFileCollection] containing the given files. * * @param paths The contents of the file collection. Evaluated as per [KotlinInitScript.files]. * @param configuration The block to use to configure the file collection. * @return The file collection. * @see KotlinInitScript.files */ @Suppress("unused") fun files(paths: Any, configuration: ConfigurableFileCollection.() -> Unit): ConfigurableFileCollection = fileOperations.configurableFiles(paths).also(configuration) /** * Creates a new [ConfigurableFileTree] using the given base directory. * * The given `baseDir` path is evaluated as per [KotlinInitScript.file]. * * The returned file tree is lazy, so that it scans for files only when the contents of the file tree are * queried. The file tree is also live, so that it scans for files each time the contents of the file tree are * queried. * * @param baseDir The base directory of the file tree. Evaluated as per [KotlinInitScript.file]. * @return The file tree. */ @Suppress("unused") fun fileTree(baseDir: Any): ConfigurableFileTree = fileOperations.fileTree(baseDir) /** * Creates a new [ConfigurableFileTree] using the given base directory. * * @param baseDir The base directory of the file tree. Evaluated as per [KotlinInitScript.file]. * @param configuration The block to use to configure the file tree. * @return The file tree. * @see [KotlinInitScript.fileTree] */ @Suppress("unused") fun fileTree(baseDir: Any, configuration: ConfigurableFileTree.() -> Unit): ConfigurableFileTree = fileOperations.fileTree(baseDir).also(configuration) /** * Creates a new [FileTree] which contains the contents of the given ZIP file. * * The given `zipPath` path is evaluated as per [KotlinInitScript.file] * * The returned file tree is lazy, so that it scans for files only when the contents of the file tree are * queried. The file tree is also live, so that it scans for files each time the contents of the file tree are * queried. * * You can combine this method with the [KotlinInitScript.copy] method to unzip a ZIP file. * * @param zipPath The ZIP file. Evaluated as per [KotlinInitScript.file]. * @return The file tree. */ @Suppress("unused") fun zipTree(zipPath: Any): FileTree = fileOperations.zipTree(zipPath) /** * Creates a new [FileTree] which contains the contents of the given TAR file. * * The given tarPath path can be: * - an instance of [org.gradle.api.resources.Resource], * - any other object is evaluated as per [KotlinInitScript.file]. * * The returned file tree is lazy, so that it scans for files only when the contents of the file tree are * queried. The file tree is also live, so that it scans for files each time the contents of the file tree are * queried. * * Unless custom implementation of resources is passed, * the tar tree attempts to guess the compression based on the file extension. * * You can combine this method with the [KotlinInitScript.copy] method to unzip a ZIP file. * * @param tarPath The TAR file or an instance of [org.gradle.api.resources.Resource]. * @return The file tree. */ @Suppress("unused") fun tarTree(tarPath: Any): FileTree = fileOperations.tarTree(tarPath) /** * Copies the specified files. * * @param configuration The block to use to configure the [CopySpec]. * @return `WorkResult` that can be used to check if the copy did any work. */ @Suppress("unused") fun copy(configuration: CopySpec.() -> Unit): WorkResult = fileOperations.copy(configuration) /** * Creates a {@link CopySpec} which can later be used to copy files or create an archive. * * @return The created [CopySpec] */ @Suppress("unused") fun copySpec(): CopySpec = fileOperations.copySpec() /** * Creates a {@link CopySpec} which can later be used to copy files or create an archive. * * @param configuration The block to use to configure the [CopySpec]. * @return The configured [CopySpec] */ @Suppress("unused") fun copySpec(configuration: CopySpec.() -> Unit): CopySpec = fileOperations.copySpec().also(configuration) /** * Creates a directory and returns a file pointing to it. * * @param path The path for the directory to be created. Evaluated as per [KotlinInitScript.file]. * @return The created directory. * @throws org.gradle.api.InvalidUserDataException If the path points to an existing file. */ @Suppress("unused") fun mkdir(path: Any): File = fileOperations.mkdir(path) /** * Deletes files and directories. * * This will not follow symlinks. If you need to follow symlinks too use [KotlinInitScript.delete]. * * @param paths Any type of object accepted by [KotlinInitScript.file] * @return true if anything got deleted, false otherwise */ @Suppress("unused") fun delete(vararg paths: Any): Boolean = fileOperations.delete(*paths) /** * Deletes the specified files. * * @param configuration The block to use to configure the [DeleteSpec]. * @return `WorkResult` that can be used to check if delete did any work. */ @Suppress("unused") fun delete(configuration: DeleteSpec.() -> Unit): WorkResult = fileOperations.delete(configuration) /** * Executes an external command. * * This method blocks until the process terminates, with its result being returned. * * @param configuration The block to use to configure the [ExecSpec]. * @return The result of the execution. */ @Suppress("unused") fun exec(configuration: ExecSpec.() -> Unit): ExecResult = processOperations.exec(configuration) /** * Executes an external Java process. * * This method blocks until the process terminates, with its result being returned. * * @param configuration The block to use to configure the [JavaExecSpec]. * @return The result of the execution. */ @Suppress("unused") fun javaexec(configuration: JavaExecSpec.() -> Unit): ExecResult = processOperations.javaexec(configuration) }
apache-2.0
0e32924012443a43b67979c3da4559e1
38.969697
119
0.688983
4.376468
false
true
false
false
KePeng1019/SmartPaperScan
app/src/main/java/com/pengke/paper/scanner/view/PaperRectangle.kt
1
6879
package com.pengke.paper.scanner.view import android.app.Activity import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.DisplayMetrics import android.util.Log import android.view.MotionEvent import android.view.View import com.pengke.paper.scanner.SourceManager import com.pengke.paper.scanner.processor.Corners import com.pengke.paper.scanner.processor.TAG import org.opencv.core.Point import org.opencv.core.Size class PaperRectangle : View { constructor(context: Context) : super(context) constructor(context: Context, attributes: AttributeSet) : super(context, attributes) constructor(context: Context, attributes: AttributeSet, defTheme: Int) : super(context, attributes, defTheme) private val rectPaint = Paint() private val circlePaint = Paint() private var ratioX: Double = 1.0 private var ratioY: Double = 1.0 private var tl: Point = Point() private var tr: Point = Point() private var br: Point = Point() private var bl: Point = Point() private val path: Path = Path() private var point2Move = Point() private var cropMode = false private var latestDownX = 0.0F private var latestDownY = 0.0F init { rectPaint.color = Color.BLUE rectPaint.isAntiAlias = true rectPaint.isDither = true rectPaint.strokeWidth = 6F rectPaint.style = Paint.Style.STROKE rectPaint.strokeJoin = Paint.Join.ROUND // set the join to round you want rectPaint.strokeCap = Paint.Cap.ROUND // set the paint cap to round too rectPaint.pathEffect = CornerPathEffect(10f) circlePaint.color = Color.LTGRAY circlePaint.isDither = true circlePaint.isAntiAlias = true circlePaint.strokeWidth = 4F circlePaint.style = Paint.Style.STROKE } fun onCornersDetected(corners: Corners) { ratioX = corners.size.width.div(measuredWidth) ratioY = corners.size.height.div(measuredHeight) tl = corners.corners[0] ?: Point() tr = corners.corners[1] ?: Point() br = corners.corners[2] ?: Point() bl = corners.corners[3] ?: Point() Log.i(TAG, "POINTS ------> ${tl.toString()} corners") resize() path.reset() path.moveTo(tl.x.toFloat(), tl.y.toFloat()) path.lineTo(tr.x.toFloat(), tr.y.toFloat()) path.lineTo(br.x.toFloat(), br.y.toFloat()) path.lineTo(bl.x.toFloat(), bl.y.toFloat()) path.close() invalidate() } fun onCornersNotDetected() { path.reset() invalidate() } fun onCorners2Crop(corners: Corners?, size: Size?) { if (corners == null) return if (size == null) return val displayMetrics = DisplayMetrics() (context as Activity).windowManager.defaultDisplay.getMetrics(displayMetrics) //exclude status bar height val statusBarHeight = getStatusBarHeight(context) var layoutWidth = displayMetrics.widthPixels var layoutHeight = displayMetrics.heightPixels - statusBarHeight val screenRatio = layoutWidth / layoutHeight val paperRatio = size.width / size.height if (screenRatio > paperRatio) { layoutWidth = (size.width / size.height * layoutHeight).toInt() } else { layoutHeight = (size.height / size.width * layoutWidth).toInt() } cropMode = true tl = corners.corners.get(0) ?: Point(8.0, 8.0) tr = corners.corners.get(1) ?: Point(size.width - 8.0, 8.0) br = corners.corners.get(2) ?: Point(size.width - 8.0, size.height - 8.0) bl = corners.corners.get(3) ?: Point(8.0, size.height - 8.0) ratioX = size.width.div(layoutWidth) ratioY = size.height.div(layoutHeight) resize() movePoints() } fun getCorners2Crop(): List<Point> { reverseSize() return listOf(tl, tr, br, bl) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas?.drawPath(path, rectPaint) if (cropMode) { canvas?.drawCircle(tl.x.toFloat(), tl.y.toFloat(), 20F, circlePaint) canvas?.drawCircle(tr.x.toFloat(), tr.y.toFloat(), 20F, circlePaint) canvas?.drawCircle(bl.x.toFloat(), bl.y.toFloat(), 20F, circlePaint) canvas?.drawCircle(br.x.toFloat(), br.y.toFloat(), 20F, circlePaint) } } override fun onTouchEvent(event: MotionEvent?): Boolean { if (!cropMode) { return false } when (event?.action) { MotionEvent.ACTION_DOWN -> { latestDownX = event.x latestDownY = event.y calculatePoint2Move(event.x, event.y) } MotionEvent.ACTION_MOVE -> { point2Move.x = (event.x - latestDownX) + point2Move.x point2Move.y = (event.y - latestDownY) + point2Move.y movePoints() latestDownY = event.y latestDownX = event.x } } return true } private fun calculatePoint2Move(downX: Float, downY: Float) { val points = listOf(tl, tr, br, bl) point2Move = points.minBy { Math.abs((it.x - downX).times(it.y - downY)) } ?: tl } private fun movePoints() { path.reset() path.moveTo(tl.x.toFloat(), tl.y.toFloat()) path.lineTo(tr.x.toFloat(), tr.y.toFloat()) path.lineTo(br.x.toFloat(), br.y.toFloat()) path.lineTo(bl.x.toFloat(), bl.y.toFloat()) path.close() invalidate() } private fun resize() { tl.x = tl.x.div(ratioX) tl.y = tl.y.div(ratioY) tr.x = tr.x.div(ratioX) tr.y = tr.y.div(ratioY) br.x = br.x.div(ratioX) br.y = br.y.div(ratioY) bl.x = bl.x.div(ratioX) bl.y = bl.y.div(ratioY) } private fun reverseSize() { tl.x = tl.x.times(ratioX) tl.y = tl.y.times(ratioY) tr.x = tr.x.times(ratioX) tr.y = tr.y.times(ratioY) br.x = br.x.times(ratioX) br.y = br.y.times(ratioY) bl.x = bl.x.times(ratioX) bl.y = bl.y.times(ratioY) } private fun getNavigationBarHeight(pContext: Context): Int { val resources = pContext.resources val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android") return if (resourceId > 0) { resources.getDimensionPixelSize(resourceId) } else 0 } private fun getStatusBarHeight(pContext: Context): Int { val resources = pContext.resources val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android") return if (resourceId > 0) { resources.getDimensionPixelSize(resourceId) } else 0 } }
apache-2.0
fd3597672ae5a16dd15ff88e6f9e7345
33.228856
113
0.607065
3.849468
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-stats-bukkit/src/main/kotlin/com/rpkit/stats/bukkit/command/stats/StatsCommand.kt
1
3437
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.stats.bukkit.command.stats import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.stats.bukkit.RPKStatsBukkit import com.rpkit.stats.bukkit.stat.RPKStatService import com.rpkit.stats.bukkit.stat.RPKStatVariableService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * Stats command. * Shows all stat values for the player's active character. */ class StatsCommand(private val plugin: RPKStatsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.stats.command.stats")) { sender.sendMessage(plugin.messages["no-permission-stats"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-service"]) return true } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages["no-character-service"]) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character"]) return true } val statsService = Services[RPKStatService::class.java] if (statsService == null) { sender.sendMessage(plugin.messages["no-stats-service"]) return true } val statVariableService = Services[RPKStatVariableService::class.java] if (statVariableService == null) { sender.sendMessage(plugin.messages["no-stat-variable-service"]) return true } sender.sendMessage(plugin.messages["stats-list-title"]) statsService.stats.forEach { stat -> sender.sendMessage(plugin.messages["stats-list-item", mapOf( "stat" to stat.name.value, "value" to stat.get(character, statVariableService.statVariables).toString() )]) } return true } }
apache-2.0
5b5fd02e0c8c4caaaa6438a6ee2b60f5
39.928571
118
0.6849
4.701778
false
false
false
false
ethauvin/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/KobaltExecutors.kt
2
2561
package com.beust.kobalt.misc import java.util.concurrent.* class NamedThreadFactory(val n: String) : ThreadFactory { private val PREFIX = "K-" val name: String get() = PREFIX + n override fun newThread(r: Runnable) : Thread { val result = Thread(r) result.name = name + "-" + result.id return result } } class KobaltExecutor(name: String, threadCount: Int) : ThreadPoolExecutor(threadCount, threadCount, 5L, TimeUnit.SECONDS, LinkedBlockingQueue<Runnable>(), NamedThreadFactory(name)) { override fun afterExecute(r: Runnable, t: Throwable?) { super.afterExecute(r, t) var ex : Throwable? = null if (t == null && r is Future<*>) { try { if (r.isDone) r.get(); } catch (ce: CancellationException) { ex = ce; } catch (ee: ExecutionException) { ex = ee.cause; } catch (ie: InterruptedException) { Thread.currentThread().interrupt(); // ignore/reset } } if (ex != null) { error(ex.toString(), ex) } } } class KobaltExecutors { fun newExecutor(name: String, threadCount: Int) : ExecutorService = KobaltExecutor(name, threadCount) val dependencyExecutor = newExecutor("Dependency", 5) val miscExecutor = newExecutor("Misc", 2) fun shutdown() { dependencyExecutor.shutdown() miscExecutor.shutdown() } fun <T> completionService(name: String, threadCount: Int, maxMs: Long, tasks: List<Callable<T>>, progress: (T) -> Unit = {}) : List<T> { val result = arrayListOf<T>() val executor = newExecutor(name, threadCount) val cs = ExecutorCompletionService<T>(executor) tasks.map { cs.submit(it) } var remainingMs = maxMs var i = 0 while (i < tasks.size && remainingMs >= 0) { var start = System.currentTimeMillis() val r = cs.take().get(remainingMs, TimeUnit.MILLISECONDS) progress(r) result.add(r) remainingMs -= (System.currentTimeMillis() - start) kobaltLog(3, "Received $r, remaining: $remainingMs ms") i++ } if (remainingMs < 0) { warn("Didn't receive all the results in time: $i / ${tasks.size}") } else { kobaltLog(2, "Received all results in ${maxMs - remainingMs} ms") } executor.shutdown() return result } }
apache-2.0
636a8322223ba9b9a2d413b1e3977752
30.231707
100
0.56228
4.340678
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/LanguageListModel.kt
1
2315
package cn.yiiguxing.plugin.translate.ui import cn.yiiguxing.plugin.translate.trans.Lang import cn.yiiguxing.plugin.translate.util.AppStorage import javax.swing.AbstractListModel import javax.swing.ComboBoxModel /** * LanguageListModel */ abstract class LanguageListModel : AbstractListModel<Lang>(), ComboBoxModel<Lang> { abstract var selected: Lang? companion object { fun sorted(languages: Collection<Lang>, selection: Lang? = null): LanguageListModel = SortedLanguageListModel(languages, selection) fun simple(languages: List<Lang>): LanguageListModel = SimpleLanguageListModel(languages) } } private class SimpleLanguageListModel(private val languages: List<Lang>) : LanguageListModel() { override var selected: Lang? = languages.elementAtOrNull(0) override fun getElementAt(index: Int): Lang = languages[index] override fun getSize(): Int = languages.size override fun setSelectedItem(anItem: Any?) { selected = languages.find { it == anItem } } override fun getSelectedItem(): Lang? = selected } private class SortedLanguageListModel(languages: Collection<Lang>, selection: Lang? = null) : LanguageListModel() { private val appStorage = AppStorage private val languageList: MutableList<Lang> = ArrayList(languages).apply { sort() } override var selected: Lang? = selection ?: languageList.firstOrNull() set(value) { if (field != value) { field = value?.apply { score += 1 } languageList.sort() update() } } private var Lang.score: Int get() = if (this == Lang.AUTO) Int.MAX_VALUE else appStorage.getLanguageScore(this) set(value) { if (this != Lang.AUTO) { appStorage.setLanguageScore(this, value) } } override fun getSize(): Int = languageList.size override fun getSelectedItem(): Any? = selected override fun getElementAt(index: Int): Lang = languageList[index] override fun setSelectedItem(anItem: Any?) { selected = anItem as Lang? } private fun MutableList<Lang>.sort() { sortByDescending { it.score } } fun update() { fireContentsChanged(this, -1, -1) } }
mit
dee183d9956d40c1ffdb28159cb4e753
28.316456
96
0.653564
4.63
false
false
false
false
wakingrufus/mastodon-jfx
src/main/kotlin/com/github/wakingrufus/mastodon/ui/StatusFeedsView.kt
1
6574
package com.github.wakingrufus.mastodon.ui import com.github.wakingrufus.mastodon.client.parseUrl import com.github.wakingrufus.mastodon.data.AccountState import com.github.wakingrufus.mastodon.data.StatusFeed import com.github.wakingrufus.mastodon.toot.boostToot import com.github.wakingrufus.mastodon.toot.unboostToot import com.github.wakingrufus.mastodon.ui.styles.DefaultStyles import javafx.collections.ObservableList import javafx.geometry.Pos import javafx.scene.control.ScrollPane import javafx.scene.paint.Color import javafx.stage.StageStyle import mu.KLogging import tornadofx.* class StatusFeedsView : View() { companion object : KLogging() val statusFeeds: ObservableList<StatusFeed> by param() val accounts: ObservableList<AccountState> by param() val parseUrlFunc: (String) -> String by param(defaultValue = ::parseUrl) override val root = hbox { style { minWidth = 100.percent minHeight = 100.percent backgroundColor = multi(DefaultStyles.backdropColor) padding = CssBox(top = 1.px, right = 1.px, bottom = 1.px, left = 1.px) } children.bind(statusFeeds) { vbox { style { backgroundColor = multi(DefaultStyles.backdropColor) textFill = Color.WHITE padding = box(1.px, 1.px, 1.px, 1.px) alignment = Pos.CENTER maxWidth = 40.em } label(it.name + " @ " + it.server) { textFill = Color.WHITE style { backgroundColor = multi(DefaultStyles.backdropColor) padding = CssBox(1.px, 1.px, 1.px, 1.px) fontSize = 2.5.em } } scrollpane { hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER vbox { children.bind(it.statuses) { status -> vbox { addClass(DefaultStyles.defaultBorder) style { padding = CssBox(top = 1.em, bottom = 1.em, left = 1.em, right = 1.em) alignment = Pos.TOP_LEFT backgroundColor = multi(DefaultStyles.backgroundColor) textFill = Color.WHITE } this += find<AccountFragment>(mapOf( "account" to status.account!!, "server" to parseUrlFunc(status.uri))) val toot = parseToot(status.content) toot.style { backgroundColor = multi(DefaultStyles.backgroundColor) textFill = Color.WHITE } this += toot hbox { button("↰") { addClass(DefaultStyles.smallButton) action { val modal: AccountChooserView = find<AccountChooserView>(mapOf("accounts" to accounts)).apply { openModal( stageStyle = StageStyle.UTILITY, block = true) } val account = modal.getAccount() logger.info { "account chosen: $account" } if (account != null) { find<TootEditor>(mapOf( "client" to account.client, "inReplyTo" to status)).apply { openModal(stageStyle = StageStyle.UTILITY, block = true) } } } } button("☆") { if (status.isFavourited) text = "★" addClass(DefaultStyles.smallButton) } button("♲") { addClass(DefaultStyles.smallButton) if (status.isReblogged) text = "♻" action { val modal: AccountChooserView = find<AccountChooserView>(mapOf("accounts" to accounts)).apply { openModal( stageStyle = StageStyle.UTILITY, block = true) } val account = modal.getAccount() logger.info { "account chosen: $account" } if (account != null) { if (status.isReblogged) { this.text = "♲" unboostToot(id = status.id, client = account.client) } else { this.text = "♻" boostToot(id = status.id, client = account.client) } } } } } } } } } } } } }
mit
d55480af43b9829f9f09bb2e3199aca1
51.071429
115
0.358079
6.659898
false
false
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/gen/go/LangGoUtils.kt
1
11999
package ee.lang.gen.go import ee.common.ext.* import ee.lang.* object g : StructureUnit({ namespace("").name("Go") }) { val error = ExternalType { ifc() } object fmt : StructureUnit({ namespace("fmt") }) { val Sprintf = Operation() val Fprintf = Operation() val Errorf = Operation() } object html : StructureUnit({ namespace("html") }) { val EscapeString = Operation() } object errors : StructureUnit({ namespace("errors") }) { val New = Operation { ret(error) } } object io : StructureUnit({ namespace("io") }) { object ioutil : StructureUnit({ namespace("io.ioutil") }) { val ReadFile = Operation { ret(error) } } } object time : StructureUnit({ namespace("time") }) { val Time = ExternalType {} val Now = Operation() } object context : StructureUnit({ namespace("context") }) { val Context = ExternalType { ifc() } } object net : StructureUnit({ namespace("net") }) { object http : StructureUnit({ namespace("net.http") }) { val Client = ExternalType {} val ResponseWriter = ExternalType { ifc() } val Request = ExternalType() val MethodGet = Operation() val MethodHead = Operation() val MethodPost = Operation() val MethodPut = Operation() val MethodPatch = Operation() val MethodDelete = Operation() val MethodConnect = Operation() val MethodOptions = Operation() val MethodTrace = Operation() } } object strings : StructureUnit({ namespace("strings") }) { val EqualFold = Operation() val Split = Operation() } object encoding : StructureUnit({ namespace("encoding") }) { object json : StructureUnit() { val NewDecoder = Operation() val Decoder = ExternalType() val Marshal = Operation() val Unmarshal = Operation() } } object mux : StructureUnit({ namespace("github.com.gorilla.mux") }) { object Router : ExternalType() {} object Vars : ExternalType() {} } object mgo2 : StructureUnit({ namespace("gopkg.in.mgo.v2.bson") }) { object bson : StructureUnit() { object Raw : ExternalType() } } //common libs val geeUtils = "github.com.go-ee.utils" object gee : StructureUnit({ namespace(geeUtils) }) { val PtrTime = Operation() object enum : StructureUnit({ namespace("$geeUtils.enum") }) { val Literal = ExternalType() } object net : StructureUnit({ namespace("$geeUtils.net") }) { val Command = ExternalType() val QueryType = ExternalType() val QueryTypeCount = ExternalType() val QueryTypeExist = ExternalType() val QueryTypeFind = ExternalType() val PostById = Operation() val DeleteById = Operation() val GetItems = Operation() } object eh : StructureUnit({ namespace("$geeUtils.eh") }) { object AggregateEngine : ExternalType() { val RegisterForAllEvents = Operation() val RegisterForEvent = Operation() val NewAggregateEngine = Operation() } object DelegateCommandHandler : ExternalType({ ifc() }) object DelegateEventHandler : ExternalType({ ifc() }) object AggregateStoreEvent : ExternalType({ ifc() }) object AggregateBase : ExternalType() object Entity : ExternalType({ namespace("$geeUtils.eh") constructorNoProps() }) { val id = prop(n.UUID).key() val deleted = prop(n.Date) } object NewAggregateBase : Operation() object EventHandlerNotImplemented : Operation() object CommandHandlerNotImplemented : Operation() object QueryNotImplemented : Operation() object EntityAlreadyExists : Operation() object EntityNotExists : Operation() object EntityChildNotExists : Operation() object EntityChildIdNotDefined : Operation() object IdsDismatch : Operation() object ValidateIdsMatch : Operation() object ValidateNewId : Operation() object HttpCommandHandler : ExternalType({ constructorFull() }) { val ctx = prop { type(context.Context) } val commandBus = prop { type(g.eh.CommandHandler) } } object HttpQueryHandler : ExternalType({ constructorFull() }) { } object Projector : ExternalType() {} object NewProjector : Operation() {} // errors object CommandError : ExternalType() object ErrAggregateDeleted : ExternalType() object Middleware : ExternalType() } } object google : StructureUnit({ namespace("github.com.google").name("google") }) { object uuid : StructureUnit() { object UUID : ExternalType() object New : Operation() object NewUUID : Operation() object Parse : Operation() } } object eh : StructureUnit({ namespace("github.com.looplab.eventhorizon").name("eh") }) { object Aggregate : ExternalType({}) {} object AggregateBase : ExternalType({ name("AggregateBase") namespace("github.com.looplab.eventhorizon.aggregatestore.events") constr { namespace("github.com.looplab.eventhorizon.aggregatestore.events") p("t", AggregateType) p("id", n.UUID) } }) {} object NewAggregateBase : Operation({ namespace("github.com.looplab.eventhorizon.aggregatestore.events") }) {} object RegisterEventData : Operation() {} object EventData : ExternalType({ ifc() }) {} object AggregateType : ExternalType() {} object Command : ExternalType({ ifc() }) {} object CommandHandler : ExternalType({ ifc() }) object CommandBus : ExternalType({ name("CommandHandler") namespace("github.com.looplab.eventhorizon.commandhandler.bus") }) {} object CommandType : ExternalType() {} object AggregateCommandHandler : ExternalType({ ifc() }) { object SetAggregate : Operation() { val aggregateType = p() val cmdType = p() } } object Entity : ExternalType({ ifc() }) {} object EventStore : ExternalType({ ifc() }) { object Save : Operation() { val ctx = p() } } object EventBus : ExternalType({ ifc() }) {} object EventPublisher : ExternalType({ ifc() }) {} object EventHandler : ExternalType({ ifc() }) {} object Event : ExternalType({ ifc() }) {} object EventType : ExternalType() {} object ReadRepo : ExternalType({ ifc() }) { } object WriteRepo : ExternalType({ ifc() }) { } object ReadWriteRepo : ExternalType({ ifc() }) { } object Projector : ExternalType({ namespace("github.com.looplab.eventhorizon.eventhandler.projector") }) {} object Type : ExternalType({ namespace("github.com.looplab.eventhorizon.eventhandler.projector") }) {} } object mapset : StructureUnit({ namespace("github.com.deckarep.golang-set.mapset").name("mapset") }) { val NewSet = Operation() object Set : Type() { val Add = Operation() } } object cli : StructureUnit({ namespace("github.com.urfave.cli").name("cli") }) { val Command = ExternalType { ifc() } val Context = ExternalType() val NewApp = Operation() } object logrus : StructureUnit({ namespace("github.com.sirupsen.logrus") }) { val Entry = ExternalType() } } open class GoContext( namespace: String = "", moduleFolder: String = "", genFolder: String = "src", genFolderDeletable: Boolean = false, genFolderPatternDeletable: Regex? = ".*_base.go".toRegex(), derivedController: DerivedController, macroController: MacroController ) : GenerationContext( namespace, moduleFolder, genFolder, genFolderDeletable, genFolderPatternDeletable, derivedController, macroController ) { private val namespaceLastPart: String = namespace.substringAfterLast(".") override fun complete(content: String, indent: String): String { return "${toHeader(indent)}${toPackage(indent)}${toImports(indent)}$content${toFooter(indent)}" } private fun toPackage(indent: String): String { return namespaceLastPart.isNotEmpty().then { "${indent}package $namespaceLastPart$nL$nL" } } private fun toImports(indent: String): String { return types.isNotEmpty().then { val outsideTypes = types.filter { it.namespace().isNotEmpty() && !it.namespace().equals(namespace, true) } outsideTypes.isNotEmpty().then { outsideTypes.sortedBy { it.namespace() }.map { "$indent${it.namespace()}" }.toSortedSet() .joinSurroundIfNotEmptyToString(nL, "${indent}import ($nL", "$nL)") { if (it.startsWith("ee.")) { """ "${ it.toLowerCase().toDotsAsPath() .replace("ee/", "github.com/go-ee/") .replace("github/com", "github.com") .replace("gopkg/in/mgo/v2", "gopkg.in/mgo.v2") }"""" } else { """ "${ it.toLowerCase().toDotsAsPath() .replace("github/com", "github.com") .replace("gopkg/in/mgo/v2", "gopkg.in/mgo.v2") }"""" } } } } } override fun n(item: ItemI<*>, derivedKind: String): String { val derived = types.addReturn(derivedController.derive(item, derivedKind)) if (derived.namespace().isEmpty() || derived.namespace().equals(namespace, true)) { return derived.name() } else { return """${derived.namespace().substringAfterLast(".").toLowerCase()}.${derived.name()}""" } } } fun <T : StructureUnitI<*>> T.prepareForGoGeneration(): T { initsForGoGeneration() extendForGoGenerationLang() return this } fun <T : StructureUnitI<*>> T.initsForGoGeneration(): T { g.initObjectTree() initObjectTrees() return this } fun <T : StructureUnitI<*>> T.extendForGoGenerationLang(): T { //declare as 'isBase' all compilation units with non implemented operations. declareAsBaseWithNonImplementedOperation() prepareAttributesOfEnums() defineSuperUnitsAsAnonymousProps() defineConstructorNoProps() return this } fun AttributeI<*>.nameForGoMember(): String = storage.getOrPut(this, "nameForGoMember", { val name = name() isReplaceable().notSetOrTrue().ifElse({ name.capitalize() }, { name.decapitalize() }) }) val itemAndTemplateNameAsGoFileName: TemplateI<*>.(CompositeI<*>) -> Names = { Names("${it.name().toUnderscoredLowerCase()}_${name.toUnderscoredLowerCase()}.go") } val templateNameAsGoFileName: TemplateI<*>.(CompositeI<*>) -> Names = { Names("${name.toUnderscoredLowerCase()}.go") } val itemNameAsGoFileName: TemplateI<*>.(CompositeI<*>) -> Names = { Names("${it.name().toUnderscoredLowerCase()}.go") }
apache-2.0
a690e108baab50cc909c9260f3eea042
30.496063
115
0.562547
4.801521
false
false
false
false
FurhatRobotics/example-skills
demo-skill/src/main/kotlin/furhatos/app/demo/flow/transitions/verifyWakeup.kt
1
1574
package furhatos.app.demo.flow import furhatos.app.demo.flow.modes.Parent import furhatos.app.demo.nlu.ConversationalIntent import furhatos.app.demo.personas.phrases import furhatos.app.demo.util.AttendUsers import furhatos.app.demo.util.setLED import furhatos.autobehavior.setDefaultMicroexpression import furhatos.flow.kotlin.* import furhatos.gestures.Gestures import furhatos.nlu.Response import furhatos.nlu.common.No import furhatos.nlu.common.Yes fun VerifyWakeup(resp: Response<*>? = null) : State = state(Parent) { onEntry { send(AttendUsers()) furhat.setLED("White") furhat.setDefaultMicroexpression() furhat.gesture(Gestures.OpenEyes, priority = 1) // If we have an intent that we have flagged as a conversational intent, we go to active to answer it if (resp != null && resp.multiIntent && resp.secondaryIntent is ConversationalIntent) { // is working resp.intent = resp.secondaryIntent resp.multiIntent = false resp.secondaryIntent = null goto(Active(resp)) } // If not, we check if the user wanted to address us or if it triggered as a mistake else { furhat.ask("Are you talking to me?") } } onResponse<Yes> { furhat.say { +"Cool!" +phrases.greeting } goto(Active(resp)) } onResponse<No> { furhat.say("Oh, okay") goto(Sleeping) } onNoResponse { goto(Sleeping) } onResponse { goto(Sleeping) } }
mit
d0c7cd476b033174c6ebe169290bf8bc
27.636364
109
0.646125
4.164021
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/manual_machines/Blocks.kt
2
4485
package com.cout970.magneticraft.features.manual_machines import com.cout970.magneticraft.AABB import com.cout970.magneticraft.misc.CreativeTabMg import com.cout970.magneticraft.misc.RegisterBlocks import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.misc.vector.createAABBUsing import com.cout970.magneticraft.misc.vector.plus import com.cout970.magneticraft.misc.vector.toBlockPos import com.cout970.magneticraft.misc.vector.vec3Of import com.cout970.magneticraft.systems.blocks.BlockBase import com.cout970.magneticraft.systems.blocks.BlockBuilder import com.cout970.magneticraft.systems.blocks.CommonMethods import com.cout970.magneticraft.systems.blocks.IBlockMaker import com.cout970.magneticraft.systems.itemblocks.itemBlockListOf import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.item.ItemBlock import net.minecraft.util.math.BlockPos /** * Created by cout970 on 2017/06/12. */ @RegisterBlocks object Blocks : IBlockMaker { lateinit var box: BlockBase private set lateinit var crushingTable: BlockBase private set lateinit var sluiceBox: BlockBase private set lateinit var fabricator: BlockBase private set override fun initBlocks(): List<Pair<Block, ItemBlock>> { val builder = BlockBuilder().apply { material = Material.IRON creativeTab = CreativeTabMg } box = builder.withName("box").copy { material = Material.WOOD factory = factoryOf(::TileBox) onActivated = CommonMethods::openGui }.build() crushingTable = builder.withName("crushing_table").copy { factory = factoryOf(::TileCrushingTable) material = Material.ROCK forceModelBake = true customModels = listOf("normal" to resource("models/block/mcx/crushing_table.mcx")) hasCustomModel = true //methods boundingBox = { listOf(vec3Of(0, 0, 0) createAABBUsing vec3Of(1, 0.875, 1)) } onActivated = CommonMethods::delegateToModule }.build() sluiceBox = builder.withName("sluice_box").copy { states = CommonMethods.CenterOrientation.values().toList() factory = factoryOf(::TileSluiceBox) factoryFilter = { it[CommonMethods.PROPERTY_CENTER_ORIENTATION]?.center ?: false } customModels = listOf( "model" to resource("models/block/mcx/sluice_box.mcx"), "inventory" to resource("models/block/mcx/sluice_box_inv.mcx"), "water" to resource("models/block/mcx/sluice_box_water.mcx") ) hasCustomModel = true generateDefaultItemBlockModel = false alwaysDropDefault = true //methods pickBlock = CommonMethods::pickDefaultBlock onActivated = CommonMethods::delegateToModule blockStatesToPlace = { val facing = it.player.horizontalFacing val center = CommonMethods.CenterOrientation.of(facing, true) val noCenter = CommonMethods.CenterOrientation.of(facing.opposite, false) val thisState = it.default.withProperty(CommonMethods.PROPERTY_CENTER_ORIENTATION, center) val otherState = it.default.withProperty(CommonMethods.PROPERTY_CENTER_ORIENTATION, noCenter) listOf(BlockPos.ORIGIN to thisState, facing.toBlockPos() to otherState) } onBlockBreak = func@{ val facing = it.state[CommonMethods.PROPERTY_CENTER_ORIENTATION]?.facing ?: return@func it.worldIn.destroyBlock(it.pos + facing.toBlockPos(), true) } onDrop = { val center = it.state[CommonMethods.PROPERTY_CENTER_ORIENTATION]?.center ?: false if (center) it.default else emptyList() } boundingBox = { val center = it.state[CommonMethods.PROPERTY_CENTER_ORIENTATION]?.center ?: false if (center) listOf(Block.FULL_BLOCK_AABB) else listOf(AABB(0.0, 0.0, 0.0, 1.0, 0.5, 1.0)) } }.build() fabricator = builder.withName("fabricator").copy { factory = factoryOf(::TileFabricator) onActivated = CommonMethods::openGui }.build() return itemBlockListOf(box, crushingTable, sluiceBox, fabricator) } }
gpl-2.0
beac724fffb43694c8475612f93bb775
42.970588
109
0.665106
4.388454
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/api/internal/registries/machines/kiln/KilnRecipe.kt
2
1727
package com.cout970.magneticraft.api.internal.registries.machines.kiln import com.cout970.magneticraft.api.internal.ApiUtils import com.cout970.magneticraft.api.registries.machines.kiln.IKilnRecipe import com.cout970.magneticraft.misc.inventory.isNotEmpty import net.minecraft.block.state.IBlockState import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraftforge.oredict.OreDictionary /** * Created by Yurgen on 22/08/2016. */ data class KilnRecipe( private val input: ItemStack, private val itemOutput: ItemStack, private val blockOutput: IBlockState?, private val duration: Int, private val minTemp: Double, private val maxTemp: Double, private val oreDict: Boolean ) : IKilnRecipe { override fun getInput(): ItemStack = input.copy() override fun getItemOutput(): ItemStack = itemOutput.copy() override fun getBlockOutput(): IBlockState? = blockOutput override fun getBlockOutputAsItem(): ItemStack = if (blockOutput == null) ItemStack.EMPTY else ItemStack(Item.getItemFromBlock(blockOutput.block), 1, blockOutput.block.damageDropped(blockOutput)) override fun isItemRecipe(): Boolean = itemOutput.isNotEmpty override fun isBlockRecipe(): Boolean = blockOutput != null override fun getDuration(): Int = duration override fun getMaxTemp(): Double = maxTemp override fun getMinTemp(): Double = minTemp override fun matches(input: ItemStack): Boolean { if (ApiUtils.equalsIgnoreSize(input, this.input)) return true if (oreDict) { val ids = OreDictionary.getOreIDs(this.input) return OreDictionary.getOreIDs(input).any { it in ids } } return false } }
gpl-2.0
d1f09ac57a60806bc6372b3e45f0ac7f
35
154
0.736537
4.383249
false
false
false
false
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/ui/modules/search/SearchUserActivity.kt
1
3662
package com.fastaccess.ui.modules.search import android.content.Context import android.content.Intent import android.os.Bundle import android.text.Editable import android.view.View import android.widget.CheckBox import butterknife.BindView import butterknife.OnClick import butterknife.OnEditorAction import butterknife.OnTextChanged import com.evernote.android.state.State import com.fastaccess.R import com.fastaccess.helper.AnimHelper import com.fastaccess.helper.AppHelper import com.fastaccess.helper.InputHelper import com.fastaccess.ui.base.BaseActivity import com.fastaccess.ui.base.mvp.BaseMvp import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.fastaccess.ui.modules.search.repos.SearchReposFragment import com.fastaccess.ui.widgets.FontAutoCompleteEditText class SearchUserActivity : BaseActivity<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() { @BindView(R.id.forkCheckBox) lateinit var forkCheckBox: CheckBox @BindView(R.id.clear) lateinit var clear: View @BindView(R.id.searchEditText) lateinit var searchEditText: FontAutoCompleteEditText @State var username = "" @State var searchTerm = "" @OnTextChanged(value = [R.id.searchEditText], callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED) fun onTextChange(str: Editable) { searchTerm = str.toString() if (searchTerm.isEmpty()) { AnimHelper.animateVisibility(clear, false) } else { AnimHelper.animateVisibility(clear, true) } } @OnClick(R.id.search) fun onSearchClicked() { searchTerm = searchEditText.text.toString() makeSearch() } @OnClick(R.id.forkCheckBox) fun checkBoxClicked() { onSearchClicked() } @OnEditorAction(R.id.searchEditText) fun onEditor(): Boolean { onSearchClicked() return true } @OnClick(R.id.clear) internal fun onClear(view: View) { if (view.id == R.id.clear) { searchEditText.setText("") } } override fun layout(): Int = R.layout.activity_search_user override fun isTransparent(): Boolean = false override fun canBack(): Boolean = true override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter() override fun isSecured(): Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { val args = intent.extras username = args?.getString(USERNAME) ?: "" if (InputHelper.isEmpty(username)) { finish() return } searchTerm = args?.getString(SEARCH_TERM) ?: "" supportFragmentManager.beginTransaction() .replace(R.id.containerFragment, SearchReposFragment.newInstance(), "SearchReposFragment") .commit() } searchEditText.setText(searchTerm) onSearchClicked() } private fun makeSearch() { val query = "user:$username $searchTerm fork:${forkCheckBox.isChecked}" getFragment()?.onQueueSearch(query) } private fun getFragment() = AppHelper.getFragmentByTag(supportFragmentManager, "SearchReposFragment") as? SearchReposFragment? companion object { val USERNAME = "username" val SEARCH_TERM = "search" fun getIntent(context: Context, username: String, searchTerm: String?): Intent { val intent = Intent(context, SearchUserActivity::class.java) intent.putExtra(USERNAME, username) intent.putExtra(SEARCH_TERM, searchTerm) return intent } } }
gpl-3.0
f0fcdbf091d742c803d8f358c08e71eb
32.605505
130
0.685418
4.635443
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/resolver/KotlinBuildScriptModelRequest.kt
1
8047
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.resolver import org.gradle.kotlin.dsl.provider.KotlinDslProviderMode import org.gradle.kotlin.dsl.support.KotlinScriptType import org.gradle.kotlin.dsl.support.isParentOf import org.gradle.kotlin.dsl.support.kotlinScriptTypeFor import org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptModel import org.gradle.tooling.GradleConnector import org.gradle.tooling.ModelBuilder import org.gradle.tooling.ProjectConnection import com.google.common.annotations.VisibleForTesting import java.io.File import java.util.function.Function @VisibleForTesting sealed class GradleInstallation { data class Local(val dir: java.io.File) : GradleInstallation() data class Remote(val uri: java.net.URI) : GradleInstallation() data class Version(val number: String) : GradleInstallation() object Wrapper : GradleInstallation() } @VisibleForTesting data class KotlinBuildScriptModelRequest( val projectDir: File, val scriptFile: File? = null, val gradleInstallation: GradleInstallation = GradleInstallation.Wrapper, val gradleUserHome: File? = null, val javaHome: File? = null, val options: List<String> = emptyList(), val jvmOptions: List<String> = emptyList(), val environmentVariables: Map<String, String> = emptyMap(), val correlationId: String = newCorrelationId() ) internal fun newCorrelationId() = System.nanoTime().toString() internal typealias ModelBuilderCustomization = ModelBuilder<KotlinBuildScriptModel>.() -> Unit @VisibleForTesting fun fetchKotlinBuildScriptModelFor( request: KotlinBuildScriptModelRequest, modelBuilderCustomization: ModelBuilderCustomization = {} ): KotlinBuildScriptModel = fetchKotlinBuildScriptModelFor(request.toFetchParametersWith { setJavaHome(request.javaHome) modelBuilderCustomization() }) @VisibleForTesting fun fetchKotlinBuildScriptModelFor( importedProjectDir: File, scriptFile: File?, connectorForProject: Function<File, GradleConnector> ): KotlinBuildScriptModel = fetchKotlinBuildScriptModelFor(FetchParameters(importedProjectDir, scriptFile, connectorForProject)) private data class FetchParameters( val importedProjectDir: File, val scriptFile: File?, val connectorForProject: Function<File, GradleConnector>, val options: List<String> = emptyList(), val jvmOptions: List<String> = emptyList(), val environmentVariables: Map<String, String> = emptyMap(), val correlationId: String = newCorrelationId(), val modelBuilderCustomization: ModelBuilderCustomization = {} ) private fun KotlinBuildScriptModelRequest.toFetchParametersWith(modelBuilderCustomization: ModelBuilderCustomization) = FetchParameters( projectDir, scriptFile, Function { projectDir -> connectorFor(this).forProjectDirectory(projectDir) }, options, jvmOptions, environmentVariables, correlationId, modelBuilderCustomization ) private fun connectorFor(request: KotlinBuildScriptModelRequest): GradleConnector = GradleConnector.newConnector() .useGradleFrom(request.gradleInstallation) .useGradleUserHomeDir(request.gradleUserHome) private fun GradleConnector.useGradleFrom(gradleInstallation: GradleInstallation): GradleConnector = gradleInstallation.run { when (this) { is GradleInstallation.Local -> useInstallation(dir) is GradleInstallation.Remote -> useDistribution(uri) is GradleInstallation.Version -> useGradleVersion(number) GradleInstallation.Wrapper -> useBuildDistribution() } } private fun fetchKotlinBuildScriptModelFor(parameters: FetchParameters): KotlinBuildScriptModel { if (parameters.scriptFile == null) { return fetchKotlinBuildScriptModelFrom(parameters.importedProjectDir, parameters) } val effectiveProjectDir = buildSrcProjectDirOf(parameters.scriptFile, parameters.importedProjectDir) ?: parameters.importedProjectDir val scriptModel = fetchKotlinBuildScriptModelFrom(effectiveProjectDir, parameters) if (scriptModel.enclosingScriptProjectDir == null && hasProjectDependentClassPath(parameters.scriptFile)) { val externalProjectRoot = projectRootOf(parameters.scriptFile, parameters.importedProjectDir) if (externalProjectRoot != parameters.importedProjectDir) { return fetchKotlinBuildScriptModelFrom(externalProjectRoot, parameters) } } return scriptModel } private fun fetchKotlinBuildScriptModelFrom( projectDir: File, parameters: FetchParameters ): KotlinBuildScriptModel = connectionForProjectDir(projectDir, parameters).let { connection -> @Suppress("ConvertTryFinallyToUseCall") try { connection.modelBuilderFor(parameters).apply(parameters.modelBuilderCustomization).get() } finally { connection.close() } } private fun connectionForProjectDir(projectDir: File, parameters: FetchParameters): ProjectConnection = parameters.connectorForProject.apply(projectDir).connect() private fun ProjectConnection.modelBuilderFor(parameters: FetchParameters) = model(KotlinBuildScriptModel::class.java).apply { setEnvironmentVariables(parameters.environmentVariables.takeIf { it.isNotEmpty() }) setJvmArguments(parameters.jvmOptions + modelSpecificJvmOptions) forTasks(kotlinBuildScriptModelTask) val arguments = parameters.options.toMutableList() arguments += "-P$kotlinBuildScriptModelCorrelationId=${parameters.correlationId}" parameters.scriptFile?.let { arguments += "-P$kotlinBuildScriptModelTarget=${it.canonicalPath}" } withArguments(arguments) } private val modelSpecificJvmOptions = listOf("-D${KotlinDslProviderMode.systemPropertyName}=${KotlinDslProviderMode.classPathMode}") const val kotlinBuildScriptModelTarget = "org.gradle.kotlin.dsl.provider.script" const val kotlinBuildScriptModelCorrelationId = "org.gradle.kotlin.dsl.provider.cid" const val kotlinBuildScriptModelTask = "prepareKotlinBuildScriptModel" private fun buildSrcProjectDirOf(scriptFile: File, importedProjectDir: File): File? = importedProjectDir.resolve("buildSrc").takeIf { buildSrc -> buildSrc.isDirectory && buildSrc.isParentOf(scriptFile) } private fun hasProjectDependentClassPath(scriptFile: File): Boolean = when (kotlinScriptTypeFor(scriptFile)) { KotlinScriptType.INIT -> false else -> true } internal fun projectRootOf(scriptFile: File, importedProjectRoot: File, stopAt: File? = null): File { // TODO remove hardcoded reference to settings.gradle once there's a public TAPI client api for that fun isProjectRoot(dir: File) = File(dir, "settings.gradle.kts").isFile || File(dir, "settings.gradle").isFile || dir.name == "buildSrc" tailrec fun test(dir: File): File = when { dir == importedProjectRoot -> importedProjectRoot isProjectRoot(dir) -> dir else -> { val parentDir = dir.parentFile when (parentDir) { null, dir, stopAt -> scriptFile.parentFile // external project else -> test(parentDir) } } } return test(scriptFile.parentFile) }
apache-2.0
9bd5494d48ccadcb4db54322ea5b453d
31.188
111
0.735678
4.991935
false
false
false
false
owncloud/android
owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/security/PassCodeViewModel.kt
2
10585
/** * ownCloud Android client application * * @author Juan Carlos Garrote Gascón * * Copyright (C) 2021 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.presentation.viewmodels.security import android.os.CountDownTimer import android.os.SystemClock import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.owncloud.android.R import com.owncloud.android.data.preferences.datasources.SharedPreferencesProvider import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.ui.security.BiometricActivity import com.owncloud.android.presentation.ui.security.PREFERENCE_LAST_UNLOCK_ATTEMPT_TIMESTAMP import com.owncloud.android.presentation.ui.security.PREFERENCE_LAST_UNLOCK_TIMESTAMP import com.owncloud.android.presentation.ui.security.passcode.PasscodeAction import com.owncloud.android.presentation.ui.security.passcode.PassCodeActivity import com.owncloud.android.presentation.ui.security.passcode.Status import com.owncloud.android.presentation.ui.security.passcode.PasscodeType import com.owncloud.android.presentation.ui.settings.fragments.SettingsSecurityFragment.Companion.PREFERENCE_LOCK_ATTEMPTS import com.owncloud.android.providers.ContextProvider import java.lang.StringBuilder import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.pow class PassCodeViewModel( private val preferencesProvider: SharedPreferencesProvider, private val contextProvider: ContextProvider, private val action: PasscodeAction ) : ViewModel() { private val _getTimeToUnlockLiveData = MutableLiveData<Event<String>>() val getTimeToUnlockLiveData: LiveData<Event<String>> get() = _getTimeToUnlockLiveData private val _getFinishedTimeToUnlockLiveData = MutableLiveData<Event<Boolean>>() val getFinishedTimeToUnlockLiveData: LiveData<Event<Boolean>> get() = _getFinishedTimeToUnlockLiveData private var _passcode = MutableLiveData<String>() val passcode: LiveData<String> get() = _passcode private var _status = MutableLiveData<Status>() val status: LiveData<Status> get() = _status private var numberOfPasscodeDigits: Int private var passcodeString = StringBuilder() private lateinit var firstPasscode: String private var confirmingPassCode = false init { numberOfPasscodeDigits = (getPassCode()?.length ?: getNumberOfPassCodeDigits()) } fun onNumberClicked(number: Int) { if (passcodeString.length < numberOfPasscodeDigits && (getNumberOfAttempts() < 3 || getTimeToUnlockLeft() == 0.toLong())) { passcodeString.append(number.toString()) _passcode.postValue(passcodeString.toString()) if (passcodeString.length == numberOfPasscodeDigits) { processFullPassCode() } } } fun onBackspaceClicked() { if (passcodeString.isNotEmpty()) { passcodeString.deleteCharAt(passcodeString.length - 1) _passcode.postValue(passcodeString.toString()) } } /** * Processes the passcode entered by the user just after the last digit was in. * * Takes into account the action requested to the activity, the currently saved pass code and * the previously typed pass code, if any. */ private fun processFullPassCode() { when (action) { PasscodeAction.CHECK -> { actionCheckPasscode() } PasscodeAction.REMOVE -> { actionRemovePasscode() } PasscodeAction.CREATE -> { actionCreatePasscode() } } } private fun actionCheckPasscode() { if (checkPassCodeIsValid(passcodeString.toString())) { // pass code accepted in request, user is allowed to access the app setLastUnlockTimestamp() val passCode = getPassCode() if (passCode != null && passCode.length < getNumberOfPassCodeDigits()) { setMigrationRequired(true) removePassCode() _status.postValue(Status(PasscodeAction.CHECK, PasscodeType.MIGRATION)) } _status.postValue(Status(PasscodeAction.CHECK, PasscodeType.OK)) resetNumberOfAttempts() } else { increaseNumberOfAttempts() passcodeString = StringBuilder() _status.postValue(Status(PasscodeAction.CHECK, PasscodeType.ERROR)) } } private fun actionRemovePasscode() { if (checkPassCodeIsValid(passcodeString.toString())) { removePassCode() _status.postValue(Status(PasscodeAction.REMOVE, PasscodeType.OK)) } else { passcodeString = StringBuilder() _status.postValue(Status(PasscodeAction.REMOVE, PasscodeType.ERROR)) } } private fun actionCreatePasscode() { // enabling pass code if (!confirmingPassCode) { requestPassCodeConfirmation() _status.postValue(Status(PasscodeAction.CREATE, PasscodeType.NO_CONFIRM)) } else if (confirmPassCode()) { setPassCode() _status.postValue(Status(PasscodeAction.CREATE, PasscodeType.CONFIRM)) } else { passcodeString = StringBuilder() _status.postValue(Status(PasscodeAction.CREATE, PasscodeType.ERROR)) } } fun getPassCode() = preferencesProvider.getString(PassCodeActivity.PREFERENCE_PASSCODE, loadPinFromOldFormatIfPossible()) fun setPassCode() { preferencesProvider.putString(PassCodeActivity.PREFERENCE_PASSCODE, firstPasscode) preferencesProvider.putBoolean(PassCodeActivity.PREFERENCE_SET_PASSCODE, true) numberOfPasscodeDigits = (getPassCode()?.length ?: getNumberOfPassCodeDigits()) } fun removePassCode() { preferencesProvider.removePreference(PassCodeActivity.PREFERENCE_PASSCODE) preferencesProvider.putBoolean(PassCodeActivity.PREFERENCE_SET_PASSCODE, false) numberOfPasscodeDigits = (getPassCode()?.length ?: getNumberOfPassCodeDigits()) } fun checkPassCodeIsValid(passcode: String): Boolean { val passCodeString = getPassCode() if (passCodeString.isNullOrEmpty()) return false return passcode == passCodeString } fun getNumberOfPassCodeDigits(): Int { val numberOfPassCodeDigits = contextProvider.getInt(R.integer.passcode_digits) return maxOf(numberOfPassCodeDigits, PassCodeActivity.PASSCODE_MIN_LENGTH) } fun setMigrationRequired(required: Boolean) = preferencesProvider.putBoolean(PassCodeActivity.PREFERENCE_MIGRATION_REQUIRED, required) fun setLastUnlockTimestamp() = preferencesProvider.putLong(PREFERENCE_LAST_UNLOCK_TIMESTAMP, SystemClock.elapsedRealtime()) fun getNumberOfAttempts() = preferencesProvider.getInt(PREFERENCE_LOCK_ATTEMPTS, 0) fun increaseNumberOfAttempts() { preferencesProvider.putInt(PREFERENCE_LOCK_ATTEMPTS, getNumberOfAttempts().plus(1)) preferencesProvider.putLong(PREFERENCE_LAST_UNLOCK_ATTEMPT_TIMESTAMP, SystemClock.elapsedRealtime()) } fun resetNumberOfAttempts() = preferencesProvider.putInt(PREFERENCE_LOCK_ATTEMPTS, 0) fun getTimeToUnlockLeft(): Long { val timeLocked = 1.5.pow(getNumberOfAttempts()).toLong().times(1000) val lastUnlockAttempt = preferencesProvider.getLong(PREFERENCE_LAST_UNLOCK_ATTEMPT_TIMESTAMP, 0) return max(0, (lastUnlockAttempt + timeLocked) - SystemClock.elapsedRealtime()) } fun initUnlockTimer() { object : CountDownTimer(getTimeToUnlockLeft(), 1000) { override fun onTick(millisUntilFinished: Long) { val hours = TimeUnit.HOURS.convert(millisUntilFinished.plus(1000), TimeUnit.MILLISECONDS) val minutes = if (hours > 0) TimeUnit.MINUTES.convert( TimeUnit.SECONDS.convert( millisUntilFinished.plus(1000), TimeUnit.MILLISECONDS ) - hours.times(3600), TimeUnit.SECONDS ) else TimeUnit.MINUTES.convert(millisUntilFinished.plus(1000), TimeUnit.MILLISECONDS) val seconds = TimeUnit.SECONDS.convert(millisUntilFinished.plus(1000), TimeUnit.MILLISECONDS).rem(60) val timeString = if (hours > 0) String.format("%02d:%02d:%02d", hours, minutes, seconds) else String.format("%02d:%02d", minutes, seconds) _getTimeToUnlockLiveData.postValue(Event(timeString)) } override fun onFinish() { _getFinishedTimeToUnlockLiveData.postValue(Event(true)) } }.start() } private fun loadPinFromOldFormatIfPossible(): String? { var pinString = "" for (i in 1..4) { val pinChar = preferencesProvider.getString(PassCodeActivity.PREFERENCE_PASSCODE_D + i, null) pinChar?.let { pinString += pinChar } } return pinString.ifEmpty { null } } fun setBiometricsState(enabled: Boolean) { preferencesProvider.putBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, enabled) } /** * Ask to the user for retyping the pass code just entered before saving it as the current pass * code. */ private fun requestPassCodeConfirmation() { confirmingPassCode = true firstPasscode = passcodeString.toString() passcodeString = StringBuilder() } /** * Compares pass code retyped by the user in the input fields with the value entered just * before. * * @return 'True' if retyped pass code equals to the entered before. */ private fun confirmPassCode(): Boolean { confirmingPassCode = false return firstPasscode == passcodeString.toString() } }
gpl-2.0
a02ae71576b3dbea4e5cce983e24a838
39.707692
141
0.684996
4.729223
false
false
false
false
google/horologist
media-ui/src/debug/java/com/google/android/horologist/media/ui/components/DefaultMediaDisplayPreview.kt
1
1629
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.components import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.google.android.horologist.compose.tools.WearPreview import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import com.google.android.horologist.media.ui.state.model.MediaUiModel @WearPreview @Composable fun DefaultMediaDisplayPreview() { DefaultMediaDisplay( media = MediaUiModel( id = "id", title = "Song title", artist = "Artist name" ) ) } @Preview( "With long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun DefaultMediaDisplayPreviewLongText() { DefaultMediaDisplay( media = MediaUiModel( id = "id", title = "I Predict That You Look Good In A Riot", artist = "Arctic Monkeys feat Kaiser Chiefs" ) ) }
apache-2.0
f378cf613f86510806955a37f3bef67d
29.735849
78
0.712707
4.209302
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/adapter/MaterialIconsGridAdapter.kt
1
2549
package info.papdt.express.helper.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import info.papdt.express.helper.R import info.papdt.express.helper.model.MaterialIcon import kotlinx.coroutines.* import me.drakeet.multitype.ItemViewBinder import me.drakeet.multitype.MultiTypeAdapter class MaterialIconsGridAdapter : MultiTypeAdapter() { private var keyword: String? = null private var searchJob: Job? = null var callback: (String) -> Unit = {} init { register(MaterialIcon::class.java, IconItemBinder()) } fun update(keyword: String? = null) { this.keyword = keyword searchJob?.cancel() searchJob = CoroutineScope(Dispatchers.IO).launch(Dispatchers.Main) { val result = withContext(Dispatchers.IO) { MaterialIcon.search(keyword) } items = result.map { MaterialIcon(it) } notifyDataSetChanged() } } fun destroy() { searchJob?.cancel() } inner class IconItemBinder : ItemViewBinder<MaterialIcon, IconItemBinder.ViewHolder>() { override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder { return ViewHolder(inflater.inflate(R.layout.grid_item_material_icon, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, item: MaterialIcon) { holder.job?.cancel() holder.job = CoroutineScope(Dispatchers.Main).launch { holder.iconView.setImageBitmap(item.toBitmapAsync(holder.iconSize).await()) } holder.textView.text = item.code } override fun onViewRecycled(holder: ViewHolder) { super.onViewRecycled(holder) holder.job?.cancel() holder.iconView.setImageBitmap(null) } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal var job: Job? = null val iconView: ImageView = itemView.findViewById(R.id.icon_view) val textView: TextView = itemView.findViewById(R.id.text_view) val iconSize: Int = itemView.resources.getDimensionPixelSize(R.dimen.icon_size_medium) init { itemView.setOnClickListener { callback(textView.text.toString()) } } } } }
gpl-3.0
7693d82b5be7ff7834acd514481c87be
29.722892
98
0.650059
4.809434
false
false
false
false
FredJul/TaskGame
TaskGame/src/main/java/net/fred/taskgame/utils/UiUtils.kt
1
3292
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.utils import android.app.Activity import android.support.annotation.StringRes import android.support.design.widget.Snackbar import android.support.v4.app.FragmentTransaction import android.support.v4.content.ContextCompat import android.util.TypedValue import android.widget.TextView import net.fred.taskgame.App import net.fred.taskgame.R object UiUtils { enum class TransitionType { TRANSITION_FADE_IN } enum class MessageType { TYPE_INFO, TYPE_WARN, TYPE_ERROR } fun dpToPixel(dp: Int): Int { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), App.context?.resources?.displayMetrics).toInt() } fun animateTransition(transaction: FragmentTransaction, transitionType: TransitionType) { when (transitionType) { UiUtils.TransitionType.TRANSITION_FADE_IN -> transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out) } } fun showMessage(activity: Activity, @StringRes messageId: Int, type: MessageType = MessageType.TYPE_INFO) { showMessage(activity, activity.getString(messageId), type) } fun showMessage(activity: Activity, message: String, type: MessageType = MessageType.TYPE_INFO) { val snackbar = Snackbar.make(activity.findViewById(R.id.coordinator_layout), message, Snackbar.LENGTH_SHORT) when (type) { UiUtils.MessageType.TYPE_WARN -> { val textView = snackbar.view.findViewById<TextView>(R.id.snackbar_text) textView.setTextColor(ContextCompat.getColor(activity, R.color.warning)) } UiUtils.MessageType.TYPE_ERROR -> { val textView = snackbar.view.findViewById<TextView>(R.id.snackbar_text) textView.setTextColor(ContextCompat.getColor(activity, R.color.error)) } else -> { } } snackbar.show() } fun showWarningMessage(activity: Activity, @StringRes messageId: Int) { showMessage(activity, activity.getString(messageId), MessageType.TYPE_WARN) } fun showWarningMessage(activity: Activity, message: String) { showMessage(activity, message, MessageType.TYPE_WARN) } fun showErrorMessage(activity: Activity, @StringRes messageId: Int) { showMessage(activity, activity.getString(messageId), MessageType.TYPE_ERROR) } fun showErrorMessage(activity: Activity, message: String) { showMessage(activity, message, MessageType.TYPE_ERROR) } }
gpl-3.0
3022ea9b250e4b651d77e15dc79c01d8
36.83908
154
0.702309
4.348745
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UITextField_AdditionalView.kt
1
1154
package com.yy.codex.uikit /** * Created by cuiminghui on 2017/2/7. */ internal fun UITextField.setupPlaceholder() { if (input?.editor?.text?.toString()?.length == 0 && (placeholder != null || attributedPlaceholder != null)) { if (attributedPlaceholder != null) { label.attributedText = attributedPlaceholder } else { placeholder?.let { label.attributedText = NSAttributedString(it, hashMapOf( Pair(NSAttributedString.NSFontAttributeName, label.font), Pair(NSAttributedString.NSForegroundColorAttributeName, UIColor.blackColor.colorWithAlpha(0.3)) )) } } resetLayouts() } } internal fun UITextField.removePlaceholder() { if ((placeholder != null || attributedPlaceholder != null) && label.text == placeholder) { label.text = "" } } internal fun UITextField.resetLeftView() { leftView?.let { addSubview(it) resetLayouts() } } internal fun UITextField.resetRightView() { rightView?.let { addSubview(it) resetLayouts() } }
gpl-3.0
5067f22e6a2883aa605299b082ffbbf2
26.5
119
0.598787
4.561265
false
false
false
false
chrisbanes/tivi
core/analytics/src/main/java/app/tivi/util/TiviAnalytics.kt
1
2029
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.util import android.os.Bundle import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent import javax.inject.Inject import javax.inject.Provider internal class TiviAnalytics @Inject constructor( private val firebaseAnalytics: Provider<FirebaseAnalytics> ) : Analytics { override fun trackScreenView( label: String, route: String?, arguments: Any? ) { try { firebaseAnalytics.get().logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) { param(FirebaseAnalytics.Param.SCREEN_NAME, label) if (route != null) param("screen_route", route) // Expand out the rest of the parameters when { arguments is Bundle -> { for (key in arguments.keySet()) { val value = arguments.getString(key) // We don't want to include the label or route twice if (value == label || value == route) continue param("screen_arg_$key", value ?: "") } } arguments != null -> param("screen_arg", arguments.toString()) } } } catch (t: Throwable) { // Ignore, Firebase might not be setup for this project } } }
apache-2.0
693053bfbb8d9310d3fb2458dbbd6f3f
35.232143
83
0.598817
4.889157
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddElseIntention.kt
2
1201
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsIfExpr import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.parentOfType class AddElseIntention : RsElementBaseIntentionAction<RsIfExpr>() { override fun getText() = "Add else branch to is if statement" override fun getFamilyName(): String = text override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsIfExpr? { val ifStmnt = element.parentOfType<RsIfExpr>() ?: return null return if (ifStmnt.elseBranch == null) ifStmnt else null } override fun invoke(project: Project, editor: Editor, ctx: RsIfExpr) { val ifStmnt = ctx val ifExpr = RsPsiFactory(project).createExpression("${ifStmnt.text}\nelse {}") as RsIfExpr val elseBlockOffset = (ifStmnt.replace(ifExpr) as RsIfExpr).elseBranch?.block?.textOffset ?: return editor.caretModel.moveToOffset(elseBlockOffset + 1) } }
mit
4c8ed445618edd39123944f9d2c8d76f
39.033333
107
0.735221
4.098976
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/common/util/QkChooserTargetService.kt
3
2883
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS 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. * * QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.common.util import android.content.ComponentName import android.content.IntentFilter import android.graphics.drawable.Icon import android.os.Build import android.service.chooser.ChooserTarget import android.service.chooser.ChooserTargetService import androidx.annotation.RequiresApi import androidx.core.os.bundleOf import com.moez.QKSMS.R import com.moez.QKSMS.feature.compose.ComposeActivity import com.moez.QKSMS.injection.appComponent import com.moez.QKSMS.model.Conversation import com.moez.QKSMS.repository.ConversationRepository import com.moez.QKSMS.util.GlideApp import com.moez.QKSMS.util.tryOrNull import javax.inject.Inject @RequiresApi(Build.VERSION_CODES.M) class QkChooserTargetService : ChooserTargetService() { @Inject lateinit var conversationRepo: ConversationRepository override fun onCreate() { appComponent.inject(this) super.onCreate() } override fun onGetChooserTargets(targetActivityName: ComponentName?, matchedFilter: IntentFilter?): List<ChooserTarget> { return conversationRepo.getTopConversations() .take(3) .map(this::createShortcutForConversation) } private fun createShortcutForConversation(conversation: Conversation): ChooserTarget { val icon = when (conversation.recipients.size) { 1 -> { val photoUri = conversation.recipients.first()?.contact?.photoUri val request = GlideApp.with(this) .asBitmap() .circleCrop() .load(photoUri) .submit() val bitmap = tryOrNull(false) { request.get() } if (bitmap != null) Icon.createWithBitmap(bitmap) else Icon.createWithResource(this, R.mipmap.ic_shortcut_person) } else -> Icon.createWithResource(this, R.mipmap.ic_shortcut_people) } val componentName = ComponentName(this, ComposeActivity::class.java) return ChooserTarget(conversation.getTitle(), icon, 1f, componentName, bundleOf("threadId" to conversation.id)) } }
gpl-3.0
89fe4ab3ce27d845e3f46eff0ce326d7
36.454545
125
0.702393
4.48367
false
false
false
false
mbuhot/eskotlin
src/main/kotlin/mbuhot/eskotlin/query/joining/HasChild.kt
1
1125
/* * Copyright (c) 2016. Michael Buhot [email protected] */ package mbuhot.eskotlin.query.joining import org.apache.lucene.search.join.ScoreMode import org.elasticsearch.join.query.HasChildQueryBuilder import org.elasticsearch.index.query.InnerHitBuilder import org.elasticsearch.index.query.QueryBuilder data class HasChildData( var query: QueryBuilder? = null, var type: String? = null, var boost: Float? = null, var score_mode: ScoreMode = ScoreMode.None, var min_children: Int = HasChildQueryBuilder.DEFAULT_MIN_CHILDREN, var max_children: Int = HasChildQueryBuilder.DEFAULT_MAX_CHILDREN, var inner_hits: InnerHitBuilder? = null) { fun query(f: () -> QueryBuilder) { query = f() } } fun has_child(init: HasChildData.() -> Unit): HasChildQueryBuilder { val params = HasChildData().apply(init) return HasChildQueryBuilder(params.type, params.query, params.score_mode).apply { params.boost?.let { boost(it) } minMaxChildren(params.min_children, params.max_children) params.inner_hits?.let { innerHit(it) } } }
mit
3d4fbb7fbcb89d1fe518dc3f7b0571aa
33.121212
85
0.694222
3.725166
false
false
false
false
davidschreiber/MarcoPoloTrash
app/src/main/kotlin/at/droiddave/marcopolotrash/MaintenanceStatus.kt
1
4053
package at.droiddave.marcopolotrash import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import at.droiddave.marcopolotrash.databinding.ActivityCurrentStatusBinding import at.droiddave.marcopolotrash.internal.* import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.android.appKodein import com.github.salomonbrys.kodein.lazyInstance import org.threeten.bp.LocalTime import org.threeten.bp.LocalTime.MIDNIGHT import org.threeten.bp.temporal.ChronoUnit.MINUTES interface MaintenanceStatusContract { interface Presenter : at.droiddave.marcopolotrash.internal.Presenter<View> interface View { fun showClosed(remainingMinutes: Long) fun showOpen(remainingMinutes: Long) } } class MaintenanceStatusPresenter(kodein: () -> Kodein) : MaintenanceStatusContract.Presenter { private val maintenanceTimes: MaintenanceTimeTable by kodein.lazyInstance() private val timeProvider: TimeProvider by kodein.lazyInstance() private var boundView: MaintenanceStatusContract.View? = null override fun bindView(view: MaintenanceStatusContract.View) { boundView = view showMaintenanceStatus(view) } override fun detachView() { boundView = null } private fun showMaintenanceStatus(view: MaintenanceStatusContract.View) { val nextMaintenanceTime = maintenanceTimes.getNextMaintenanceWindow() if (nextMaintenanceTime.isNow()) { view.showClosed(remainingMinutes = minutesUntil(nextMaintenanceTime.end)) } else { view.showOpen(remainingMinutes = minutesUntil(nextMaintenanceTime.from)) } } private fun MaintenanceWindow.isNow() = this.contains(timeProvider.getCurrentTime()) private fun minutesUntil(time: LocalTime): Long { val now = timeProvider.getCurrentTime() // If the given time is earlier in the day, calculate minutes until the time next day. // MIDNIGHT is defined as 00:00 so calculating minutes from now to midnight is a negative number. + // Instead count the minutes to the maximum possible time 23:59 and add 1. return when { now <= time -> now.until(time, MINUTES) else -> now.until(LocalTime.MAX, MINUTES) + 1 + MIDNIGHT.until(time, MINUTES) } } } /** * Shows the current status of the trash chute (open/closed). */ class CurrentStatusActivity : AppCompatActivity(), MaintenanceStatusContract.View { private lateinit var binding: ActivityCurrentStatusBinding // TODO Make the presenter injectable, so we can actually test UI only. private val presenter = MaintenanceStatusPresenter(appKodein) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_current_status) presenter.bindView(this) } override fun showClosed(remainingMinutes: Long) { binding.apply { activityCurrentStatus.setBackgroundColor(getColorCompat(R.color.statusChuteClosed)) mainStatusMessage.setText(R.string.trash_chute_is_closed) secondaryStatusMessage.text = getString(R.string.opens_up_in_minutes, remainingMinutes) statusIcon.setImageResource(R.drawable.ic_cross) } } override fun showOpen(remainingMinutes: Long) { binding.apply { activityCurrentStatus.setBackgroundColor(getColorCompat(R.color.statusChuteOpen)) mainStatusMessage.setText(R.string.trash_chute_is_open) secondaryStatusMessage.text = getString(R.string.still_open_for_minutes, remainingMinutes) statusIcon.setImageResource(R.drawable.ic_check) } } companion object { fun start(context: Context) { val intent = Intent(context, CurrentStatusActivity::class.java) context.startActivity(intent) } } }
apache-2.0
c2b1b96922cc1e8b0231543e93c70e7b
38.359223
107
0.725635
4.478453
false
false
false
false
mehulsbhatt/emv-bertlv
src/main/java/io/github/binaryfoo/decoders/apdu/ResponseCode.kt
1
1490
package io.github.binaryfoo.decoders.apdu import io.github.binaryfoo.res.ClasspathIO import org.apache.commons.io.IOUtils import org.apache.commons.lang.builder.ToStringBuilder import org.apache.commons.lang.builder.ToStringStyle import java.io.IOException import java.io.InputStream import java.util.ArrayList import kotlin.platform.platformStatic /** * Maps the two status words (SW1, SW2) included in an R-APDU to a type and description. */ public data class ResponseCode(val sw1: String, val sw2: String, val `type`: String, val description: String) { public fun getHex(): String { return sw1 + sw2 } class object { private val codes = ClasspathIO.readLines("r-apdu-status.txt").map { line -> ResponseCode(line.substring(0, 2), line.substring(3, 5), line.substring(6, 7), line.substring(8)) } platformStatic public fun lookup(hex: String): ResponseCode { val sw1 = hex.substring(0, 2) val sw2 = hex.substring(2, 4) for (code in codes) { if (sw1 == code.sw1) { if ("XX" == code.sw2) { return code } if ("--" == code.sw2) { continue } if (sw2 == code.sw2) { return code } } } return ResponseCode(sw1, sw2, "", "Unknown") } } }
mit
90b16b584b7d2ad2ba353e58a5a6d744
30.702128
111
0.555705
4.082192
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/ui/schedule/ScheduleAdapter.kt
1
3565
/* * 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.ui.schedule import android.content.Context import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import co.timetableapp.R import co.timetableapp.model.* import co.timetableapp.ui.OnItemClick /** * A RecyclerView adapter for displaying items in the schedule page. */ class ScheduleAdapter( private val context: Context, private val classTimes: List<ClassTime> ) : RecyclerView.Adapter<ScheduleAdapter.ScheduleViewHolder>() { private var onItemClick: OnItemClick? = null fun onItemClick(action: OnItemClick) { onItemClick = action } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ScheduleViewHolder { val itemView = LayoutInflater.from(parent!!.context) .inflate(R.layout.item_general, parent, false) return ScheduleViewHolder(itemView) } override fun onBindViewHolder(holder: ScheduleViewHolder?, position: Int) { val classTime = classTimes[position] val classDetail = ClassDetail.create(context, classTime.classDetailId) val cls = Class.create(context, classDetail.classId) val subject = Subject.create(context, cls.subjectId) val color = Color(subject.colorId) with(holder!!) { colorView.setBackgroundColor( ContextCompat.getColor(context, color.getPrimaryColorResId(context))) subjectText.text = cls.makeName(subject) detailText.text = makeDetailText(classDetail) timesText.text = "${classTime.startTime} - ${classTime.endTime}" } } private fun makeDetailText(classDetail: ClassDetail): String { val builder = StringBuilder() if (classDetail.hasRoom()) { builder.append(classDetail.room) } if (classDetail.hasBuilding()) { if (classDetail.hasRoom()) builder.append(", ") builder.append(classDetail.building) } if (classDetail.hasTeacher()) { if (classDetail.hasRoom() || classDetail.hasBuilding()) builder.append(" \u2022 ") builder.append(classDetail.teacher) } return builder.toString() } override fun getItemCount() = classTimes.size inner class ScheduleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val colorView = itemView.findViewById(R.id.color)!! val subjectText = itemView.findViewById(R.id.text1) as TextView val detailText = itemView.findViewById(R.id.text2) as TextView val timesText = itemView.findViewById(R.id.text3) as TextView init { itemView.findViewById(R.id.text4).visibility = View.GONE itemView.setOnClickListener { onItemClick?.invoke(it, layoutPosition) } } } }
apache-2.0
a70d6113f15c35bd5da01ce7860820da
32.952381
94
0.689201
4.489924
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/performance/SpreadOperatorSpec.kt
1
7808
package io.gitlab.arturbosch.detekt.rules.performance import io.gitlab.arturbosch.detekt.test.KtTestCompiler import io.gitlab.arturbosch.detekt.test.compileAndLint import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class SpreadOperatorSpec : Spek({ val subject by memoized { SpreadOperator() } describe("SpreadOperator rule") { /** This rule has different behaviour depending on whether type resolution is enabled in detekt or not. The two * `context` blocks are there to test behaviour when type resolution is enabled and type resolution is disabled * as different warning messages are shown in each case. */ context("with type resolution") { val wrapper by memoized( factory = { KtTestCompiler.createEnvironment() }, destructor = { it.dispose() } ) val typeResolutionEnabledMessage = "Used in this way a spread operator causes a full copy of the array to" + " be created before calling a method which has a very high performance penalty." it("reports when array copy required using named parameters") { val code = """ val xsArray = intArrayOf(1) fun foo(vararg xs: Int) {} val testVal = foo(xs = *xsArray) """ val actual = subject.compileAndLintWithContext(wrapper.env, code) assertThat(actual).hasSize(1) assertThat(actual.first().message).isEqualTo(typeResolutionEnabledMessage) } it("reports when array copy required without using named parameters") { val code = """ val xsArray = intArrayOf(1) fun foo(vararg xs: Int) {} val testVal = foo(*xsArray) """ val actual = subject.compileAndLintWithContext(wrapper.env, code) assertThat(actual).hasSize(1) assertThat(actual.first().message).isEqualTo(typeResolutionEnabledMessage) } it("doesn't report when using array constructor with spread operator") { val code = """ fun foo(vararg xs: Int) {} val testVal = foo(xs = *intArrayOf(1)) """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } it("doesn't report when using array constructor with spread operator when varargs parameter comes first") { val code = """ fun <T> asList(vararg ts: T, stringValue: String): List<Int> = listOf(1,2,3) val list = asList(-1, 0, *arrayOf(1, 2, 3), 4, stringValue = "5") """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } it("doesn't report when passing values directly") { val code = """ fun <T> asList(vararg ts: T, stringValue: String): List<Int> = listOf(1,2,3) val list = asList(-1, 0, 1, 2, 3, 4, stringValue = "5") """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } it("doesn't report when function doesn't take a vararg parameter") { val code = """ fun test0(strs: Array<String>) { test(strs) } fun test(strs: Array<String>) { strs.forEach { println(it) } } """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } it("doesn't report with expression inside params") { val code = """ fun test0(strs: Array<String>) { test(2*2) } fun test(test : Int) { println(test) } """ assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty() } } context("without type resolution") { val typeResolutionDisabledMessage = "In most cases using a spread operator causes a full copy of the " + "array to be created before calling a method which has a very high performance penalty." it("reports when array copy required using named parameters") { val code = """ val xsArray = intArrayOf(1) fun foo(vararg xs: Int) {} val testVal = foo(xs = *xsArray) """ val actual = subject.compileAndLint(code) assertThat(actual).hasSize(1) assertThat(actual.first().message).isEqualTo(typeResolutionDisabledMessage) } it("reports when array copy required without using named parameters") { val code = """ val xsArray = intArrayOf(1) fun foo(vararg xs: Int) {} val testVal = foo(*xsArray) """ val actual = subject.compileAndLint(code) assertThat(actual).hasSize(1) assertThat(actual.first().message).isEqualTo(typeResolutionDisabledMessage) } it("doesn't report when using array constructor with spread operator") { val code = """ fun foo(vararg xs: Int) {} val testVal = foo(xs = *intArrayOf(1)) """ val actual = subject.compileAndLint(code) assertThat(actual).hasSize(1) assertThat(actual.first().message).isEqualTo(typeResolutionDisabledMessage) } it("doesn't report when using array constructor with spread operator when varargs parameter comes first") { val code = """ fun <T> asList(vararg ts: T, stringValue: String): List<Int> = listOf(1,2,3) val list = asList(-1, 0, *arrayOf(1, 2, 3), 4, stringValue = "5") """ val actual = subject.compileAndLint(code) assertThat(actual).hasSize(1) assertThat(actual.first().message).isEqualTo(typeResolutionDisabledMessage) } it("doesn't report when passing values directly") { val code = """ fun <T> asList(vararg ts: T, stringValue: String): List<Int> = listOf(1,2,3) val list = asList(-1, 0, 1, 2, 3, 4, stringValue = "5") """ assertThat(subject.compileAndLint(code)).isEmpty() } it("doesn't report when function doesn't take a vararg parameter") { val code = """ fun test0(strs: Array<String>) { test(strs) } fun test(strs: Array<String>) { strs.forEach { println(it) } } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("doesn't report with expression inside params") { val code = """ fun test0(strs: Array<String>) { test(2*2) } fun test(test : Int) { println(test) } """ assertThat(subject.compileAndLint(code)).isEmpty() } } } })
apache-2.0
4674f9a5e9269908aaca5612573064ff
42.620112
120
0.522797
5.236754
false
true
false
false
kropp/intellij-makefile
src/main/kotlin/name/kropp/intellij/makefile/toolWindow/MakeToolWindowFactory.kt
1
3848
package name.kropp.intellij.makefile.toolWindow import com.intellij.execution.impl.* import com.intellij.ide.* import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.CommonDataKeys.* import com.intellij.openapi.project.* import com.intellij.openapi.ui.* import com.intellij.openapi.wm.* import com.intellij.psi.search.* import com.intellij.ui.* import com.intellij.ui.content.impl.* import com.intellij.ui.treeStructure.* import com.intellij.util.ui.tree.* import name.kropp.intellij.makefile.* import java.awt.* import java.awt.event.* import java.awt.event.MouseEvent.* import javax.swing.* import javax.swing.tree.* class MakeToolWindowFactory : ToolWindowFactory { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { toolWindow.title = "make" val contentManager = toolWindow.contentManager val options = MakefileToolWindowOptions(project) DumbService.getInstance(project).runWhenSmart { val model = DefaultTreeModel(options.getRootNode()) val panel = SimpleToolWindowPanel(true) val tree = object : Tree(model), DataProvider { override fun getData(dataId: String): Any? { if (PSI_ELEMENT.`is`(dataId)) { val selectedNodes = getSelectedNodes(MakefileTargetNode::class.java, {true}) if (selectedNodes.any()) { val selected = selectedNodes.first() return MakefileTargetIndex.get(selected.name, project, GlobalSearchScope.fileScope(selected.parent.psiFile)).firstOrNull() } } return null } }.apply { cellRenderer = MakefileCellRenderer() selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION isRootVisible = false showsRootHandles = true } TreeUtil.installActions(tree) TreeSpeedSearch(tree) panel.add(ScrollPaneFactory.createScrollPane(tree)) val toolBarPanel = JPanel(GridLayout()) val runManager = RunManagerImpl.getInstanceImpl(project) val autoScrollHandler = object : AutoScrollToSourceHandler() { override fun isAutoScrollMode(): Boolean = options.autoScrollToSource override fun setAutoScrollMode(state: Boolean) { options.autoScrollToSource = state } } autoScrollHandler.install(tree) val runTargetAction = MakefileToolWindowRunTargetAction(tree, project, runManager) runTargetAction.registerCustomShortcutSet(CustomShortcutSet(KeyEvent.VK_ENTER), panel) tree.addMouseListener(object : MouseAdapter() { override fun mousePressed(e: MouseEvent?) { if (e?.clickCount == 2 && e.button == BUTTON1) { ActionManager.getInstance().tryToExecute(runTargetAction, e, tree, "", true) } } }) val goToTargetAction = MakefileToolWindowGoToTargetAction(tree, project) goToTargetAction.registerCustomShortcutSet(CustomShortcutSet(KeyEvent.VK_F4), panel) val group = DefaultActionGroup() group.add(runTargetAction) group.addSeparator() val treeExpander = DefaultTreeExpander(tree) group.add(CommonActionsManager.getInstance().createExpandAllAction(treeExpander, tree)) group.add(CommonActionsManager.getInstance().createCollapseAllAction(treeExpander, tree)) group.addAction(MakefileToolWindowAutoscrollToSourceAction(options, autoScrollHandler, tree)) group.addSeparator() group.addAction(MakefileToolWindowSortAlphabeticallyAction(options, model)) group.addAction(MakefileToolWindowShowSpecialAction(options, model)) toolBarPanel.add(ActionManager.getInstance().createActionToolbar("MakeToolWindowToolbar", group, true).component) panel.toolbar = toolBarPanel contentManager.addContent(ContentImpl(panel, "", true)) } } }
mit
1c453bbf6f372161022020a6da37a3e8
37.868687
136
0.722453
4.858586
false
false
false
false
aCoder2013/general
general-gossip/src/main/java/com/song/general/gossip/net/handler/GossipDigestAck2MessageHandler.kt
1
903
package com.song.general.gossip.net.handler import com.song.general.gossip.Gossip import com.song.general.gossip.message.GossipDigestAck2Message import com.song.general.gossip.net.Message import org.slf4j.LoggerFactory /** * Created by song on 2017/9/9. */ class GossipDigestAck2MessageHandler(g: Gossip) : AbstractMessageHandler(g) { override fun handleMessage(message: Message) { val from = message.from val localSocketAddress = gossip.localSocketAddress if (localSocketAddress == from) { logger.info("Ignore ack2 message from itself.") return } val gossipDigestAck2Message = message.payload as GossipDigestAck2Message gossip.applyStateLocally(gossipDigestAck2Message.endpointStateMap) } companion object { private val logger = LoggerFactory.getLogger(GossipDigestAck2MessageHandler::class.java) } }
apache-2.0
f982a3bc6c4e37e5461419a7798cd4de
32.481481
96
0.732004
4.085973
false
false
false
false
jrenner/kotlin-algorithms-ds
src/datastructs/fundamental/queue/ArrayQueue.kt
1
3015
package datastructs.fundamental.queue import util.NonNullArrayIterator import java.util.ArrayList /** FIFO Queue with a backing array */ public class ArrayQueue<T> : Queue<T> { val DEFAULT_INIT_CAPACITY = 8 val RESIZE_MULTIPLE = 2f var items = Array<Any?>(DEFAULT_INIT_CAPACITY, { null } ) as Array<T?> var first = 0 var last = 0 var itemCount = 0 override fun iterator(): Iterator<T> { return NonNullArrayIterator(items) } override fun push(item: T) { if (items[last] != null) last++ if (last >= items.size) { resize((itemCount * RESIZE_MULTIPLE).toInt()) } if (items[last] != null) last++ items[last] = item itemCount++ } val SHRINK_THRESHOLD = 0.25f override fun pop(): T { val item = items[first] items[first] = null first++ itemCount-- val threshold = (items.size * SHRINK_THRESHOLD).toInt() if (itemCount < threshold && itemCount >= DEFAULT_INIT_CAPACITY) { resize((itemCount * RESIZE_MULTIPLE).toInt()) } return item!! } override fun clear() { first = 0 last = 0 for (i in items.indices) { items[i] = null } itemCount = 0 } override fun isEmpty(): Boolean { return itemCount == 0 } override fun size(): Int { return itemCount } fun capacity(): Int { return items.size } private fun resize(newSize: Int) { assert(newSize > 0, "newSize must be greater than zero: $newSize") val newArray = Array<Any?>(newSize, { null } ) as Array<T?> var i = 0 for (item in items) { if (item != null) newArray[i++] = item } items = newArray for (j in items.indices) { if (items[i] != null) { first = i break } } for (j in items.lastIndex downTo 0) { if (items[i] != null) { last = i break } } } override fun details() { println("ArrayQueue, size: ${size()}, capacity: ${capacity()}, first: $first, last: $last") var i = 0 for (item in items) { println("\t[${i++}]: $item") } } override fun equals(other: Any?): Boolean { if (other is Queue<*>) { val myList = this.toList() val otherList = other.toList() if (myList.size != otherList.size) return false for (i in myList.indices) { if (myList[i] != otherList[i]) { return false } } return true } return false } override fun toList(): List<out T> { val list = ArrayList<T>() for (item in items) { if (item != null) { list.add(item) } } return list.toList() } }
apache-2.0
9c914400c80b562362892c4990444d8d
24.336134
99
0.492537
4.205021
false
false
false
false