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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bropane/Job-Seer | app/src/main/java/com/taylorsloan/jobseer/domain/job/GetJobs.kt | 1 | 1097 | package com.taylorsloan.jobseer.domain.job
import com.taylorsloan.jobseer.data.common.model.DataResult
import com.taylorsloan.jobseer.data.job.repo.JobRepository
import com.taylorsloan.jobseer.domain.BaseUseCase
import com.taylorsloan.jobseer.domain.DomainModuleImpl
import com.taylorsloan.jobseer.domain.job.models.Job
import io.reactivex.Flowable
import javax.inject.Inject
/**
* Created by taylo on 10/29/2017.
*/
class GetJobs(var page: Int = 0,
var title: String? = null,
var description: String? = null,
var location: String? = null,
var lat: Double? = null,
var long: Double? = null,
var fullTime: Boolean? = null) : BaseUseCase<Flowable<DataResult<List<Job>>>> {
@Inject
lateinit var jobRepo : JobRepository
init {
DomainModuleImpl.dataComponent().inject(this)
}
override fun execute(): Flowable<DataResult<List<Job>>> {
return jobRepo.getJobs(description, location, lat, long, fullTime)
}
fun getMore(){
jobRepo.getMoreJobs(page = page)
}
} | mit | 8518ef2a20e541c142aae58cb1a27562 | 29.5 | 93 | 0.674567 | 3.960289 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/TemporaryContentProvider.kt | 1 | 9025 | package io.oversec.one.crypto
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.*
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import io.oversec.one.crypto.sym.SymUtil
import io.oversec.one.crypto.symbase.KeyUtil
import roboguice.util.Ln
import java.io.*
import java.lang.IllegalArgumentException
import java.util.ArrayList
import java.util.HashMap
class TemporaryContentProvider : ContentProvider() {
internal class Entry(val mimetype: String, val ttl_seconds: Int, val tag: String?) {
var data: ByteArray? = null
}
@Synchronized
@Throws(FileNotFoundException::class)
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
val token = getTokenFromUri(uri) ?: throw IllegalArgumentException(uri.toString())
try {
if ("w" == mode) {
val entry = mEntries[token] ?: throw FileNotFoundException("unprepared token!")
if (entry.data != null) {
throw FileNotFoundException("data has already been provided!")
}
val pipe = ParcelFileDescriptor.createPipe()
val pfdRead = pipe[0]
val pfdWrite = pipe[1]
val `is` = ParcelFileDescriptor.AutoCloseInputStream(pfdRead)
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
TransferThreadIn(context, `is`, token).start()
return pfdWrite
} else if ("r" == mode) {
val entry =
mEntries[token] ?: throw FileNotFoundException("unknown or expired token!")
if (entry.data == null) {
throw FileNotFoundException("data not yet provided token!")
}
val pipe = ParcelFileDescriptor.createPipe()
val pfdRead = pipe[0]
val pfdWrite = pipe[1]
val os = ParcelFileDescriptor.AutoCloseOutputStream(pfdWrite)
TransferThreadOut(os, entry.data!!).start()
return pfdRead
}
} catch (ex: IOException) {
throw FileNotFoundException(ex.message)
}
return null
}
class Recv : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (ACTION_EXPIRE_BUFFER == intent.action) {
val token = intent.getStringExtra(EXTRA_TOKEN)
expire(token)
}
}
}
internal inner class TransferThreadIn(
private val mCtx: Context,
private val mIn: InputStream,
private val mToken: String
) : Thread("TTI") {
init {
isDaemon = true
}
override fun run() {
val baos = ByteArrayOutputStream()
try {
baos.use {
mIn.copyTo(baos, 4096)
}
val entry = mEntries[mToken]
if (entry == null) {
Ln.d(
"TCPR Entry for token %s not found, somebody has re-prepared another content with the same tag, ignoring content input stream",
mToken
)
} else {
entry.data = baos.toByteArray()
val ttlSeconds = mEntries[mToken]!!.ttl_seconds
val am = mCtx.getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.set(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + ttlSeconds * 1000,
buildPendingIntent(mCtx, mToken)
)
if (!mReceiverRegistered) {
val filter = IntentFilter(ACTION_EXPIRE_BUFFER)
mCtx.applicationContext.registerReceiver(Recv(), filter)
mReceiverRegistered = true
}
}
} catch (e: IOException) {
try {
baos.close()
} catch (ignored: IOException) {
}
} finally {
try {
mIn.close()
} catch (ignored: IOException) {
}
}
}
}
internal inner class TransferThreadOut(private val mOut: OutputStream, private val mData: ByteArray) :
Thread("TTO") {
init {
isDaemon = true
}
override fun run() {
//synchronized (mData) //hmm, this is dead-locking in case multiple clients access it
run {
val mIn = ByteArrayInputStream(mData)
try {
mOut.use {
mIn.copyTo(mOut, 4096)
}
} catch (ignored: IOException) {
//ignoring possible exception on closing
}
}
}
}
override fun onCreate(): Boolean {
return false
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
throw UnsupportedOperationException("query not supported")
}
override fun getType(uri: Uri): String? {
val token = getTokenFromUri(uri)
val entry = mEntries[token]
return entry?.mimetype
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw UnsupportedOperationException("insert not supported")
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("delete not supported")
}
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
): Int {
throw UnsupportedOperationException("update not supported")
}
companion object {
const val TTL_5_MINUTES = 60 * 5
const val TTL_1_HOUR = 60 * 60
const val TAG_ENCRYPTED_IMAGE = "ENCRYPTED_IMAGE"
const val TAG_CAMERA_SHOT = "CAMERA_SHOT"
const val TAG_DECRYPTED_IMAGE = "DECRYPTED_IMAGE"
private const val ACTION_EXPIRE_BUFFER = "OVERSEC_ACTION_EXPIRE_BUFFER"
private const val EXTRA_TOKEN = "token"
private val mEntries = HashMap<String, Entry>()
private var mReceiverRegistered: Boolean = false
@Synchronized
fun prepare(ctx: Context, mimetype: String, ttl_seconds: Int, tag: String?): Uri {
Ln.d("TCPR prepare tag=%s", tag)
//delete all existing entries with the same tag
if (tag != null) {
val toRemove = ArrayList<String>()
for ((key, value) in mEntries) {
if (tag == value.tag) {
toRemove.add(key)
}
}
for (key in toRemove) {
expire(key)
}
}
val token = createRandomToken()
Ln.d("TCPR prepared tag=%s token=%s", tag, token)
mEntries[token] = Entry(mimetype, ttl_seconds, tag)
val authority = ctx.resources.getString(R.string.tempcontent_authority)
return Uri.parse("content://$authority/$token")
}
private fun createRandomToken(): String {
return SymUtil.byteArrayToHex(KeyUtil.getRandomBytes(16))
}
@Synchronized
fun deleteUri(uri: Uri?) {
val token = getTokenFromUri(uri ?: return)
token?.let{ expire(it) }
}
private fun getTokenFromUri(uri: Uri): String? {
val segs = uri.pathSegments
return if (segs.size >= 1) {
segs[0]
} else null
}
private fun expire(token: String) {
val entry = mEntries[token]
if (entry?.data != null) {
synchronized(entry.data!!) {
KeyUtil.erase(entry.data)
entry.data = null
}
}
Ln.d("TCPR expired entry token=%s", token)
mEntries.remove(token)
}
private fun buildPendingIntent(ctx: Context, token: String): PendingIntent {
val i = Intent()
//i.setClass(ctx, TemporaryContentProvider.class); //doesn't work with dynamically registered receivers
i.action = ACTION_EXPIRE_BUFFER
i.putExtra(EXTRA_TOKEN, token)
val flags = 0//PendingIntent.FLAG_ONE_SHOT
// | PendingIntent.FLAG_CANCEL_CURRENT
// | PendingIntent.FLAG_IMMUTABLE;
return PendingIntent.getBroadcast(
ctx, 0,
i, flags
)
}
}
}
| gpl-3.0 | 399779f3cd2c6833511f3086c9f9563e | 29.697279 | 151 | 0.529751 | 5.016676 | false | false | false | false |
tmarsteel/kotlin-prolog | stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/builtins.kt | 1 | 4969 | package com.github.prologdb.runtime.stdlib
import com.github.prologdb.async.LazySequenceBuilder
import com.github.prologdb.runtime.ArgumentTypeError
import com.github.prologdb.runtime.ClauseIndicator
import com.github.prologdb.runtime.PrologException
import com.github.prologdb.runtime.PrologInternalError
import com.github.prologdb.runtime.PrologInvocationContractViolationException
import com.github.prologdb.runtime.builtin.getInvocationStackFrame
import com.github.prologdb.runtime.builtin.prologSourceInformation
import com.github.prologdb.runtime.exception.PrologStackTraceElement
import com.github.prologdb.runtime.proofsearch.PrologCallableFulfill
import com.github.prologdb.runtime.proofsearch.ProofSearchContext
import com.github.prologdb.runtime.proofsearch.Rule
import com.github.prologdb.runtime.query.PredicateInvocationQuery
import com.github.prologdb.runtime.query.Query
import com.github.prologdb.runtime.term.CompoundTerm
import com.github.prologdb.runtime.term.Term
import com.github.prologdb.runtime.term.Variable
import com.github.prologdb.runtime.unification.Unification
internal val A = Variable("A")
internal val B = Variable("B")
internal val C = Variable("C")
internal val X = Variable("X")
/**
* [Variable]s to be used in the "prolog"-ish representation of builtins. E.g.
* when defining the builtin `string_chars(A, B)`, `A` and `B` are obtained from
* this list.
*/
private val builtinArgumentVariables = arrayOf(
Variable("_Arg0"),
Variable("_Arg1"),
Variable("_Arg2"),
Variable("_Arg3"),
Variable("_Arg4"),
Variable("_Arg5"),
Variable("_Arg6"),
Variable("_Arg7"),
Variable("_Arg8"),
Variable("_Arg9")
)
/**
* This query is used as a placeholder for builtins where an instance of [Query] is required
* but the actual query never gets invoked because kotlin code implements the builtin.
*/
private val nativeCodeQuery = PredicateInvocationQuery(CompoundTerm("__nativeCode", emptyArray()))
typealias NativePredicateFulfill = suspend LazySequenceBuilder<Unification>.(TypedPredicateArguments, ProofSearchContext) -> Unification?
class NativeCodeRule(name: String, arity: Int, definedAt: StackTraceElement, code: NativePredicateFulfill) : Rule(
CompoundTerm(name, builtinArgumentVariables.sliceArray(0 until arity)),
nativeCodeQuery
) {
private val invocationStackFrame = definedAt
private val stringRepresentation = """$head :- __nativeCode("${definedAt.fileName}:${definedAt.lineNumber}")"""
private val indicator = ClauseIndicator.of(head)
private val builtinStackFrame = PrologStackTraceElement(
head,
invocationStackFrame.prologSourceInformation,
null,
"$indicator native implementation (${definedAt.fileName}:${definedAt.lineNumber})"
)
override val fulfill: PrologCallableFulfill = { arguments, context ->
if (head.arity == arguments.size) {
val typeSafeArguments = TypedPredicateArguments(indicator, arguments)
try {
code(this, typeSafeArguments, context)
} catch (ex: PrologException) {
if (ex is PrologInvocationContractViolationException && ex.indicator == null) {
ex.fillIndicator(indicator)
}
ex.addPrologStackFrame(builtinStackFrame)
throw ex
} catch (ex: Throwable) {
val newEx = PrologInternalError(ex.message ?: "", ex)
newEx.addPrologStackFrame(builtinStackFrame)
throw newEx
}
} else null
}
override fun toString() = stringRepresentation
}
fun nativeRule(name: String, arity: Int, code: NativePredicateFulfill): NativeCodeRule {
val definedAt = getInvocationStackFrame()
return NativeCodeRule(name, arity, definedAt, code)
}
fun nativeRule(name: String, arity: Int, definedAt: StackTraceElement, code: NativePredicateFulfill): NativeCodeRule {
return NativeCodeRule(name, arity, definedAt, code)
}
inline fun <reified From : Term, reified To : Term> nativeConversionRule(name: String, crossinline aToB: (From) -> To, crossinline bToA: (To) -> From) : NativeCodeRule = nativeRule(name, 2, getInvocationStackFrame()) { args, ctxt ->
val inputForA = args[0]
val inputForB = args[1]
if (inputForA !is Variable) {
if (inputForA !is From) {
throw ArgumentTypeError(0, inputForA, From::class.java)
}
val convertedB = aToB(inputForA)
return@nativeRule convertedB.unify(inputForB, ctxt.randomVariableScope)
}
if (inputForB !is Variable) {
if (inputForB !is To) {
throw ArgumentTypeError(1, inputForB, To::class.java)
}
val convertedA = bToA(inputForB)
return@nativeRule inputForA.unify(convertedA, ctxt.randomVariableScope)
}
throw PrologInvocationContractViolationException("At least one argument to ${args.indicator} must be instantiated")
} | mit | 4a2e0e646298461550fbfe74fc5e0000 | 39.406504 | 232 | 0.720064 | 4.309627 | false | false | false | false |
encodeering/conflate | modules/conflate-api/src/main/kotlin/com/encodeering/conflate/experimental/api/Action.kt | 1 | 2196 | package com.encodeering.conflate.experimental.api
/**
* An action usually describes an intent that something should happen and may or may not cause other intents to be raised
* along the way to the storage, which is usually managed by chained middleware components.
*
* Intents should be designed with immutability in mind, or at least be effectively final.
* Even though mutable properties are acceptable for cases with no adequate default value,
* they should be used sparingly and never be mutated, as there will be no implicit synchronization mechanism implemented.
* It's further recommended to use serializable payloads, as they make the intents more reasonable and debug friendly.
*
* As a short reminder:
*
* - Intents should *never* be mutated
* - Intents interacting with the store *must* be serializable, but those being processed by middleware components only *are not* required to be fully serializable
*
* ### Official documentation:
*
* - Actions are payloads of information that send data from your application to your store.
* They are the only source of information for the store. [http://redux.js.org/docs/basics/Actions.html]
*
* - As with state, serializable actions enable several of Redux's defining features, such as time travel debugging, and recording and replaying actions. [http://redux.js.org/docs/faq/Actions.html#actions]
*
* ### Sample
*
* #### Intent with default parameters
* ```
* data class Toast (
* val message : String,
* val duration : Int = LENGTH_SHORT
* ) : Action
*
* dispatch (Toast ("welcome $user"))
* ```
*
* #### Intent with a UI toggle to display a progress indicator
*
* ```
* data class SearchAccommodation (
* val city : String, // title and query parameter
* val accommodations : List<String> = emptyList (), // result
* val searching : Boolean = true // progress indicator
* ) : Action
*
* val search = SearchAccommodation ("Berlin")
* dispatch (search)
* dispatch (search.copy (accommodations = listOf ("Hotel XYZ"), searching = false))
* ```
*
* @author Michael Clausen - [email protected]
*/
interface Action | apache-2.0 | 35853d11cf5ee7d05578ca94d5cade22 | 41.25 | 205 | 0.702641 | 4.280702 | false | false | false | false |
EndlessCodeGroup/BukkitGradle | src/main/kotlin/dependencies/DependenciesExtensions.kt | 1 | 2696 | package ru.endlesscode.bukkitgradle.dependencies
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_AIKAR
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_CODEMC
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_DMULLOY2
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_JITPACK
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_MD5
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_PAPERMC
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_PLACEHOLDERAPI
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_SK89Q
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.URL_SPIGOT
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.addRepo
import ru.endlesscode.bukkitgradle.dependencies.Dependencies.api
public fun RepositoryHandler.spigot(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("Spigot", URL_SPIGOT, configure)
}
public fun RepositoryHandler.sk89q(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("sk89q", URL_SK89Q, configure)
}
public fun RepositoryHandler.papermc(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("PaperMC", URL_PAPERMC, configure)
}
public fun RepositoryHandler.dmulloy2(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("dmulloy2", URL_DMULLOY2, configure)
}
public fun RepositoryHandler.md5(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("md5", URL_MD5, configure)
}
public fun RepositoryHandler.jitpack(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("jitpack", URL_JITPACK, configure)
}
public fun RepositoryHandler.placeholderApi(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("PlaceholderAPI", URL_PLACEHOLDERAPI, configure)
}
public fun RepositoryHandler.aikar(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("aikar", URL_AIKAR, configure)
}
public fun RepositoryHandler.codemc(configure: MavenArtifactRepository.() -> Unit = {}) {
addRepo("codemc", URL_CODEMC, configure)
}
public val DependencyHandler.spigot: String
get() = api("org.spigotmc", "spigot", "mavenLocal")
public val DependencyHandler.spigotApi: String
get() = api("org.spigotmc", "spigot-api", "spigot")
public val DependencyHandler.bukkitApi: String
get() = api("org.bukkit", "bukkit", "spigot")
public val DependencyHandler.paperApi: String
get() = api("com.destroystokyo.paper", "paper-api", "papermc")
| mit | a6ffd5911fee3626ef6cf8f9c1be1515 | 41.125 | 97 | 0.78227 | 3.868006 | false | true | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/Constants.kt | 1 | 2956 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.sync
/**
* Account type id
*/
const val ACCOUNT_TYPE = "org.xwiki.android.sync"
const val defaultLearnMoreLink = "https://xwiki.org"
/**
* Account name
*/
const val ACCOUNT_NAME = "XWiki"
const val USERDATA_SERVER = "XWIKI_SERVER"
const val ADD_NEW_ACCOUNT = "ADD_NEW_ACCOUNT"
const val REQUEST_ACCESS_TOKEN = 1
const val REQUEST_NEW_ACCOUNT = 2
private fun prepareBaseUrlForOIDCUrlCreating(baseServerUrl: String): String = if (baseServerUrl.endsWith("/")) {
baseServerUrl.substring(0, baseServerUrl.length - 1)
} else {
baseServerUrl
}
fun buildOIDCTokenServerUrl(baseServerUrl: String): String = "${prepareBaseUrlForOIDCUrlCreating(baseServerUrl)}/oidc/token"
fun buildOIDCAuthorizationServerUrl(baseServerUrl: String): String = "${prepareBaseUrlForOIDCUrlCreating(baseServerUrl)}/oidc/authorization"
const val REDIRECT_URI = "xwiki://oidc"
const val PAGE_SIZE = 30
const val XWIKI_DEFAULT_SERVER_ADDRESS = "https://www.xwiki.org/xwiki"
const val ACCESS_TOKEN = "access_token"
const val URL_FIELD = "url"
/**
* Auth token types
*/
const val AUTHTOKEN_TYPE_READ_ONLY = "Read only"
const val AUTHTOKEN_TYPE_READ_ONLY_LABEL = "Read only access to an XWiki account"
const val AUTHTOKEN_TYPE_FULL_ACCESS = "Full access"
const val AUTHTOKEN_TYPE_FULL_ACCESS_LABEL = "Full access to an XWiki account"
/**
* limit the number of users synchronizing from server.
*/
const val LIMIT_MAX_SYNC_USERS = 10000
/**
* SyncType
* 0: no sync, 1: all users, 2: sync groups
*/
const val SYNC_TYPE_ALL_USERS = 0
const val SYNC_TYPE_SELECTED_GROUPS = 1
const val SYNC_TYPE_NO_NEED_SYNC = 2
/**
* sync maker
*/
const val SYNC_MARKER_KEY = "org.xwiki.android.sync.marker"
/**
* sharePreference
*/
const val PACKAGE_LIST = "packageList"
const val SERVER_ADDRESS = "requestUrl"
const val SELECTED_GROUPS = "SelectGroups"
const val SYNC_TYPE = "SyncType"
const val COOKIE = "Cookie"
/**
* sync interval
*/
const val SYNC_INTERVAL = 1800 //half an hour
/**
* @version $Id: b5f3c64375bf824faab782e804c73de41ce33a4b $
*/ | lgpl-2.1 | bcd51add2c5c831b7d403094ddbddb05 | 28.57 | 140 | 0.738498 | 3.58303 | false | false | false | false |
rodrigo196/kotlin-marvel-api-client | app/src/main/java/br/com/bulgasoftwares/feedreader/model/bussines/MarvelBO.kt | 1 | 1473 | package br.com.bulgasoftwares.feedreader.model.bussines
import android.util.Log
import br.com.bulgasoftwares.feedreader.model.bean.Response
import br.com.bulgasoftwares.feedreader.model.network.RestApi
import rx.Observable
import javax.inject.Singleton
@Singleton
class MarvelBO(val api: RestApi) {
fun getCharacters(after: String, limit: String = "30"): Observable<Response> {
return Observable.create {
subscriber ->
Log.d("MarvelBO", "Getting after $after + limit $limit")
val callResponse = api.getCharacters(after, limit)
val response = callResponse.execute()
if (response.isSuccessful) {
val dataResponse = response.body()
subscriber.onNext(dataResponse)
subscriber.onCompleted()
} else {
subscriber.onError(Throwable(response.message()))
}
}
}
fun getCharacter(characterId: String): Observable<Response> {
return Observable.create {
subscriber ->
val callResponse = api.getCharacter(characterId)
val response = callResponse.execute()
if (response.isSuccessful) {
val dataResponse = response.body()
subscriber.onNext(dataResponse)
subscriber.onCompleted()
} else {
subscriber.onError(Throwable(response.message()))
}
}
}
} | apache-2.0 | 89a442c8e1b17ef8a7c86453e1b9e5c2 | 27.901961 | 82 | 0.606246 | 4.691083 | false | false | false | false |
VerifAPS/verifaps-lib | ide/src/main/kotlin/edu/kit/iti/formal/automation/ide/editors/st.kt | 1 | 13831 | package edu.kit.iti.formal.automation.ide.editors
import edu.kit.iti.formal.automation.IEC61131Facade
import edu.kit.iti.formal.automation.ide.*
import edu.kit.iti.formal.automation.ide.tools.OutlineService
import edu.kit.iti.formal.automation.ide.tools.OverviewStructureNode
import edu.kit.iti.formal.automation.ide.tools.StructureData
import edu.kit.iti.formal.automation.ide.tools.StructureTypeIcon
import edu.kit.iti.formal.automation.parser.IEC61131Lexer
import edu.kit.iti.formal.automation.parser.IEC61131Lexer.*
import edu.kit.iti.formal.automation.parser.SyntaxErrorReporter
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.st.util.AstVisitor
import edu.kit.iti.formal.automation.ide.BaseLanguageSupport
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.Lexer
import org.fife.io.DocumentReader
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea
import org.fife.ui.rsyntaxtextarea.Style
import org.fife.ui.rsyntaxtextarea.SyntaxScheme
import org.fife.ui.rsyntaxtextarea.folding.Fold
import org.fife.ui.rsyntaxtextarea.folding.FoldParser
import org.fife.ui.rsyntaxtextarea.folding.FoldType
import org.fife.ui.rsyntaxtextarea.parser.*
import java.util.*
import javax.swing.Icon
import javax.swing.text.BadLocationException
class IECLanguageSupport(lookup: Lookup) : BaseLanguageSupport() {
override fun createParser(textArea: CodeEditor, lookup: Lookup): Parser? = STChecker(textArea, lookup)
override val extension: Collection<String> = setOf("st", "iec", "iec61131")
override val mimeType = "text/iec61131"
override val syntaxScheme: SyntaxScheme = IEC61131SyntaxScheme(lookup)
override val antlrLexerFactory: AntlrLexerFactory
get() = object : AntlrLexerFactory {
override fun create(code: String): Lexer =
IEC61131Lexer(CharStreams.fromString(code))
}
}
class IEC61131SyntaxScheme(lookup: Lookup) : SyntaxScheme(true) {
val colors: Colors by lookup.with()
private val STRUCTURAL_KEYWORDS = setOf(
PROGRAM,
INITIAL_STEP,
TRANSITION,
END_TRANSITION,
END_VAR,
VAR,
VAR_ACCESS,
VAR_CONFIG,
VAR_EXTERNAL,
VAR_GLOBAL,
VAR_INPUT,
VAR_IN_OUT,
VAR_OUTPUT,
VAR_TEMP,
END_PROGRAM,
END_ACTION,
END_CASE,
END_CLASS,
END_CONFIGURATION,
END_FUNCTION_BLOCK,
FUNCTION_BLOCK,
IEC61131Lexer.FUNCTION,
END_FUNCTION,
END_INTERFACE,
END_METHOD,
INTERFACE,
METHOD,
END_NAMESPACE,
NAMESPACE,
END_STEP,
STEP,
TYPE,
END_TYPE,
STRUCT, END_STRUCT,
CONFIGURATION, END_CONFIGURATION,
ACTION, END_ACTION)
private val DATATYPE_KEYWORD = setOf(
ANY_BIT,
ARRAY,
STRING,
WSTRING,
ANY_DATE,
ANY_INT,
ANY_NUM,
ANY_REAL,
REAL,
LREAL,
INT,
DINT,
UDINT,
SINT,
USINT,
ULINT,
DINT,
LINT,
DATE,
DATE_AND_TIME,
TIME,
WORD,
LWORD,
DWORD,
BOOL)
private val LITERALS = setOf(
DATE_LITERAL,
INTEGER_LITERAL,
BITS_LITERAL,
CAST_LITERAL,
DIRECT_VARIABLE_LITERAL,
REAL_LITERAL,
STRING_LITERAL,
TOD_LITERAL,
TIME_LITERAL,
WSTRING_LITERAL
)
val CONTROL_KEYWORDS = setOf(
IF, ELSE, ELSEIF, FOR, END_FOR,
WHILE, END_WHILE, REPEAT, END_REPEAT,
END_IF, DO, THEN, UNTIL, TO,
WITH, CASE, END_CASE, OF
)
val OPERATORS = setOf(
NOT, AND, OR, MOD, DIV, MULT, MINUS, EQUALS, NOT_EQUALS,
GREATER_EQUALS, GREATER_THAN, LESS_EQUALS, LESS_THAN,
IL_ADD, IL_ANDN, IL_CAL, IL_CALC, IL_CALCN, IL_CD, IL_CLK,
IL_CU, IL_DIV, IL_EQ, IL_GE, IL_GT, IL_IN, IL_JMP, IL_JMPC, IL_JMPCN, IL_LD, IL_LDN, IL_LE, IL_LT,
IL_MOD, IL_MUL, IL_NE, IL_NOT, IL_ORN, IL_PT, IL_PV, IL_R1, IL_R, IL_RET, IL_RETC, IL_RETCN,
IL_S1, IL_S, IL_ST, IL_STN, IL_STQ, IL_SUB, IL_XORN, IL_OR
)
override fun getStyle(index: Int): Style {
return when (index) {
in STRUCTURAL_KEYWORDS -> colors.structural
in CONTROL_KEYWORDS -> colors.control
in LITERALS -> colors.literal
in DATATYPE_KEYWORD -> colors.types
in OPERATORS -> colors.operators
IDENTIFIER -> colors.identifier
COMMENT -> colors.comment
LINE_COMMENT -> colors.comment
ERROR_CHAR -> colors.error
else -> colors.default
}
}
}
class STChecker(val codeEditor: CodeEditor, val lookup: Lookup) : AbstractParser() {
val result = DefaultParseResult(this)
override fun parse(doc: RSyntaxDocument, style: String): ParseResult {
result.clearNotices()
val input = DocumentReader(doc)
val stream = CharStreams.fromReader(input, codeEditor.titleText)
try {
val (elements, issues) = IEC61131Facade.fileResolve(stream, false)
lookup.get<OutlineService>().show(StOverviewTransformer(codeEditor).create(elements))
issues.forEach {
result.addNotice(DefaultParserNotice(this, it.message,
it.startLine, it.startOffset, it.length))
}
lookup.get<ProblemService>().announceProblems(codeEditor, issues)
} catch (e: SyntaxErrorReporter.ParserException) {
e.errors.forEach {
result.addNotice(DefaultParserNotice(this, it.msg,
it.line, it.offendingSymbol?.startIndex ?: -1,
it.offendingSymbol?.text?.length ?: -1))
}
} catch (e: Exception) {
}
return result
}
override fun isEnabled(): Boolean = true
}
class STFoldParser : FoldParser {
private val OPEN_KEYWORDS =
regex(hashMapOf("\\bTHEN\\b" to "\\bEND_IF\\b",
"\\bFUNCTION\\b" to "\\bEND_FUNCTION\\b",
"\\bFUNCTION_BLOCK\\b" to "\\bEND_FUNCTION_BLOCK\\b",
"\\bCLASS\\b" to "\\bEND_CLASS\\b",
"\\bMETHOD\\b" to "\\bEND_METHOD\\b",
"\\bFOR\\b" to "\\bEND_FOR\\b",
"\\bWHILE\\b" to "\\bEND_WHILE\\b",
"\\bVAR.*\\b" to "\\bEND_VAR\\b",
"\\bACTION.*\\b" to "\\bEND_ACTION\\b",
"\\bSTEP.*\\b" to "\\bEND_STEP\\b",
"\\bPROGRAM\\b" to "\\bEND_PROGRAM\\b"
))
private fun regex(map: HashMap<String, String>): List<Pair<Regex, Regex>> = map.map { (k, v) ->
k.toRegex(RegexOption.IGNORE_CASE) to v.toRegex(RegexOption.IGNORE_CASE)
}
override fun getFolds(textArea: RSyntaxTextArea): List<Fold> {
val folds = ArrayList<Fold>()
val expected = LinkedList<Pair<Regex, Fold>>()
try {
var offset = 0
val lines = textArea.text.splitToSequence('\n')
lines.forEachIndexed { idx, line ->
val match = expected.indexOfFirst { (regex, _) ->
regex.containsMatchIn(line)
}
if (match > -1) {
for (i in 0..match) {
val (_, f) = expected.pollFirst()
f.endOffset = offset
folds += f
}
}
loop@ for ((open, close) in OPEN_KEYWORDS) {
when {
open.containsMatchIn(line) && close.containsMatchIn(line) -> {
val f = Fold(FoldType.CODE, textArea, offset)
f.endOffset = offset + line.length
expected.addFirst(close to f)
break@loop
}
open.containsMatchIn(line) -> {
expected.addFirst(
close to Fold(FoldType.CODE, textArea, offset))
break@loop
}
}
}
offset += line.length + 1
}
} catch (ble: BadLocationException) {
ble.printStackTrace()
}
return folds
}
}
class StOverviewTransformer(val editor: CodeEditor) {
private val colors: Colors by editor.lookup.with()
companion object {
private val ICON_SIZE = 12
private val ROOT_ICON: Icon = IconFontSwing.buildIcon(FontAwesomeRegular.FILE_CODE, ICON_SIZE.toFloat())
private val ICON_GVL: Icon? = StructureTypeIcon.buildIcon("v", ICON_SIZE)
private val ICON_DATATYPES: Icon? = StructureTypeIcon.buildIcon("v", ICON_SIZE)
private val ICON_DATATYPE: Icon? = StructureTypeIcon.buildIcon("v", ICON_SIZE)
private val ICON_METHOD: Icon? = StructureTypeIcon.buildIcon("m", ICON_SIZE)
private val ICON_CLASS: Icon? = StructureTypeIcon.buildIcon("c", ICON_SIZE)
private val ICON_PROGRAM: Icon? = StructureTypeIcon.buildIcon("p", ICON_SIZE)
private val ICON_FBD: Icon? = StructureTypeIcon.buildIcon("fbd", ICON_SIZE)
private val ICON_VAR: Icon? = StructureTypeIcon.buildIcon("v", ICON_SIZE)
private val ICON_FUNCTION: Icon? = StructureTypeIcon.buildIcon("f", ICON_SIZE)
}
fun create(elements: PouElements): OverviewStructureNode {
val root = OverviewStructureNode(StructureData(editor.titleText.trim('*'), editor, ROOT_ICON))
val v = Visitor()
elements.mapNotNull { it.accept(v) }.forEach { root.add(it) }
return root
}
inner class Visitor : AstVisitor<OverviewStructureNode?>() {
override fun defaultVisit(obj: Any): OverviewStructureNode? = null
override fun visit(gvlDecl: GlobalVariableListDeclaration): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData("global variables", editor, ICON_GVL))
gvlDecl.scope.accept(this)?.seq?.also { node.seq.addAll(it) }
return node
}
override fun visit(programDeclaration: ProgramDeclaration): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData(programDeclaration.name, editor, ICON_PROGRAM))
val variables = programDeclaration.scope.accept(this)?.seq
val actions = programDeclaration.actions.mapNotNull { it.accept(this) }
variables?.also { node.seq.addAll(it) }
actions.forEach { node.seq.add(it) }
return node
}
override fun visit(functionBlockDeclaration: FunctionBlockDeclaration): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData(functionBlockDeclaration.name, editor, ICON_FBD))
val variables = functionBlockDeclaration.scope.accept(this)?.seq
val actions = functionBlockDeclaration.actions.mapNotNull { it.accept(this) }
variables?.also { seq -> seq.forEach { node.add(it) } }
actions.forEach { node.add(it) }
return node
}
override fun visit(functionDeclaration: FunctionDeclaration): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData(functionDeclaration.name, editor, ICON_FUNCTION))
functionDeclaration.scope.accept(this)?.seq?.also { node.seq.addAll(it) }
return node
}
override fun visit(localScope: Scope): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData("Variables", editor, ICON_VAR))
localScope.mapNotNull { it.accept(this) }.forEach { node.add(it) }
return node
}
override fun visit(typeDeclarations: TypeDeclarations): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData("Data Types", editor,
ICON_DATATYPES, typeDeclarations.startPosition))
typeDeclarations.mapNotNull {
OverviewStructureNode(StructureData(it.name, editor, ICON_DATATYPE, it.startPosition))
}
.forEach { node.add(it) }
return node
}
override fun visit(clazz: ClassDeclaration): OverviewStructureNode? {
val node = OverviewStructureNode(StructureData(clazz.name, editor,
ICON_CLASS, clazz.startPosition))
val variables = clazz.scope.accept(this)?.seq
variables?.also { seq -> seq.forEach { node.add(it) } }
clazz.methods.mapNotNull {
it.accept(this)
}.forEach { node.add(it) }
return node
}
override fun visit(variableDeclaration: VariableDeclaration): OverviewStructureNode? {
return OverviewStructureNode(
StructureData("${variableDeclaration.name} : ${variableDeclaration.dataType}",
editor, ICON_METHOD, variableDeclaration.startPosition))
}
override fun visit(method: MethodDeclaration): OverviewStructureNode? {
return OverviewStructureNode(StructureData(method.name, editor, ICON_METHOD, method.startPosition))
}
}
}
| gpl-3.0 | 07ae90771e0315699754bfe0f2b757fd | 38.292614 | 112 | 0.584267 | 4.330307 | false | false | false | false |
dkhmelenko/Varis-Android | app-v3/src/main/java/com/khmelenko/lab/varis/util/ImageHelper.kt | 2 | 1287 | package com.khmelenko.lab.varis.util
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
/**
* Provides utility methods for processing images
*
* @author Dmytro Khmelenko
*/
object ImageHelper {
/**
* Gets the bitmap with rounded corners
*
* @param bitmap Bitmap for processing
* @param pixels Picture diameter in pixels
* @return Rounded picture
*/
fun getRoundedCornerBitmap(bitmap: Bitmap, pixels: Int): Bitmap {
val output = Bitmap.createBitmap(bitmap.width, bitmap
.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
val color = -0xbdbdbe
val paint = Paint()
val rect = Rect(0, 0, bitmap.width, bitmap.height)
val rectF = RectF(rect)
val roundPx = pixels.toFloat()
paint.isAntiAlias = true
canvas.drawARGB(0, 0, 0, 0)
paint.color = color
canvas.drawRoundRect(rectF, roundPx, roundPx, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
canvas.drawBitmap(bitmap, rect, rect, paint)
return output
}
}
| apache-2.0 | 718403d1e5a6671a3cc17dde6700fbe2 | 26.978261 | 69 | 0.67366 | 4.318792 | false | false | false | false |
RP-Kit/RPKit | rpk-core/src/main/kotlin/com/rpkit/core/expression/function/rounding/RoundFunction.kt | 1 | 1297 | /*
* 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.core.expression.function.rounding
import com.rpkit.core.expression.RPKFunction
import java.math.RoundingMode.HALF_UP
import java.text.DecimalFormat
import kotlin.math.round
internal class RoundFunction : RPKFunction {
override fun invoke(vararg args: Any?): Any? {
val arg1 = (args[0] as? Number)?.toDouble() ?: args[0].toString().toDoubleOrNull() ?: return null
val arg2 = (args[1] as? Number)?.toInt() ?: args[1].toString().toIntOrNull() ?: 0
if (arg2 == 0) return round(arg1)
val decimalFormat = DecimalFormat("#.${"#".repeat(arg2)}")
decimalFormat.roundingMode = HALF_UP
return decimalFormat.format(arg1).toDoubleOrNull()
}
} | apache-2.0 | 229298bf3f2ea4005b8267ec681973f8 | 39.5625 | 105 | 0.710871 | 4.053125 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/ui/fragment/netease/NeteaseOverviewFragment.kt | 1 | 8217 | package tech.summerly.quiet.ui.fragment.netease
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.util.DiffUtil
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_netease_overview.view.*
import kotlinx.android.synthetic.main.item_netease_recommend_mv.view.*
import kotlinx.android.synthetic.main.item_netease_recommend_playlist.view.*
import me.drakeet.multitype.MultiTypeAdapter
import org.jetbrains.anko.support.v4.startActivity
import tech.summerly.quiet.R
import tech.summerly.quiet.module.common.bean.MusicType
import tech.summerly.quiet.bean.Playlist
import tech.summerly.quiet.data.netease.result.RecommendMvResultBean
import tech.summerly.quiet.data.netease.result.UserDetailResultBean
import tech.summerly.quiet.data.netease.source.NeteaseGlideUrl
import tech.summerly.quiet.extensions.lib.GlideApp
import tech.summerly.quiet.extensions.lib.KItemViewBinder
import tech.summerly.quiet.extensions.log
import tech.summerly.quiet.extensions.multiTypeAdapter
import tech.summerly.quiet.presenter.NeteaseOverviewContract
import tech.summerly.quiet.presenter.NeteaseOverviewPresenterImpl
import tech.summerly.quiet.ui.activity.netease.LoginActivity
import tech.summerly.quiet.ui.activity.netease.MvPlayerActivity
import tech.summerly.quiet.ui.activity.netease.PersonalFmActivity
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/24
* desc : 网易云音乐的主界面
*/
class NeteaseOverviewFragment : Fragment(), NeteaseOverviewContract.NeteaseOverviewView {
companion object {
private val REQUEST_LOGIN = 100
}
private lateinit var presenter: NeteaseOverviewContract.NeteaseOverviewPresenter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_netease_overview, container, false)
view.listRecommendPlaylist.adapter = MultiTypeAdapter().also {
it.register(Playlist::class.java, RecommendPlayListItemViewBinder())
}
view.listRecommendMv.adapter = MultiTypeAdapter().also {
it.register(RecommendMvResultBean.Result::class.java, RecommendMvItemViewBinder())
}
presenter = NeteaseOverviewPresenterImpl(this)
presenter.fetchData()
return view
}
override fun onStart() {
super.onStart()
presenter.fetchUserInfo()
}
override fun setUserProfile(profile: UserDetailResultBean.Profile) {
val root = view ?: return
root.textNickname.text = profile.nickname
GlideApp.with(this).load(profile.avatarUrl?.let { NeteaseGlideUrl(it) }).circleCrop().into(root.imageAvatar)
GlideApp.with(this).load(profile.backgroundUrl).into(root.backgroundNav)
}
override fun setRecommendPlaylist(list: List<Playlist>) {
val listRecommendPlaylist = view?.listRecommendPlaylist ?: return
val adapter = listRecommendPlaylist.multiTypeAdapter
DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return (adapter.items[oldItemPosition] as
Playlist).id == list[newItemPosition].id
}
override fun getOldListSize(): Int {
return adapter.items.size
}
override fun getNewListSize(): Int {
return list.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val old = adapter.items[oldItemPosition] as
Playlist
val new = list[newItemPosition]
return old.coverImageUrl == new.coverImageUrl && old.name == new.name
}
}).dispatchUpdatesTo(adapter)
adapter.items = list
}
override fun setRecommendMv(list: List<RecommendMvResultBean.Result>) {
val listRecommendMv = view?.listRecommendMv ?: return
val adapter = listRecommendMv.multiTypeAdapter
DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return (adapter.items[oldItemPosition] as
RecommendMvResultBean.Result).id == list[newItemPosition].id
}
override fun getOldListSize(): Int {
return adapter.items.size
}
override fun getNewListSize(): Int {
return list.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val old = adapter.items[oldItemPosition] as
RecommendMvResultBean.Result
val new = list[newItemPosition]
return old.picUrl == new.picUrl && old.name == new.name
}
}).dispatchUpdatesTo(adapter)
adapter.items = list
}
private inner class RecommendMvItemViewBinder : KItemViewBinder<RecommendMvResultBean.Result>() {
override fun onBindViewHolder(holder: KViewHolder, item: RecommendMvResultBean.Result) {
GlideApp.with(this@NeteaseOverviewFragment)
.load(item.picUrl?.let { NeteaseGlideUrl(it) }).into(holder.itemView.imageMv)
holder.itemView.textTitle.text = item.name
holder.itemView.textSubTitle.text = item.artistName
holder.itemView.setOnClickListener {
log("to check $item")
MvPlayerActivity.start(activity, item.id, MusicType.NETEASE)
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder {
return KViewHolder(inflater.inflate(R.layout.item_netease_recommend_mv, parent, false))
}
}
private inner class RecommendPlayListItemViewBinder : KItemViewBinder<Playlist>() {
override fun onBindViewHolder(holder: KViewHolder, item: Playlist) {
holder.itemView.textName.text = item.name
GlideApp.with(this@NeteaseOverviewFragment).load(item.coverImageUrl?.toString()?.let { NeteaseGlideUrl(it) })
.into(holder.itemView.imagePlaylist)
holder.itemView.setOnClickListener {
log("to check $item")
TODO()
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder {
return KViewHolder(inflater.inflate(R.layout.item_netease_recommend_playlist, parent, false))
}
}
override fun setFetchUserProfileFailed() {
val root = view ?: return
root.textNickname.text = "获取网络数据失败"
}
override fun setNotLogin() {
val root = view ?: return
root.textNickname.text = "未登录"
root.groupForNotLogin.visibility = View.VISIBLE
root.groupForLogin.visibility = View.GONE
root.actionLogin.setOnClickListener {
startActivity<LoginActivity>()
}
}
override fun readyToRefreshUserInfo(neteaseUserName: String) {
val root = view ?: return
root.textNickname.text = neteaseUserName
root.groupForNotLogin.visibility = View.GONE
root.groupForLogin.visibility = View.VISIBLE
root.buttonDailyRecommend.setOnClickListener {
TODO()
}
root.buttonPersonalFm.setOnClickListener {
startActivity<PersonalFmActivity>()
}
}
override fun setFetchRecommendPlaylistFailed() {
//TODO
}
override fun setFetchRecommendMvFailed() {
//TODO
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_LOGIN && resultCode == Activity.RESULT_OK) {
presenter.fetchUserInfo()
presenter.fetchData()
}
super.onActivityResult(requestCode, resultCode, data)
}
} | gpl-2.0 | 3ecfa9c896410e9ef43e82c4aa7d339b | 38.507246 | 121 | 0.677021 | 4.807172 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/StyledViewer.kt | 1 | 10676 | package cn.yiiguxing.plugin.translate.ui
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.trans.Lang
import cn.yiiguxing.plugin.translate.trans.Translation
import cn.yiiguxing.plugin.translate.trans.google.GoogleDictDocument
import cn.yiiguxing.plugin.translate.trans.youdao.YoudaoDictDocument
import cn.yiiguxing.plugin.translate.trans.youdao.YoudaoWebTranslationDocument
import cn.yiiguxing.plugin.translate.util.text.text
import com.intellij.icons.AllIcons
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.ui.JBMenuItem
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.ui.JBColor
import com.intellij.ui.PopupMenuListenerAdapter
import java.awt.Color
import java.awt.Cursor
import java.awt.datatransfer.StringSelection
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.Icon
import javax.swing.JMenuItem
import javax.swing.event.PopupMenuEvent
import javax.swing.text.Element
import javax.swing.text.MutableAttributeSet
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants as DefaultStyleConstants
/**
* StyledViewer
*/
class StyledViewer : Viewer() {
private var onClickHandler: ((Element, Any?) -> Unit)? = null
private var onBeforeFoldingExpandHandler: ((Element, Any?) -> Unit)? = null
private var onFoldingExpandedHandler: ((Any?) -> Unit)? = null
private val popupMenu = JBPopupMenu()
private var popupMenuTargetElement: Element? = null
private var popupMenuTargetData: Any? = null
init {
foreground = JBColor(0x333333, 0xD4D7D9)
ViewerMouseAdapter().let {
addMouseListener(it)
addMouseMotionListener(it)
}
popupMenu.addPopupMenuListener(object : PopupMenuListenerAdapter() {
override fun popupMenuCanceled(e: PopupMenuEvent?) {
popupMenuTargetElement = null
popupMenuTargetData = null
}
})
}
fun addPopupMenuItem(
text: String,
icon: Icon? = null,
action: (item: JMenuItem, element: Element, data: Any?) -> Unit
): JMenuItem {
val item = JBMenuItem(text, icon)
item.addActionListener {
popupMenuTargetElement?.let { action(item, it, popupMenuTargetData) }
popupMenuTargetElement = null
popupMenuTargetData = null
}
return popupMenu.add(item)
}
fun onClick(handler: ((element: Element, data: Any?) -> Unit)?) {
onClickHandler = handler
}
fun onBeforeFoldingExpand(handler: ((element: Element, data: Any?) -> Unit)?) {
onBeforeFoldingExpandHandler = handler
}
fun onFoldingExpanded(handler: ((data: Any?) -> Unit)?) {
onFoldingExpandedHandler = handler
}
private fun showPopupMenu(event: MouseEvent, element: Element, data: Any?) {
if (popupMenu.componentCount > 0) {
popupMenuTargetElement = element
popupMenuTargetData = data
popupMenu.show(this, event.x, event.y)
}
}
enum class StyleConstants {
MouseListener;
companion object {
fun setMouseListener(attrs: MutableAttributeSet, listener: StyledViewer.MouseListener) {
attrs.addAttribute(MouseListener, listener)
}
fun setClickable(attrs: MutableAttributeSet, color: Color, hoverColor: Color? = null, data: Any? = null) {
val mouseListener = ColoredMouseListener(color, hoverColor, data)
setMouseListener(attrs, mouseListener)
}
}
}
private inner class ViewerMouseAdapter : MouseAdapter() {
private var lastElement: Element? = null
private var activeElement: Element? = null
private inline val MouseEvent.characterElement: Element
@Suppress("DEPRECATION")
get() = styledDocument.getCharacterElement(viewToModel(point))
private inline val Element.mouseListener: MouseListener?
get() = attributes.getAttribute(StyleConstants.MouseListener) as? MouseListener
override fun mouseMoved(event: MouseEvent) {
val element = event.characterElement
if (element !== lastElement) {
exitLastElement(event)
lastElement = element.mouseListener?.run {
mouseEntered(this@StyledViewer, event, element)
element
}
}
}
private fun exitLastElement(event: MouseEvent) {
activeElement = null
val element = lastElement ?: return
element.mouseListener?.mouseExited(this@StyledViewer, event, element)
lastElement = null
}
override fun mouseExited(event: MouseEvent) = exitLastElement(event)
override fun mousePressed(event: MouseEvent) {
event.component.requestFocus()
activeElement = event.characterElement
}
override fun mouseReleased(event: MouseEvent) { // 使用`mouseClicked`在MacOS下会出现事件丢失的情况...
event.characterElement.takeIf { it === activeElement }?.let { elem ->
(elem.attributes.getAttribute(StyleConstants.MouseListener) as? MouseListener)?.let { listener ->
when {
event.button == MouseEvent.BUTTON1 && event.clickCount == 1 -> {
listener.mouseClicked(this@StyledViewer, event, elem)
}
event.button == MouseEvent.BUTTON3 && event.clickCount == 1 -> {
listener.mouseRightButtonClicked(this@StyledViewer, event, elem)
}
}
}
}
activeElement = null
}
}
open class MouseListener internal constructor(val data: Any? = null) {
fun mouseClicked(viewer: StyledViewer, event: MouseEvent, element: Element) {
if (!onMouseClick(viewer, event, element)) {
viewer.onClickHandler?.invoke(element, data)
}
}
protected open fun onMouseClick(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean = false
fun mouseRightButtonClicked(viewer: StyledViewer, event: MouseEvent, element: Element) {
if (!onMouseRightButtonClick(viewer, event, element)) {
viewer.showPopupMenu(event, element, data)
}
}
protected open fun onMouseRightButtonClick(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean {
return false
}
fun mouseEntered(viewer: StyledViewer, event: MouseEvent, element: Element) {
if (!onMouseEnter(viewer, event, element)) {
viewer.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
}
}
protected open fun onMouseEnter(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean = false
fun mouseExited(viewer: StyledViewer, event: MouseEvent, element: Element) {
if (!onMouseExit(viewer, event, element)) {
viewer.cursor = Cursor.getDefaultCursor()
}
}
protected open fun onMouseExit(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean = false
}
open class ColoredMouseListener internal constructor(
color: Color,
hoverColor: Color? = null,
data: Any? = null
) : MouseListener(data) {
private val regularAttributes = SimpleAttributeSet().apply {
DefaultStyleConstants.setForeground(this, color)
}
private val hoverAttributes = SimpleAttributeSet().apply {
DefaultStyleConstants.setForeground(this, hoverColor ?: color)
}
override fun onMouseEnter(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean {
with(element) {
viewer.styledDocument.setCharacterAttributes(startOffset, offsetLength, hoverAttributes, false)
}
return super.onMouseEnter(viewer, event, element)
}
override fun onMouseExit(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean {
with(element) {
viewer.styledDocument.setCharacterAttributes(startOffset, offsetLength, regularAttributes, false)
}
return super.onMouseExit(viewer, event, element)
}
}
class FoldingMouseListener(
data: Any? = null,
private val onFoldingExpand: (viewer: StyledViewer, element: Element, data: Any?) -> Unit
) : MouseListener(data) {
override fun onMouseClick(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean {
viewer.onBeforeFoldingExpandHandler?.invoke(element, data)
onFoldingExpand(viewer, element, data)
viewer.onFoldingExpandedHandler?.invoke(data)
return true
}
override fun onMouseRightButtonClick(viewer: StyledViewer, event: MouseEvent, element: Element): Boolean = true
}
companion object {
private inline val Element.offsetLength: Int
get() = endOffset - startOffset
fun StyledViewer.setupActions(
prevTranslation: () -> Translation?,
onNewTranslateHandler: ((String, Lang, Lang) -> Unit)
) {
addPopupMenuItem(message("menu.item.copy"), AllIcons.Actions.Copy) { _, element, _ ->
CopyPasteManager.getInstance().setContents(StringSelection(element.text))
}
onClick { element, data ->
prevTranslation()?.run {
val src: Lang
val target: Lang
when (data) {
GoogleDictDocument.WordType.WORD,
YoudaoDictDocument.WordType.WORD,
YoudaoWebTranslationDocument.WordType.WEB_VALUE -> {
src = targetLang
target = srcLang
}
GoogleDictDocument.WordType.REVERSE,
YoudaoDictDocument.WordType.VARIANT,
YoudaoWebTranslationDocument.WordType.WEB_KEY -> {
src = srcLang
target = targetLang
}
else -> return@onClick
}
onNewTranslateHandler(element.text, src, target)
}
}
}
}
} | mit | 1f6134bf048365b0673e3d7a7266c8c6 | 36.496479 | 120 | 0.618144 | 5.119231 | false | false | false | false |
gdgplzen/gugorg-android | app/src/main/java/cz/jacktech/gugorganizer/ui/util/RecyclerItemDivider.kt | 1 | 1350 | package cz.jacktech.gugorganizer.ui.util
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.View
import cz.jacktech.gugorganizer.R
/**
* Created by toor on 13.8.15.
*/
public class RecyclerItemDivider(context: Context) : RecyclerView.ItemDecoration() {
private val mDivider: Drawable
init {
mDivider = context.getResources().getDrawable(R.drawable.line_divider)
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
val left = parent.getPaddingLeft()
val right = parent.getWidth() - parent.getPaddingRight()
val childCount = parent.getChildCount()
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.getLayoutParams() as RecyclerView.LayoutParams
val top = child.getBottom() + params.bottomMargin
val bottom = top + mDivider.getIntrinsicHeight()
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
outRect.bottom = mDivider.getIntrinsicHeight()
}
}
| gpl-2.0 | 7314d2b368f946bea546a8a16f181b75 | 29 | 110 | 0.688889 | 4.299363 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/util/HexUtil.kt | 1 | 838 | package com.jeremiahzucker.pandroid.util
/**
* Created by Jeremiah Zucker on 8/19/2017.
*/
fun String.hexStringToByteArray(): ByteArray {
val len = 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
}
// Credit where credit is due
// https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
private val hexArray = "0123456789abcdef".toCharArray()
fun ByteArray.bytesToHex(): String {
val hexChars = CharArray(size * 2)
for (j in indices) {
val v = this[j].toInt() and 0xFF
hexChars[j * 2] = hexArray[v.ushr(4)]
hexChars[j * 2 + 1] = hexArray[v and 0x0F]
}
return String(hexChars)
}
| mit | 0b484bbf70c990d34368d3a806c56ddd | 27.896552 | 104 | 0.626492 | 3.312253 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/guilds/dashboard/GeneralConfigRoute.kt | 1 | 9050 | package net.perfectdreams.spicymorenitta.routes.guilds.dashboard
import LoriDashboard
import jq
import kotlinx.browser.document
import kotlinx.dom.addClass
import kotlinx.dom.clear
import kotlinx.dom.removeClass
import kotlinx.html.*
import kotlinx.html.dom.append
import kotlinx.html.js.onClickFunction
import kotlinx.html.js.onInputFunction
import kotlinx.serialization.Serializable
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import net.perfectdreams.spicymorenitta.application.ApplicationCall
import net.perfectdreams.spicymorenitta.locale
import net.perfectdreams.spicymorenitta.routes.UpdateNavbarSizePostRender
import net.perfectdreams.spicymorenitta.utils.DashboardUtils
import net.perfectdreams.spicymorenitta.utils.DashboardUtils.launchWithLoadingScreenAndFixContent
import net.perfectdreams.spicymorenitta.utils.DashboardUtils.switchContentAndFixLeftSidebarScroll
import net.perfectdreams.spicymorenitta.utils.EmbedEditorStuff
import net.perfectdreams.spicymorenitta.utils.SaveUtils
import net.perfectdreams.spicymorenitta.utils.select
import net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig
import org.w3c.dom.*
class GeneralConfigRoute(val m: SpicyMorenitta) : UpdateNavbarSizePostRender("/guild/{guildid}/configure") {
companion object {
private const val LOCALE_PREFIX = "website.dashboard.general"
}
@Serializable
class PartialGuildConfiguration(
val general: ServerConfig.GeneralConfig,
val textChannels: List<ServerConfig.TextChannel>
)
val blacklistedChannels = mutableListOf<Long>()
override fun onUnload() {
blacklistedChannels.clear()
}
override val keepLoadingScreen: Boolean
get() = true
private fun DIV.createFakeMessage(avatarUrl: String, name: String, content: DIV.() -> (Unit)) {
div {
style = "display: flex; align-items: center;"
div {
style = "display: flex; flex-direction: column; margin-right: 10px;"
img(src = avatarUrl) {
style = "border-radius: 100%;"
width = "40"
}
}
div {
style = "display: flex; flex-direction: column;"
div {
style = "font-weight: 600;"
+ name
}
div {
content.invoke(this)
}
}
}
}
override fun onRender(call: ApplicationCall) {
launchWithLoadingScreenAndFixContent(call) {
val guild = DashboardUtils.retrievePartialGuildConfiguration<PartialGuildConfiguration>(call.parameters["guildid"]!!, "general", "textchannels")
blacklistedChannels.addAll(guild.general.blacklistedChannels)
switchContentAndFixLeftSidebarScroll(call)
val stuff = document.select<HTMLDivElement>("#general-stuff")
stuff.append {
div(classes = "userOptionsWrapper") {
div(classes = "pure-g") {
div(classes = "pure-u-1 pure-u-md-1-6") {
img(src = "/assets/img/lori_avatar_v3.png") {
style = "border-radius: 99999px; height: 100px;"
}
}
div(classes = "pure-u-1 pure-u-md-2-3") {
div(classes = "flavourText") {
+ locale["${LOCALE_PREFIX}.commandPrefix.title"]
}
div(classes = "toggleSubText") {
+ locale["${LOCALE_PREFIX}.commandPrefix.subtext"]
}
input(type = InputType.text) {
id = "command-prefix"
value = guild.general.commandPrefix
onInputFunction = {
val commandPrefix = document.select<HTMLInputElement>("#command-prefix")
commandPrefix.value = commandPrefix.value.trim()
document.select<HTMLSpanElement>("#command-prefix-preview")
.innerText = commandPrefix.value
}
}
div(classes = "discord-message-helper") {
style = "display: flex; flex-direction: column; justify-content: center; font-family: Lato,Helvetica Neue,Helvetica,Arial,sans-serif;"
createFakeMessage(
m.userIdentification?.userAvatarUrl ?: "???",
m.userIdentification?.username ?: "???"
) {
span {
id = "command-prefix-preview"
+ guild.general.commandPrefix
}
span {
+ "ping"
}
}
div {
hr {}
}
createFakeMessage(
"/assets/img/lori_avatar_v3.png",
"Loritta"
) {
span {
+ "\uD83C\uDFD3"
}
b {
+ " | "
span(classes = "discord-mention") {
+ ("@" + (m.userIdentification?.username ?: "???"))
}
+ " Pong!"
}
}
}
}
}
}
div {
createToggle(
locale["${LOCALE_PREFIX}.deleteMessagesAfterExecuting.title"],
locale["${LOCALE_PREFIX}.deleteMessagesAfterExecuting.subtext"],
"delete-message-after-command",
guild.general.deleteMessageAfterCommand
)
hr {}
createToggle(
locale["${LOCALE_PREFIX}.tellUserWhenUsingUnknownCommand.title"],
locale["${LOCALE_PREFIX}.tellUserWhenUsingUnknownCommand.subtext"],
"warn-on-unknown-command",
guild.general.warnOnUnknownCommand
)
hr {}
div(classes = "flavourText") {
+ locale["${LOCALE_PREFIX}.blacklistedChannels.title"]
}
div(classes = "toggleSubText") {
+ locale["${LOCALE_PREFIX}.blacklistedChannels.subtext"]
}
select {
id = "choose-channel-blacklisted"
style = "width: 320px;"
for (channel in guild.textChannels) {
option {
+ ("#${channel.name}")
value = channel.id.toString()
}
}
}
+ " "
button(classes = "button-discord button-discord-info pure-button") {
+ locale["loritta.add"]
onClickFunction = {
val role = document.select<HTMLSelectElement>("#choose-channel-blacklisted").value
blacklistedChannels.add(role.toLong())
updateBlacklistedChannelsList(guild)
}
}
div(classes = "list-wrapper") {
id = "channel-blacklisted-list"
}
hr {}
createToggle(
locale["${LOCALE_PREFIX}.tellUserWhenUsingCommandsOnABlacklistedChannel.title"],
locale["${LOCALE_PREFIX}.tellUserWhenUsingCommandsOnABlacklistedChannel.subtext"],
"warn-if-blacklisted",
guild.general.warnIfBlacklisted
) { result ->
updateDisabledSections()
result
}
hr {}
div {
id = "hidden-if-disabled-blacklist"
div(classes = "flavourText") {
+ locale["${LOCALE_PREFIX}.messageWhenUsingACommandInABlockedChannel.title"]
}
textArea {
id = "blacklisted-warning"
+ (guild.general.blacklistedWarning ?: "{@user} Você não pode usar comandos no {@channel}, bobinho(a)")
}
}
hr {}
button(classes = "button-discord button-discord-success pure-button") {
style = "float: right;"
+ locale["loritta.save"]
onClickFunction = {
prepareSave()
}
}
}
}
LoriDashboard.configureTextArea(
jq("#blacklisted-warning"),
true,
false,
null,
true,
EmbedEditorStuff.userInContextPlaceholders(locale),
// customTokens = mapOf(),
showTemplates = false
)
updateBlacklistedChannelsList(guild)
updateDisabledSections()
}
}
fun updateDisabledSections() {
val warnIfBlacklisted = document.select<HTMLInputElement>("#warn-if-blacklisted").checked
if (warnIfBlacklisted) {
document.select<HTMLDivElement>("#hidden-if-disabled-blacklist").removeClass("blurSection")
} else {
document.select<HTMLDivElement>("#hidden-if-disabled-blacklist").addClass("blurSection")
}
}
fun updateBlacklistedChannelsList(guild: PartialGuildConfiguration) {
val list = document.select<HTMLDivElement>("#channel-blacklisted-list")
list.clear()
list.append {
blacklistedChannels.forEach { channelId ->
val guildChannel = guild.textChannels.firstOrNull { it.id.toLong() == channelId } ?: return@forEach
list.append {
span(classes = "discord-mention") {
style = "cursor: pointer; margin-right: 4px;"
+ "#${guildChannel.name}"
onClickFunction = {
blacklistedChannels.remove(channelId)
updateBlacklistedChannelsList(guild)
}
span {
style = "border-left: 1px solid rgba(0, 0, 0, 0.15);opacity: 0.7;padding-left: 3px;font-size: 14px;margin-left: 3px;padding-right: 3px;"
i(classes = "fas fa-times") {}
}
}
}
}
}
}
fun prepareSave() {
SaveUtils.prepareSave("general", extras = {
it["commandPrefix"] = document.select<HTMLInputElement>("#command-prefix").value
it["deleteMessageAfterCommand"] = document.select<HTMLInputElement>("#delete-message-after-command").checked
it["warnOnUnknownCommand"] = document.select<HTMLInputElement>("#warn-on-unknown-command").checked
it["blacklistedChannels"] = blacklistedChannels.map { it.toString() }
val warnIfBlacklisted = document.select<HTMLInputElement>("#warn-if-blacklisted").checked
it["warnIfBlacklisted"] = warnIfBlacklisted
if (warnIfBlacklisted) {
it["blacklistedWarning"] = document.select<HTMLTextAreaElement>("#blacklisted-warning").value
}
})
}
} | agpl-3.0 | 6630e3879f59dda427c26ec16d8f0f10 | 26.929012 | 147 | 0.658599 | 3.749689 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/time/MutableClock.kt | 1 | 1165 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.time
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.time.temporal.TemporalAmount
class MutableClock(
private var instant: Instant,
private val zone: ZoneId = ZoneId.systemDefault()
) : Clock() {
override fun withZone(zone: ZoneId) = MutableClock(instant, zone)
override fun getZone() = zone
override fun instant() = instant
fun incrementBy(amount: TemporalAmount) {
instant = instant.plus(amount)
}
fun instant(newInstant: Instant): Unit {
instant = newInstant
}
}
| apache-2.0 | 1d62d6d9e586fafc9f2f4f6ca971e8b0 | 26.738095 | 75 | 0.737339 | 4.031142 | false | false | false | false |
eugeis/ee | ee-common/src/main/kotlin/ee/common/ext/NetExt.kt | 1 | 576 | package ee.common.ext
import java.net.InetAddress
import java.net.NetworkInterface
fun InetAddress.isLocalAddress(): Boolean {
val ifaces = NetworkInterface.getNetworkInterfaces()
while (ifaces.hasMoreElements()) {
val iface = ifaces.nextElement()
val addresses = iface.inetAddresses
while (addresses.hasMoreElements()) {
val addr = addresses.nextElement()
if (addr.equals(this)) {
return true
}
}
}
return false
}
fun String.toInetAddress() = InetAddress.getByName(this)
| apache-2.0 | a570b017083c61402298cbd0e6c0b2d6 | 25.181818 | 56 | 0.644097 | 4.721311 | false | false | false | false |
google/xplat | j2kt/jre/java/native/java/util/regex/Pattern.kt | 1 | 2384 | /*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.util.regex
import kotlin.text.Regex
/** Kotlin Pattern implementation backed by kotlin.text.Regex. */
class Pattern(pattern: String, private val flags: Int) {
internal val regex: Regex
init {
try {
regex = Regex(pattern, flagsToOptions(flags))
} catch (e: RuntimeException) {
throw PatternSyntaxException(e.message ?: "", pattern, -1)
}
}
fun flags() = flags
fun matcher(input: CharSequence): Matcher = Matcher(this, input)
fun split(input: CharSequence): Array<String> = regex.split(input).toTypedArray()
fun split(input: CharSequence, limit: Int): Array<String> =
regex.split(input, limit).toTypedArray()
fun pattern() = regex.pattern
override fun toString() = regex.toString()
companion object {
const val CANON_EQ = 128
const val CASE_INSENSITIVE = 2
const val COMMENTS = 4
const val DOTALL = 32
const val LITERAL = 16
const val MULTILINE = 8
const val UNICODE_CASE = 64
const val UNICODE_CHARACTER_CLASS = 256
const val UNIX_LINES = 1
private fun flagsToOptions(flags: Int): Set<RegexOption> {
val builder = mutableSetOf<RegexOption>()
var flag = 1
while (flag <= 256) {
when (flags and flag) {
0 -> {} // Flag not set
CASE_INSENSITIVE -> builder.add(RegexOption.IGNORE_CASE)
MULTILINE -> builder.add(RegexOption.MULTILINE)
else -> throw IllegalStateException("Unsupported flag $flag")
}
flag *= 2
}
return builder.toSet()
}
fun compile(regex: String) = Pattern(regex, 0)
fun compile(regex: String, flags: Int) = Pattern(regex, flags)
fun matches(regex: String, input: CharSequence) = Regex(regex).matches(input)
fun quote(s: String) = Regex.escape(s)
}
}
| apache-2.0 | e9fa3e5d149ac657b4e45ee8104e4e9c | 29.177215 | 83 | 0.672399 | 4.09622 | false | false | false | false |
YounesRahimi/java-utils | src/main/java/ir/iais/utilities/javautils/ranges/ProgressionIterators.kt | 2 | 4323 | package ir.iais.utilities.javautils.ranges
import ir.iais.utilities.javautils.time.PersianDate
import ir.iais.utilities.javautils.utils.toDate
import java.time.Duration
import java.time.LocalDate
import java.time.LocalTime
import java.time.Period
import java.util.*
///** An iterator over a progression of values of type `Date`.
// * @property step the number by which the value is incremented on each step.
// */
//internal class DateProgressionIterator(first: Date, last: Date,
// /**
// * Step in milliseconds
// */
// private val step: Long) : DateIterator() {
// private val finalElement = last
// private var hasNext: Boolean = if (step > 0) first <= last else first >= last
// private var next = if (hasNext) first else finalElement
//
// override fun hasNext(): Boolean = hasNext
//
// override fun nextDate(): Date {
// val value = Date(next.time)
// if (value == finalElement) {
// if (!hasNext) throw kotlin.NoSuchElementException()
// hasNext = false
// } else {
// next += step.millis
// }
// return value
// }
//}
/** An iterator over a progression of values of type `Date`.
* @property step the number by which the value is incremented on each step.
*/
internal class DateProgressionIterator(val iterator: LocalDateIterator) : DateIterator() {
override fun hasNext(): Boolean = iterator.hasNext()
override fun nextDate(): Date = iterator.nextLocalDate().toDate
}
/**
* An iterator over a progression of values of type `LocalDate`.
* @property step the number by which the value is incremented on each step.
*/
internal class PersianDateProgressionIterator(first: PersianDate, last: PersianDate, private val step: Int) : PersianDateIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextPersianDate(): PersianDate {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
} else {
next += Period.ofDays(step)
}
return value
}
}
/**
* An iterator over a progression of values of type `LocalDate`.
* @property step the number by which the value is incremented on each step.
*/
internal class LocalDateProgressionIterator(first: LocalDate, last: LocalDate, private val step: Int) : LocalDateIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextLocalDate(): LocalDate {
val value = next
// "1. Next value: ${value.formatAsJalali()}".println()
if (value == finalElement) {
// "2. After if ${value.formatAsJalali()} >= ${finalElement.formatAsJalali()}".println()
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
} else next += Period.ofDays(step) //.println { "3. Set next value: ${(next + it).persian}" }
return value //.println { "4. return ${value.formatAsJalali()}" }
}
}
/**
* An iterator over a progression of values of type `LocalDate`.
* @property step the number by which the value is incremented on each step.
*/
internal class LocalTimeProgressionIterator(first: LocalTime, last: LocalTime, private val step: Duration) : LocalTimeIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step.seconds > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextLocalTime(): LocalTime {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
} else {
next += step
}
return value
}
}
| gpl-3.0 | fe8bfe964c3919a94d3badd8e76413f9 | 36.921053 | 133 | 0.630581 | 4.550526 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/fakes/FakeBufferingPlaybackHandler.kt | 2 | 1857 | package com.lasthopesoftware.bluewater.client.playback.file.fakes
import com.lasthopesoftware.bluewater.client.playback.file.PlayableFile
import com.lasthopesoftware.bluewater.client.playback.file.PlayedFile
import com.lasthopesoftware.bluewater.client.playback.file.PlayingFile
import com.lasthopesoftware.bluewater.client.playback.file.buffering.IBufferingPlaybackFile
import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressedPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressingPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
open class FakeBufferingPlaybackHandler : IBufferingPlaybackFile, PlayableFile, PlayingFile, PlayedFile {
var isPlaying = false
private set
protected var backingCurrentPosition = 0
fun setCurrentPosition(position: Int) {
backingCurrentPosition = position
}
override fun promisePlayback(): Promise<PlayingFile> {
isPlaying = true
return Promise(this)
}
override fun close() {}
override fun promiseBufferedPlaybackFile(): Promise<IBufferingPlaybackFile> {
return Promise(this)
}
override val progress: Promise<Duration>
get() = Duration.millis(backingCurrentPosition.toLong()).toPromise()
override fun promisePause(): Promise<PlayableFile> {
isPlaying = false
return Promise(this)
}
override fun promisePlayedFile(): ProgressedPromise<Duration, PlayedFile> {
return object : ProgressingPromise<Duration, PlayedFile>() {
override val progress: Promise<Duration>
get() = Duration.millis(backingCurrentPosition.toLong()).toPromise()
init {
resolve(this@FakeBufferingPlaybackHandler)
}
}
}
override val duration: Promise<Duration>
get() = Duration.millis(backingCurrentPosition.toLong()).toPromise()
}
| lgpl-3.0 | 7990275007d5982faf9062fb91ca617b | 33.388889 | 105 | 0.808293 | 4.308585 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/util/PayloadTypeUtil.kt | 2 | 4961 | /*
* Copyright @ 2019-Present 8x8, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.util
import org.jitsi.nlj.format.AudioRedPayloadType
import org.jitsi.nlj.format.H264PayloadType
import org.jitsi.nlj.format.OpusPayloadType
import org.jitsi.nlj.format.OtherAudioPayloadType
import org.jitsi.nlj.format.OtherVideoPayloadType
import org.jitsi.nlj.format.PayloadType
import org.jitsi.nlj.format.PayloadTypeEncoding.Companion.createFrom
import org.jitsi.nlj.format.PayloadTypeEncoding.H264
import org.jitsi.nlj.format.PayloadTypeEncoding.OPUS
import org.jitsi.nlj.format.PayloadTypeEncoding.OTHER
import org.jitsi.nlj.format.PayloadTypeEncoding.RED
import org.jitsi.nlj.format.PayloadTypeEncoding.RTX
import org.jitsi.nlj.format.PayloadTypeEncoding.VP8
import org.jitsi.nlj.format.PayloadTypeEncoding.VP9
import org.jitsi.nlj.format.RtxPayloadType
import org.jitsi.nlj.format.VideoRedPayloadType
import org.jitsi.nlj.format.Vp8PayloadType
import org.jitsi.nlj.format.Vp9PayloadType
import org.jitsi.utils.MediaType
import org.jitsi.utils.MediaType.AUDIO
import org.jitsi.utils.MediaType.VIDEO
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.LoggerImpl
import org.jitsi.xmpp.extensions.jingle.PayloadTypePacketExtension
import java.util.concurrent.ConcurrentHashMap
/**
* Utilities to deserialize [PayloadTypePacketExtension] into a
* {PayloadType}. This is currently in `jitsi-videobridge` in order to
* avoid adding the XML extensions as a dependency to
* `jitsi-media-transform`.
*
* @author Boris Grozev
* @author Brian Baldino
*/
class PayloadTypeUtil {
companion object {
private val logger: Logger = LoggerImpl(PayloadTypeUtil::class.java.name)
/**
* Creates a [PayloadType] for the payload type described in the
* given [PayloadTypePacketExtension].
* @param ext the XML extension which describes the payload type.
*/
@JvmStatic
fun create(
ext: PayloadTypePacketExtension,
mediaType: MediaType
): PayloadType? {
val parameters: MutableMap<String, String> = ConcurrentHashMap()
ext.parameters.forEach { parameter ->
// In SDP, format parameters don't necessarily come in name=value pairs (see e.g. the format used in
// RFC2198). However XEP-0167 requires a name and a value. Our SDP-to-Jingle implementation in
// lib-jitsi-meet translates a non-name=value SDP string into a parameter extension with a value but no
// name. Here we'll just ignore such parameters, because we don't currently support any and changing the
// implementation would be inconvenient (we store them mapped by name).
if (parameter.name != null) {
parameters[parameter.name] = parameter.value
} else {
logger.warn("Ignoring a format parameter with no name: " + parameter.toXML())
}
}
val rtcpFeedbackSet = ext.rtcpFeedbackTypeList.map { rtcpExtension ->
buildString {
append(rtcpExtension.feedbackType)
if (!rtcpExtension.feedbackSubtype.isNullOrBlank()) {
append(" ${rtcpExtension.feedbackSubtype}")
}
}
}.toSet()
val id = ext.id.toByte()
val encoding = createFrom(ext.name)
val clockRate = ext.clockrate
return when (encoding) {
VP8 -> Vp8PayloadType(id, parameters, rtcpFeedbackSet)
VP9 -> Vp9PayloadType(id, parameters, rtcpFeedbackSet)
H264 -> H264PayloadType(id, parameters, rtcpFeedbackSet)
RTX -> RtxPayloadType(id, parameters)
OPUS -> OpusPayloadType(id, parameters)
RED -> when (mediaType) {
AUDIO -> AudioRedPayloadType(id, clockRate, parameters)
VIDEO -> VideoRedPayloadType(id, clockRate, parameters, rtcpFeedbackSet)
else -> null
}
OTHER -> when (mediaType) {
AUDIO -> OtherAudioPayloadType(id, clockRate, parameters)
VIDEO -> OtherVideoPayloadType(id, clockRate, parameters)
else -> null
}
}
}
}
}
| apache-2.0 | d3d74895c07aee4d6b2f32bbf4f06209 | 42.902655 | 120 | 0.663777 | 4.501815 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/dropbox/DropboxAuthFlow.kt | 1 | 1341 | package com.baulsupp.okurl.services.dropbox
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.SimpleWebServer
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.kotlin.queryMap
import okhttp3.Credentials
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
object DropboxAuthFlow {
suspend fun login(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
clientId: String,
clientSecret: String
): Oauth2Token {
SimpleWebServer.forCode().use { s ->
val loginUrl =
"https://www.dropbox.com/1/oauth2/authorize?client_id=$clientId&response_type=code&redirect_uri=${s.redirectUri}"
outputHandler.openLink(loginUrl)
val code = s.waitForCode()
val basic = Credentials.basic(clientId, clientSecret)
val body = FormBody.Builder().add("code", code)
.add("grant_type", "authorization_code")
.add("redirect_uri", s.redirectUri)
.build()
val request = Request.Builder().url("https://api.dropboxapi.com/1/oauth2/token")
.post(body)
.header("Authorization", basic)
.build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(responseMap["access_token"] as String)
}
}
}
| apache-2.0 | 940137f7807501ae962cc943c3a299cf | 29.477273 | 121 | 0.712155 | 4.027027 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/configuration/src/main/kotlin/org/gradle/gradlebuild/BuildEnvironment.kt | 1 | 921 | package org.gradle.gradlebuild
import org.gradle.api.JavaVersion
import org.gradle.internal.os.OperatingSystem
object BuildEnvironment {
val isCiServer = "CI" in System.getenv()
val isTravis = "TRAVIS" in System.getenv()
val isJenkins = "JENKINS_HOME" in System.getenv()
val jvm = org.gradle.internal.jvm.Jvm.current()
val javaVersion = JavaVersion.current()
val isWindows = OperatingSystem.current().isWindows
val isSlowInternetConnection
get() = System.getProperty("slow.internet.connection", "false").toBoolean()
val agentNum: Int
get() {
if (System.getenv().containsKey("USERNAME")) {
val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
return agentNumEnv.toInt()
}
}
return 1
}
}
| apache-2.0 | 30722ae1f836d528973a71dc7d88085b | 34.423077 | 87 | 0.624321 | 4.34434 | false | false | false | false |
vania-pooh/kotlin-algorithms | src/com/freaklius/kotlin/algorithms/sort/MergeSort.kt | 1 | 1925 | package com.freaklius.kotlin.algorithms.sort
/**
* An implementation of merge sort procedure
* AveragePerformance = O(n*lg(n)), where lg(n) is a logarithm of n for base 2
*/
class MergeSort : SortAlgorithm {
override fun sort(arr: Array<Long>): Array<Long> {
sortArrayPiece(arr, 0, arr.size - 1)
return arr
}
/**
* Sorts a piece of input array using recursive calls of itself
* @param arr
* @param fromIndex
* @param toIndex
*/
private fun sortArrayPiece(arr: Array<Long>, startIndex: Int, endIndex: Int){
val pieceSize = endIndex - startIndex + 1
if (pieceSize == 1){
return //Single element piece case
}
val middleElementIndex = Math.floor((startIndex + endIndex) / 2.0).toInt()
sortArrayPiece(arr, startIndex, middleElementIndex)
sortArrayPiece(arr, middleElementIndex + 1, endIndex)
merge(arr, startIndex, middleElementIndex, endIndex)
}
/**
* Merges two subarrays of initial array arr: [startIndex; middleIndex] and [middleIndex + 1; endIndex]
* in ascending order.
* @param arr
* @param startIndex
* @param middleIndex
* @param endIndex
*/
private fun merge(arr: Array<Long>, startIndex: Int, middleIndex: Int, endIndex: Int){
val leftArray = arr.copyOfRange(startIndex, middleIndex + 1) //Left bound is exclusive, right - inclusive
val rightArray = arr.copyOfRange(middleIndex + 1, endIndex + 1)
var i = 0
var j = 0
for (k in startIndex..endIndex){
if ( (i <= leftArray.size - 1) && ( (j >= rightArray.size) || (leftArray[i] <= rightArray[j]) ) ){
arr[k] = leftArray[i]
i++
}else {
arr[k] = rightArray[j]
j++
}
}
}
override fun getName(): String {
return "MergeSort"
}
} | mit | 9cceb520af0949d008bab4b5908c8889 | 32.206897 | 113 | 0.588571 | 4.095745 | false | false | false | false |
DadosAbertosBrasil/android-radar-politico | app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/VotacoesTabFragment.kt | 1 | 4434 | package br.edu.ifce.engcomp.francis.radarpolitico.controllers
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
import br.edu.ifce.engcomp.francis.radarpolitico.R
import br.edu.ifce.engcomp.francis.radarpolitico.helpers.VolleySharedQueue
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.CDUrlFormatter
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.adapters.ProposicoesVotadasRecyclerViewAdapter
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.parsers.CDXmlParser
import br.edu.ifce.engcomp.francis.radarpolitico.models.Proposicao
import com.android.volley.Request
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import kotlinx.android.synthetic.main.content_add_politicians.*
import java.util.*
class VotacoesTabFragment : Fragment() , SwipeRefreshLayout.OnRefreshListener{
lateinit var adapter: ProposicoesVotadasRecyclerViewAdapter
lateinit var votacoesRecyclerView: RecyclerView
internal var swipeRefreshLayout: SwipeRefreshLayout? = null
internal var votacoesProgressBar: ProgressBar? = null
internal var datasource: ArrayList<Proposicao>
init {
datasource = ArrayList<Proposicao>()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.adapter = ProposicoesVotadasRecyclerViewAdapter(activity, this.datasource)
retrieveVotedPropositionsOfCurrentYearFromServer()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater!!.inflate(R.layout.fragment_votacoes, container, false)
this.votacoesRecyclerView = rootView.findViewById(R.id.votacoesRecyclerView) as RecyclerView
this.votacoesProgressBar = rootView.findViewById(R.id.votacoesProgressBar) as ProgressBar
this.swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout) as SwipeRefreshLayout
if(datasource.size > 0) {
votacoesProgressBar?.visibility = View.INVISIBLE
}
this.initRecyclerView()
this.initSwipeRefreshLayout()
return rootView
}
override fun onRefresh() {
this.datasource.clear()
this.adapter.notifyDataSetChanged()
this.retrieveVotedPropositionsOfCurrentYearFromServer()
}
private fun initRecyclerView() {
val layoutManager = LinearLayoutManager(activity)
this.votacoesRecyclerView.setHasFixedSize(false)
this.votacoesRecyclerView.layoutManager = layoutManager
this.votacoesRecyclerView.adapter = adapter
this.votacoesRecyclerView.itemAnimator = DefaultItemAnimator()
}
private fun initSwipeRefreshLayout(){
swipeRefreshLayout?.setOnRefreshListener(this)
swipeRefreshLayout?.setColorSchemeColors(R.color.colorPrimaryDark, R.color.colorPrimary, R.color.colorAccent)
}
private fun retrieveVotedPropositionsOfCurrentYearFromServer() {
val year = Calendar.getInstance().get(Calendar.YEAR);
val requestUrl = CDUrlFormatter.listarProposicoesVotadasEmPlenario(year.toString(), "")
val request = StringRequest(Request.Method.GET, requestUrl, {
stringRespose: String ->
val proposicoes = CDXmlParser.parseProposicoesFromXML(stringRespose.byteInputStream())
proposicoes.sortByDescending { it.dataVotacao }
datasource.clear()
datasource.addAll(proposicoes)
adapter.notifyDataSetChanged()
this.votacoesProgressBar?.visibility = View.INVISIBLE
this.swipeRefreshLayout?.isRefreshing = false
}, {
volleyError: VolleyError ->
Toast.makeText(activity, "Ocorreu algum erro de rede. Tente mais tarde. :/", Toast.LENGTH_SHORT).show()
this.votacoesProgressBar?.visibility = View.INVISIBLE
this.swipeRefreshLayout?.isRefreshing = false
})
VolleySharedQueue.getQueue(activity)?.add(request)
}
}
| gpl-2.0 | bff8f5674f6a64fb3180b1d05f304d71 | 39.309091 | 117 | 0.752368 | 4.687104 | false | false | false | false |
FaustXVI/kotlin-koans | src/ii_collections/_15_AllAnyAndOtherPredicates.kt | 10 | 1028 | package ii_collections
fun example2(list: List<Int>) {
val isZero: (Int) -> Boolean = { it == 0 }
val hasZero: Boolean = list.any(isZero)
val allZeros: Boolean = list.all(isZero)
val numberOfZeros: Int = list.count(isZero)
val firstPositiveNumber: Int? = list.firstOrNull { it > 0 }
}
fun Customer.isFrom(city: City): Boolean {
// Return true if the customer is from the given city
todoCollectionTask()
}
fun Shop.checkAllCustomersAreFrom(city: City): Boolean {
// Return true if all customers are from the given city
todoCollectionTask()
}
fun Shop.hasCustomerFrom(city: City): Boolean {
// Return true if there is at least one customer from the given city
todoCollectionTask()
}
fun Shop.countCustomersFrom(city: City): Int {
// Return the number of customers from the given city
todoCollectionTask()
}
fun Shop.findAnyCustomerFrom(city: City): Customer? {
// Return a customer who lives in the given city, or null if there is none
todoCollectionTask()
}
| mit | 924c1926a8d0c86415eeb8588aa7d459 | 25.358974 | 78 | 0.700389 | 4.031373 | false | false | false | false |
android/camera-samples | Camera2SlowMotion/app/src/main/java/com/example/android/camera2/slowmo/CameraActivity.kt | 1 | 2218 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera2.slowmo
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.android.camera2.slowmo.databinding.ActivityCameraBinding
class CameraActivity : AppCompatActivity() {
private lateinit var activityCameraBinding: ActivityCameraBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityCameraBinding = ActivityCameraBinding.inflate(layoutInflater)
setContentView(activityCameraBinding.root)
}
override fun onResume() {
super.onResume()
// Before setting full screen flags, we must wait a bit to let UI settle; otherwise, we may
// be trying to set app to immersive mode before it's ready and the flags do not stick
activityCameraBinding.fragmentContainer.postDelayed({
activityCameraBinding.fragmentContainer.systemUiVisibility = FLAGS_FULLSCREEN
}, IMMERSIVE_FLAG_TIMEOUT)
}
companion object {
/** Combination of all flags required to put activity into immersive mode */
const val FLAGS_FULLSCREEN =
View.SYSTEM_UI_FLAG_LOW_PROFILE or
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
/** Milliseconds used for UI animations */
const val ANIMATION_FAST_MILLIS = 50L
const val ANIMATION_SLOW_MILLIS = 100L
private const val IMMERSIVE_FLAG_TIMEOUT = 500L
}
}
| apache-2.0 | 424af46e78c9ea3191b41299a62acd3a | 38.607143 | 99 | 0.708296 | 4.739316 | false | false | false | false |
angryziber/picasa-gallery | src/photos/Config.kt | 1 | 811 | package photos
import java.util.*
object Config {
private val props = Properties().apply {
Config.javaClass.getResourceAsStream("/config.properties").use { load(it) }
Config.javaClass.getResourceAsStream("/local.properties")?.use { load(it) }
}
val apiBase = "https://photoslibrary.googleapis.com"
val oauthScopes = "profile https://www.googleapis.com/auth/photoslibrary.readonly"
val oauthClientId = get("google.oauth.clientId")
val oauthClientSecret = get("google.oauth.clientSecret")
var oauthRefreshToken = get("google.oauth.refreshToken")
val analyticsId = get("google.analytics")
val mapsKey = get("google.maps.key")
val startTime = System.currentTimeMillis() / 1000 % 1000000
operator fun get(key: String) = (props[key] as String?).let { if (it == "") null else it }
} | gpl-3.0 | 63f886bf4797afcd2b40918e0ae9bd90 | 34.304348 | 92 | 0.720099 | 3.995074 | false | true | false | false |
vase4kin/TeamCityApp | features/properties/feature/src/main/java/teamcityapp/features/properties/feature/view/PropertyItem.kt | 1 | 2310 | /*
* Copyright 2020 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teamcityapp.features.properties.feature.view
import androidx.core.content.ContextCompat
import com.xwray.groupie.databinding.BindableItem
import teamcityapp.features.properties.feature.R
import teamcityapp.features.properties.feature.databinding.ItemPropertyBinding
import teamcityapp.features.properties.feature.model.InternalProperty
import teamcityapp.features.properties.feature.router.PropertiesRouter
class PropertyItem(
private val property: InternalProperty,
private val router: PropertiesRouter
) : BindableItem<ItemPropertyBinding>() {
override fun getLayout() = R.layout.item_property
override fun bind(viewBinding: ItemPropertyBinding, position: Int) {
viewBinding.apply {
title.text = property.name
val valueIsEmpty = property.value.isEmpty()
if (valueIsEmpty) {
subTitle.text = root.context.getString(R.string.text_property_value_empty)
subTitle.setTextColor(
ContextCompat.getColor(
root.context,
R.color.material_on_background_disabled
)
)
} else {
subTitle.text = property.value
subTitle.setTextColor(
ContextCompat.getColor(
root.context,
R.color.material_on_background_emphasis_high_type
)
)
root.setOnClickListener {
router.showCopyValueBottomSheet(
property.name,
property.value
)
}
}
}
}
}
| apache-2.0 | f3d2c614e228b119aa3e303a675b47b5 | 36.258065 | 90 | 0.62987 | 5.088106 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/moderation/CommandRaid.kt | 1 | 4230 | package me.mrkirby153.KirBot.command.executors.moderation
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.annotations.LogInModlogs
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.module.ModuleManager
import me.mrkirby153.KirBot.modules.AntiRaid
import me.mrkirby153.KirBot.user.CLEARANCE_MOD
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.embed.b
import me.mrkirby153.KirBot.utils.uploadToArchive
import net.dv8tion.jda.api.Permission
import javax.inject.Inject
class CommandRaid @Inject constructor(private val antiRaid: AntiRaid){
@Command(name = "info", arguments = ["<id:string>"], clearance = CLEARANCE_MOD,
category = CommandCategory.MODERATION, parent = "raid")
@IgnoreWhitelist
fun raidInfo(context: Context, cmdContext: CommandContext) {
val raid = antiRaid.getRaid(context.guild,
cmdContext.getNotNull("id")) ?: throw CommandException("Raid not found")
val users = buildString {
raid.members.forEach { member ->
appendln("${member.id} (${member.name})")
}
appendln()
appendln()
appendln("Only IDs:")
appendln(raid.members.joinToString("\n") { it.id })
}
val uploadUrl = uploadToArchive(users)
val msg = buildString {
appendln(b("==[ RAID ${raid.id} ] =="))
appendln("${raid.members.size} members were involved in the raid")
appendln()
appendln("View the list of users: $uploadUrl")
}
context.channel.sendMessage(msg).queue()
}
@Command(name = "ban", arguments = ["<id:string>"], parent = "raid", clearance = CLEARANCE_MOD,
category = CommandCategory.MODERATION, permissions = [Permission.BAN_MEMBERS])
@LogInModlogs
@IgnoreWhitelist
fun raidBan(context: Context, cmdContext: CommandContext) {
val raid = antiRaid.getRaid(context.guild,
cmdContext.getNotNull("id")) ?: throw CommandException("Raid not found")
antiRaid.punishAllRaiders(context.guild, raid.id, "BAN",
"Member of raid ${raid.id}")
context.send().success("Banning ${raid.members.size} raiders").queue()
}
@Command(name = "kick", arguments = ["<id:string>"], parent = "raid", clearance = CLEARANCE_MOD,
category = CommandCategory.MODERATION, permissions = [Permission.KICK_MEMBERS])
@LogInModlogs
@IgnoreWhitelist
fun raidKick(context: Context, cmdContext: CommandContext) {
val raid = antiRaid.getRaid(context.guild,
cmdContext.getNotNull("id")) ?: throw CommandException("Raid not found")
antiRaid.punishAllRaiders(context.guild, raid.id, "KICK",
"Member of raid ${raid.id}")
context.send().success("Kicking ${raid.members.size} raiders").queue()
}
@Command(name = "unmute", arguments = ["<id:string>"], parent = "raid",
clearance = CLEARANCE_MOD, category = CommandCategory.MODERATION, permissions = [Permission.MANAGE_ROLES])
@LogInModlogs
@IgnoreWhitelist
fun raidUnmute(context: Context, cmdContext: CommandContext) {
val raid = antiRaid.getRaid(context.guild,
cmdContext.getNotNull("id")) ?: throw CommandException("Raid not found")
antiRaid.unmuteAllRaiders(context.guild, raid.id)
context.send().success("Unmuting ${raid.members.size} raiders").queue()
}
@Command(name = "dismiss", parent = "raid", clearance = CLEARANCE_MOD,
category = CommandCategory.MODERATION)
@LogInModlogs
@IgnoreWhitelist
fun dismiss(context: Context, cmdContext: CommandContext) {
val antiRaid = antiRaid
val raid = antiRaid.activeRaids[context.guild.id]
?: throw CommandException("There is no active raid")
antiRaid.dismissActiveRaid(context.guild)
context.send().success("Dismissed raid and unmuted members").queue()
}
} | mit | 9c0299528929b1b8e1d9e6853a3e54c6 | 44.010638 | 118 | 0.670449 | 4.024738 | false | false | false | false |
opentok/opentok-android-sdk-samples | Advanced-Audio-Driver-Kotlin/app/src/main/java/com/tokbox/sample/advancedaudiodriver/MainActivity.kt | 1 | 8095 | package com.tokbox.sample.advancedaudiodriver
import android.Manifest
import android.opengl.GLSurfaceView
import android.os.Bundle
import android.util.Log
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.opentok.android.AudioDeviceManager
import com.opentok.android.BaseVideoRenderer
import com.opentok.android.OpentokError
import com.opentok.android.Publisher
import com.opentok.android.PublisherKit
import com.opentok.android.PublisherKit.PublisherListener
import com.opentok.android.Session
import com.opentok.android.Session.SessionListener
import com.opentok.android.Stream
import com.opentok.android.Subscriber
import com.opentok.android.SubscriberKit
import com.opentok.android.SubscriberKit.VideoListener
import com.tokbox.sample.advancedaudiodriver.MainActivity
import com.tokbox.sample.advancedaudiodriver.OpenTokConfig.description
import com.tokbox.sample.advancedaudiodriver.OpenTokConfig.isValid
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
class MainActivity : AppCompatActivity(), PermissionCallbacks {
private var session: Session? = null
private var publisher: Publisher? = null
private var subscriber: Subscriber? = null
private lateinit var publisherViewContainer: RelativeLayout
private lateinit var subscriberViewContainer: LinearLayout
private val publisherListener: PublisherListener = object : PublisherListener {
override fun onStreamCreated(publisherKit: PublisherKit, stream: Stream) {
Log.d(TAG, "onStreamCreated: Own stream ${stream.streamId} created")
}
override fun onStreamDestroyed(publisherKit: PublisherKit, stream: Stream) {
Log.d(TAG, "onStreamDestroyed: Own stream ${stream.streamId} destroyed")
}
override fun onError(publisherKit: PublisherKit, opentokError: OpentokError) {
finishWithMessage("PublisherKit error: ${opentokError.message}")
}
}
private val sessionListener: SessionListener = object : SessionListener {
override fun onConnected(session: Session) {
Log.d(TAG, "onConnected: Connected to session ${session.sessionId}")
publisher = Publisher.Builder(this@MainActivity).build().also {
it.setPublisherListener(publisherListener)
it.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL)
}
publisherViewContainer.addView(publisher?.view)
(publisher?.view as? GLSurfaceView)?.let {
it.setZOrderOnTop(true)
}
session.publish(publisher)
}
override fun onDisconnected(session: Session) {
Log.d(TAG, "onDisconnected: disconnected from session ${session.sessionId}")
[email protected] = null
}
override fun onError(session: Session, opentokError: OpentokError) {
finishWithMessage("Session error: ${opentokError.message}")
}
override fun onStreamReceived(session: Session, stream: Stream) {
Log.d(TAG, "onStreamReceived: New stream ${stream.streamId} in session ${session.sessionId}")
if (subscriber != null) {
return
}
subscribeToStream(stream)
}
override fun onStreamDropped(session: Session, stream: Stream) {
Log.d(TAG, "onStreamDropped: Stream ${stream.streamId} dropped from session ${session.sessionId}")
if (subscriber == null) {
return
}
if (subscriber?.stream == stream) {
subscriberViewContainer.removeView(subscriber?.view)
subscriber = null
}
}
}
private val videoListener: VideoListener = object : VideoListener {
override fun onVideoDataReceived(subscriberKit: SubscriberKit) {
subscriber?.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL)
subscriberViewContainer.addView(subscriber?.view)
}
override fun onVideoDisabled(subscriberKit: SubscriberKit, s: String) {}
override fun onVideoEnabled(subscriberKit: SubscriberKit, s: String) {}
override fun onVideoDisableWarning(subscriberKit: SubscriberKit) {}
override fun onVideoDisableWarningLifted(subscriberKit: SubscriberKit) {}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (!isValid) {
finishWithMessage("Invalid OpenTokConfig. $description")
return
}
publisherViewContainer = findViewById(R.id.publisherview)
subscriberViewContainer = findViewById(R.id.subscriberview)
requestPermissions()
}
override fun onPause() {
super.onPause()
if (session == null) {
return
}
session?.onPause()
if (isFinishing) {
disconnectSession()
}
}
override fun onResume() {
super.onResume()
if (session == null) {
return
}
session?.onResume()
}
override fun onDestroy() {
disconnectSession()
super.onDestroy()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
Log.d(TAG, "onPermissionsGranted:$requestCode: $perms")
}
override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
finishWithMessage("onPermissionsDenied: $requestCode: $perms")
}
@AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
private fun requestPermissions() {
val perms = arrayOf(
Manifest.permission.INTERNET,
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.BLUETOOTH
)
if (EasyPermissions.hasPermissions(this, *perms)) {
val advancedAudioDevice = AdvancedAudioDevice(this)
AudioDeviceManager.setAudioDevice(advancedAudioDevice)
session = Session.Builder(this, OpenTokConfig.API_KEY, OpenTokConfig.SESSION_ID).build().also {
it.setSessionListener(sessionListener)
it.connect(OpenTokConfig.TOKEN)
}
} else {
EasyPermissions.requestPermissions(
this,
getString(R.string.rationale_video_app),
PERMISSIONS_REQUEST_CODE,
*perms
)
}
}
private fun subscribeToStream(stream: Stream) {
subscriber = Subscriber.Builder(this, stream).build().also {
it.setVideoListener(videoListener)
}
session?.subscribe(subscriber)
}
private fun disconnectSession() {
if (session == null) {
return
}
if (subscriber != null) {
subscriberViewContainer.removeView(subscriber?.view)
session?.unsubscribe(subscriber)
subscriber = null
}
if (publisher != null) {
publisherViewContainer.removeView(publisher?.view)
session?.unpublish(publisher)
publisher = null
}
session?.disconnect()
}
private fun finishWithMessage(message: String) {
Log.e(TAG, message)
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
finish()
}
companion object {
private val TAG = MainActivity::class.java.simpleName
private const val PERMISSIONS_REQUEST_CODE = 124
}
} | mit | ff926a6a32c1dcb8ae6c3a28948ab695 | 35.142857 | 115 | 0.666831 | 5.149491 | false | false | false | false |
themasterapp/master-app-android | MasterApp/app/src/main/java/br/com/ysimplicity/masterapp/helper/TurbolinksHelper.kt | 1 | 4314 | package br.com.ysimplicity.masterapp.helper
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import br.com.ysimplicity.masterapp.R
import br.com.ysimplicity.masterapp.helper.jsbridge.JsBridge
import br.com.ysimplicity.masterapp.helper.jsbridge.JsListener
import br.com.ysimplicity.masterapp.presentation.activity.MainActivity
import br.com.ysimplicity.masterapp.presentation.activity.NoDrawerActivity
import br.com.ysimplicity.masterapp.utils.Constants
import com.basecamp.turbolinks.TurbolinksAdapter
import com.basecamp.turbolinks.TurbolinksSession
import com.basecamp.turbolinks.TurbolinksView
/**
* Created by Marcelo on 08/11/2017
*/
class TurbolinksHelper(private val context: Context,
private val activity: Activity,
private val turbolinksView: TurbolinksView) : JsListener, TurbolinksAdapter {
init {
setupTurbolinks()
}
@SuppressLint("SetJavaScriptEnabled")
private fun setupTurbolinks() {
TurbolinksSession.getDefault(context).setDebugLoggingEnabled(true)
TurbolinksSession.getDefault(context).webView.settings.userAgentString = "TurbolinksDemo+Android"
TurbolinksSession.getDefault(context).webView.settings.javaScriptEnabled = true
TurbolinksSession.getDefault(context).webView.addJavascriptInterface(JsBridge(context, this), "android")
}
override fun loginSuccessful() {
redirectToSelf(Constants.URL_HOME, R.string.drawer_recipes_text)
}
override fun visitProposedToLocationWithAction(location: String, action: String) {
when {
action.equals(Constants.ACTION_REPLACE) -> visit(location, true)
location.contains(Constants.URL_RECIPES) -> visitNoDrawerActivity(location)
location.contains(Constants.URL_SIGN_UP) -> redirectToSelf(location, R.string.drawer_signup_text, true)
location.contains(Constants.URL_NEW_PASSWORD) -> visitNoDrawerActivity(location)
else -> visitToNewActivity(location)
}
}
override fun onPageFinished() {}
override fun onReceivedError(errorCode: Int) {}
override fun pageInvalidated() {}
override fun requestFailedWithStatusCode(statusCode: Int) {}
override fun visitCompleted() {}
fun visit(url: String) = visit(url, false)
fun visit(url: String, withCachedSnapshot: Boolean) {
if (withCachedSnapshot) {
TurbolinksSession.getDefault(context)
.activity(activity)
.adapter(this)
.restoreWithCachedSnapshot(true)
.view(turbolinksView)
.visit(url)
} else {
TurbolinksSession.getDefault(context)
.activity(activity)
.adapter(this)
.view(turbolinksView)
.visit(url)
}
}
fun redirectToSelf(url: String, idResourceToolbarTitle: Int, isFullUrl: Boolean) {
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
if (!isFullUrl) {
intent.putExtra(Constants.INTENT_URL, context.getString(R.string.base_url) + url)
} else {
intent.putExtra(Constants.INTENT_URL, url)
}
intent.putExtra(Constants.TOOLBAR_TITLE, context.getString(idResourceToolbarTitle))
activity.startActivity(intent)
activity.overridePendingTransition(0, 0)
activity.finish()
}
fun redirectToSelf(url: String, idResourceToolbarTitle: Int) {
redirectToSelf(url, idResourceToolbarTitle, false)
}
private fun visitNoDrawerActivity(location: String) {
val intent = Intent(context, NoDrawerActivity::class.java)
intent.putExtra(Constants.INTENT_URL, location)
intent.putExtra(Constants.TOOLBAR_TITLE, context.getString(R.string.drawer_recipes_text))
activity.startActivity(intent)
}
private fun visitToNewActivity(url: String) {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(Constants.INTENT_URL, url)
activity.startActivity(intent)
}
} | mit | 03abf50b0a4778440b5ff51e5e219e96 | 36.521739 | 115 | 0.690311 | 4.267062 | false | false | false | false |
jjoller/foxinabox | src/jjoller/foxinabox/playermodels/montecarlo/ConformityDealer.kt | 1 | 2316 | package jjoller.foxinabox.playermodels.montecarlo
import java.util.*
import jjoller.foxinabox.Card
import jjoller.foxinabox.Dealer
import jjoller.foxinabox.Phase
import jjoller.foxinabox.TexasHand
/**
* Deals cards which are more likely.
*/
class ConformityDealer : Dealer {
constructor(hero: TexasHand.Player, hand: TexasHand) {
heroName = hero.name
heroHoldings = hero.holdings().get()
tableCards = hand.tableCards()
deck = ArrayList<Card>()
deck.addAll(Card.values())
deck.removeAll(heroHoldings)
deck.removeAll(tableCards)
removed = ArrayList<Card>()
tableCardsIter = tableCards.iterator()
}
private val heroName: String
private val heroHoldings: EnumSet<Card>
private val tableCards: List<Card>
private var tableCardsIter: Iterator<Card>
private val deck: MutableList<Card>
private val removed: MutableList<Card>
private val random = Random()
override fun reset() {
deck.addAll(removed)
removed.clear()
tableCardsIter = tableCards.iterator()
}
override fun dealTableCards(hand: TexasHand) {
when (hand.phase()) {
Phase.PRE_FLOP -> hand.flop = EnumSet.of(tableCard(), tableCard(), tableCard())
Phase.FLOP -> hand.turn = tableCard()
Phase.TURN -> hand.river = tableCard()
else -> throw IllegalStateException()
}
}
override fun dealHoleCards(player: TexasHand.Player) {
if (player.name === heroName)
player.setCards(heroHoldings)
else
// TODO select cards according to a Bandit model to choose cards which are more conform with the player model
player.setCards(EnumSet.of(removeRandomFromDeck(), removeRandomFromDeck()))
// println("set cards of " + player.name + " to " + player.holdings())
}
fun update(player: TexasHand.Player, conformity: Double) {
// TODO
}
private fun tableCard(): Card {
if (tableCardsIter.hasNext())
return tableCardsIter.next()
else
return removeRandomFromDeck()
}
private fun removeRandomFromDeck(): Card {
val card = deck.removeAt(random.nextInt(deck.size))
removed.add(card)
return card
}
}
| mit | 63489ecf069c9d205418fd69feda0c75 | 27.95 | 117 | 0.639465 | 4.041885 | false | false | false | false |
GreaseMonk/android-timetable | timetable/src/main/java/nl/greasemonk/timetable/PlanView.kt | 1 | 7699 | /*
* Copyright (c) 2018 .
* This file is released under the Apache-2.0 license and part of the TimeTable repository located at:
* https://github.com/greasemonk/android-timetable-core
* See the "LICENSE" file at the root of the repository or go to the address below for the full license details.
* https://github.com/GreaseMonk/android-timetable-core/blob/develop/LICENSE
*/
package nl.greasemonk.timetable
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import nl.greasemonk.timetable.enums.PlanViewMode
import nl.greasemonk.timetable.enums.Style
import nl.greasemonk.timetable.extensions.drawDiagonalLinesStyle
import nl.greasemonk.timetable.extensions.drawItemArrows
import nl.greasemonk.timetable.extensions.drawItemText
import nl.greasemonk.timetable.extensions.drawTodayLine
import nl.greasemonk.timetable.interfaces.IPlanItem
import nl.greasemonk.timetable.models.TimeRange
import java.util.*
import java.util.Calendar.*
@Suppress("NAME_SHADOWING")
internal class PlanView : BasePlanView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private var coordCache: MutableList<Pair<IPlanItem, Rect>> = mutableListOf()
var clickListener: ((IPlanItem) -> Unit)? = null
private var rowItems: List<List<IPlanItem>> = mutableListOf()
override fun init(context: Context, attrs: AttributeSet?) {
scaleWithMultiplierSetting = true
super.init(context, attrs)
}
override fun onDraw(canvas: Canvas) {
canvas.apply {
coordCache = mutableListOf()
drawVerticalGridLines(this)
drawAllItems(this)
canvas.drawTodayLine(todayPaint, displayedRange)
}
}
/**
* Set the items
*/
fun setItems(planViewMode: PlanViewMode, timeRange: TimeRange, items: List<IPlanItem>) {
this.planViewMode = planViewMode
this.displayedRange = timeRange
this.rowItems = this.getRowItems(items)
requestLayout()
invalidate()
}
/**
* Draws all items onto the given Canvas
*
* @param canvas the Canvas to draw all items on
*/
private fun drawAllItems(canvas: Canvas) {
for ((rowNum, row) in rowItems.withIndex()) {
drawRow(canvas, row, rowNum)
}
}
/**
* Draw the rows for the given list of IPlanItems
*
* Only give a list of non-overlapping IPlanItems because this function
* will draw items on to the row, even if the items overlap
*
* @param canvas the canvas to draw on
* @param items the list of IPlanItems to draw onto the row
* @param row the row to draw
*/
private fun drawRow(canvas: Canvas, items: List<IPlanItem>, row: Int) {
val rowHeight = getRowHeight()
val lineYpos = row * rowHeight + (verticalBarPadding * 0.5f) - 0.5f
// Draw the weekend background
val columnWidth = getColumnWidth()
val calendar = Calendar.getInstance()
calendar.timeInMillis = this.displayedRange.start
for (i: Int in 0..columnCount) {
if (calendar.get(DAY_OF_WEEK) == SATURDAY || calendar.get(DAY_OF_WEEK) == SUNDAY) {
val weekendRect = Rect((i * columnWidth).toInt(), (row * rowHeight).toInt(), (i * columnWidth + columnWidth).toInt(), (row * rowHeight + rowHeight).toInt())
canvas.drawRect(weekendRect, gridLinePaint)
}
calendar.add(DAY_OF_YEAR, 1)
}
// Draw a horizontal line at the bottom of each row
canvas.drawLine(0f, lineYpos, width.toFloat(), lineYpos, gridLinePaint)
for (item in items) {
drawItem(canvas, item, row)
}
}
/**
* Draw the rectangle and text for the given item
*
*/
private fun drawItem(canvas: Canvas, item: IPlanItem, row: Int) {
val endOfWeekMillis = displayedRange.endInclusive
val columnIndexes = getColumnIndexes(item)
val rowHeight = getRowHeight()
val columnWidth = getColumnWidth()
val startY = row * rowHeight + verticalBarPadding
val endY = startY + rowHeight - verticalBarPadding
val startX = columnWidth * columnIndexes.first
val endX = columnWidth + (columnWidth * columnIndexes.second)
val rect = RectF(startX, startY, endX, endY)
val roundedRect = Rect()
rect.round(roundedRect)
val itemColor = item.planItemColor ?: Color.YELLOW
val shader = LinearGradient(0f, 0f, 0f, 50f, intArrayOf(itemColor, itemColor.lighter()), null, Shader.TileMode.CLAMP)
coordCache.add(Pair(item, Rect(roundedRect.left, roundedRect.top, roundedRect.right, roundedRect.bottom)))
val itemIsSelected = delegate?.getLastClickedPlanItem() == item
barPaint.color = if (itemIsSelected) itemColor.lighter() else itemColor
barPaint.shader = shader
drawable.paint.set(barPaint)
drawable.bounds = roundedRect
drawable.draw(canvas)
// Draw a 'selected' effect on the plan item
if (delegate?.getLastClickedPlanItem() == item) {
drawable.paint.set(barStrokePaint)
val offset: Int = (barStrokeSize / 4).toInt()
drawable.bounds = Rect(roundedRect.left + offset, roundedRect.top + offset, roundedRect.right - offset, roundedRect.bottom - offset)
drawable.draw(canvas)
}
// Draw the item arrows if needed
val showLeftArrow = columnIndexes.first == 0 && item.timeRange.start < displayedRange.start
val showRightArrow = columnIndexes.second == (columnCount - 1) && item.timeRange.endInclusive > endOfWeekMillis
canvas.drawItemArrows(arrowLeftDrawable, arrowRightDrawable, arrowHeight, arrowWidth, showLeftArrow, showRightArrow, rect)
if (item.planStyle == Style.DIAGONAL_LINES) {
canvas.drawDiagonalLinesStyle(diagonalLinesPaint, rect)
}
// Define the rect for the text to draw in, and finally draw the text.
val textRectStart: Int = roundedRect.left + (if (showLeftArrow) arrowWidth.toInt() else 0)
val textRectEnd: Int = roundedRect.right - (if (showRightArrow) arrowWidth.toInt() else 0)
val textRect = Rect(textRectStart, roundedRect.top, textRectEnd, roundedRect.bottom)
canvas.drawItemText(textPaint, item.planItemName, textRect)
}
/**
* Handle touch screen motion events.
*
* @return true if the action was intercepted
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_UP -> {
if (clickListener != null) {
val clickedItem = itemAtPosition(event.x.toInt(), event.y.toInt())
if (clickedItem != null) {
clickListener!!.invoke(clickedItem)
invalidate()
}
}
}
}
return true
}
/**
* Get the IPlanItem at a specific position, of there is any
*
* @param x the x position to look for
* @param y the y position to look for
*
* @return the first IPlanItem that was found at the position, if any
*/
private fun itemAtPosition(x: Int, y: Int): IPlanItem? {
for (entry in coordCache) {
if (entry.second.contains(x, y)) {
return entry.first
}
}
return null
}
}
| apache-2.0 | 07c081f4fd3fa540de6e145d1de361d3 | 37.495 | 172 | 0.649955 | 4.232545 | false | false | false | false |
NooAn/bytheway | app/src/main/java/ru/a1024bits/bytheway/service/FCMService.kt | 1 | 3714 | package ru.a1024bits.bytheway.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import android.os.Build
import android.support.v4.app.NotificationCompat
import android.support.v4.content.LocalBroadcastManager
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import ru.a1024bits.bytheway.R
import ru.a1024bits.bytheway.ui.activity.MenuActivity
import ru.a1024bits.bytheway.util.Constants
import ru.a1024bits.bytheway.util.Constants.NOTIFICATION_CMD
import ru.a1024bits.bytheway.util.Constants.NOTIFICATION_TITLE
import ru.a1024bits.bytheway.util.Constants.NOTIFICATION_VALUE
class FCMService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
var notificationTitle: String? = null
var notificationBody: String? = null
var dataValue: String? = null
var dataCmd: String? = null
val data = remoteMessage?.getData()
if (data != null) {
dataCmd = data[NOTIFICATION_CMD]
dataValue = data[NOTIFICATION_VALUE]
if (data.containsKey(NOTIFICATION_TITLE)) notificationTitle = data[NOTIFICATION_TITLE]
}
if (remoteMessage?.notification != null) {
notificationTitle = remoteMessage.notification?.title
notificationBody = remoteMessage.notification?.body
}
if (dataCmd?.startsWith("fcm_") == true) {
val intent = Intent(Constants.FCM_SRV)
intent.putExtra(NOTIFICATION_CMD, dataCmd)
intent.putExtra(NOTIFICATION_VALUE, dataValue)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
} else {
val intent = Intent(this, MenuActivity::class.java)
intent.putExtra(NOTIFICATION_CMD, dataCmd)
intent.putExtra(NOTIFICATION_VALUE, dataValue)
createNotification(notificationTitle, notificationBody, intent)
}
}
private fun createNotification(notificationTitle: String?, notificationBody: String?, intent: Intent) {
val pendingIntent = PendingIntent.getActivity(this, 109/* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val channelId = getString(R.string.app_name)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.icon_logo_small)
.setBadgeIconType(R.drawable.icon_logo_small)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.icon_logo))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId,
"bytheway",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(1 /* ID of notification */, notificationBuilder.build())
}
} | mit | b644903122dc801bf5f2943314120053 | 41.701149 | 107 | 0.702208 | 5.09465 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/jvmMain/kotlin/nl/adaptivity/util/activation/UrlDataSource.kt | 1 | 2488 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util.activation
import javax.activation.DataSource
import javax.activation.MimetypesFileTypeMap
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.URL
import java.net.URLConnection
class UrlDataSource @Throws(IOException::class)
constructor(private val url: URL) : DataSource {
private var contentType: String
private val inputStream: InputStream
val headers: Map<String, List<String>>
init {
val connection: URLConnection
connection = url.openConnection()
this.contentType = connection.contentType.let<String?, String?> {
if (it == null || it == "content/unknown") getMimeTypeForFileName(
url.file
) else it
} ?: "application/binary"
inputStream = connection.getInputStream()
headers = connection.headerFields
}
override fun getContentType(): String {
return contentType
}
@Throws(IOException::class)
override fun getInputStream(): InputStream {
return inputStream
}
override fun getName(): String {
return url.path
}
@Throws(IOException::class)
override fun getOutputStream(): OutputStream {
throw UnsupportedOperationException("Not allowed")
}
companion object {
private var _mimeMap: MimetypesFileTypeMap? = null
private fun getMimeTypeForFileName(fileName: String): String {
if (_mimeMap == null) {
_mimeMap = MimetypesFileTypeMap()
_mimeMap!!.addMimeTypes("text/css css\ntext/html htm html shtml\nimage/png png\n")
}
return _mimeMap!!.getContentType(fileName)
}
}
}
| lgpl-3.0 | c2c53a51f95cadb776ac205cdf1ae640 | 28.270588 | 112 | 0.663987 | 4.803089 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/persistence/WPAndroidDatabase.kt | 1 | 8299 | package org.wordpress.android.fluxc.persistence
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.wordpress.android.fluxc.persistence.BloggingRemindersDao.BloggingReminders
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOffer
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOfferFeature
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOfferId
import org.wordpress.android.fluxc.persistence.bloggingprompts.BloggingPromptsDao
import org.wordpress.android.fluxc.persistence.bloggingprompts.BloggingPromptsDao.BloggingPromptEntity
import org.wordpress.android.fluxc.persistence.comments.CommentsDao
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.persistence.coverters.StringListConverter
import org.wordpress.android.fluxc.persistence.dashboard.CardsDao
import org.wordpress.android.fluxc.persistence.dashboard.CardsDao.CardEntity
@Database(
version = 8,
entities = [
BloggingReminders::class,
PlanOffer::class,
PlanOfferId::class,
PlanOfferFeature::class,
CommentEntity::class,
CardEntity::class,
BloggingPromptEntity::class
]
)
@TypeConverters(
value = [
StringListConverter::class
]
)
abstract class WPAndroidDatabase : RoomDatabase() {
abstract fun bloggingRemindersDao(): BloggingRemindersDao
abstract fun planOffersDao(): PlanOffersDao
abstract fun commentsDao(): CommentsDao
abstract fun dashboardCardsDao(): CardsDao
abstract fun bloggingPromptsDao(): BloggingPromptsDao
@Suppress("MemberVisibilityCanBePrivate")
companion object {
const val WP_DB_NAME = "wp-android-database"
fun buildDb(applicationContext: Context) = Room.databaseBuilder(
applicationContext,
WPAndroidDatabase::class.java,
WP_DB_NAME
)
.fallbackToDestructiveMigration()
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_2_3)
.addMigrations(MIGRATION_3_4)
.addMigrations(MIGRATION_5_6)
.addMigrations(MIGRATION_7_8)
.build()
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL(
"CREATE TABLE IF NOT EXISTS `PlanOffers` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`internalPlanId` INTEGER NOT NULL, " +
"`name` TEXT, " +
"`shortName` TEXT, " +
"`tagline` TEXT, " +
"`description` TEXT, " +
"`icon` TEXT" +
")"
)
execSQL(
"CREATE UNIQUE INDEX IF NOT EXISTS `index_PlanOffers_internalPlanId` " +
"ON `PlanOffers` (`internalPlanId`)"
)
execSQL(
"CREATE TABLE IF NOT EXISTS `PlanOfferIds` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`productId` INTEGER NOT NULL, " +
"`internalPlanId` INTEGER NOT NULL, " +
"FOREIGN KEY(`internalPlanId`) REFERENCES `PlanOffers`(`internalPlanId`) " +
"ON UPDATE NO ACTION ON DELETE CASCADE" +
")"
)
execSQL(
"CREATE TABLE IF NOT EXISTS `PlanOfferFeatures` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`internalPlanId` INTEGER NOT NULL, " +
"`stringId` TEXT, " +
"`name` TEXT, " +
"`description` TEXT, " +
"FOREIGN KEY(`internalPlanId`) REFERENCES `PlanOffers`(`internalPlanId`) " +
"ON UPDATE NO ACTION ON DELETE CASCADE" +
")"
)
}
}
}
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL(
"CREATE TABLE IF NOT EXISTS `Comments` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`remoteCommentId` INTEGER NOT NULL, " +
"`remotePostId` INTEGER NOT NULL, " +
"`remoteParentCommentId` INTEGER NOT NULL, " +
"`localSiteId` INTEGER NOT NULL, " +
"`remoteSiteId` INTEGER NOT NULL, " +
"`authorUrl` TEXT, " +
"`authorName` TEXT, " +
"`authorEmail` TEXT, " +
"`authorProfileImageUrl` TEXT, " +
"`postTitle` TEXT, " +
"`status` TEXT, " +
"`datePublished` TEXT, " +
"`publishedTimestamp` INTEGER NOT NULL, " +
"`content` TEXT, " +
"`url` TEXT, " +
"`hasParent` INTEGER NOT NULL, " +
"`parentId` INTEGER NOT NULL, " +
"`iLike` INTEGER NOT NULL)"
)
}
}
}
val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL("ALTER TABLE BloggingReminders ADD COLUMN hour INTEGER DEFAULT 10 NOT NULL")
execSQL("ALTER TABLE BloggingReminders ADD COLUMN minute INTEGER DEFAULT 0 NOT NULL")
}
}
}
val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL("DROP TABLE Comments")
execSQL(
"CREATE TABLE `Comments` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`remoteCommentId` INTEGER NOT NULL, " +
"`remotePostId` INTEGER NOT NULL, " +
"`localSiteId` INTEGER NOT NULL, " +
"`remoteSiteId` INTEGER NOT NULL, " +
"`authorUrl` TEXT, " +
"`authorName` TEXT, " +
"`authorEmail` TEXT, " +
"`authorProfileImageUrl` TEXT, " +
"`authorId` INTEGER NOT NULL , " +
"`postTitle` TEXT, " +
"`status` TEXT, " +
"`datePublished` TEXT, " +
"`publishedTimestamp` INTEGER NOT NULL, " +
"`content` TEXT, " +
"`url` TEXT, " +
"`hasParent` INTEGER NOT NULL, " +
"`parentId` INTEGER NOT NULL, " +
"`iLike` INTEGER NOT NULL)"
)
}
}
}
val MIGRATION_7_8 = object : Migration(7, 8) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL(
"ALTER TABLE BloggingReminders ADD COLUMN isPromptRemindersOptedIn" +
" INTEGER DEFAULT 0 NOT NULL"
)
}
}
}
}
}
| gpl-2.0 | 26cd72bf574e76dfc513d27abfee83ff | 43.143617 | 105 | 0.492589 | 5.711631 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/order/OrdersPagedListAdapter.kt | 1 | 1712 | package org.fossasia.openevent.general.order
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import org.fossasia.openevent.general.databinding.ItemCardOrderBinding
import org.fossasia.openevent.general.event.Event
class OrdersPagedListAdapter : PagedListAdapter<Pair<Event, Order>, OrdersViewHolder>(OrdersDiffCallback()) {
private var showExpired = false
private var clickListener: OrderClickListener? = null
fun setListener(listener: OrderClickListener?) {
clickListener = listener
}
fun setShowExpired(expired: Boolean) {
showExpired = expired
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrdersViewHolder {
val binding = ItemCardOrderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return OrdersViewHolder(binding)
}
override fun onBindViewHolder(holder: OrdersViewHolder, position: Int) {
val item = getItem(position)
if (item != null) {
holder.bind(item, showExpired, clickListener)
}
}
fun clear() {
this.submitList(null)
}
interface OrderClickListener {
fun onClick(eventID: Long, orderIdentifier: String, orderId: Long)
}
}
class OrdersDiffCallback : DiffUtil.ItemCallback<Pair<Event, Order>>() {
override fun areItemsTheSame(oldItem: Pair<Event, Order>, newItem: Pair<Event, Order>): Boolean {
return oldItem.second.id == newItem.second.id
}
override fun areContentsTheSame(oldItem: Pair<Event, Order>, newItem: Pair<Event, Order>): Boolean {
return oldItem == newItem
}
}
| apache-2.0 | 98dd03ac43d3ed558c609125ef88a404 | 31.923077 | 109 | 0.719626 | 4.602151 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/data/models/Streamer.kt | 1 | 783 | package app.youkai.data.models
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.github.jasminb.jsonapi.annotations.Type
@Type("streamers") @JsonIgnoreProperties(ignoreUnknown = true)
class Streamer : BaseJsonModel(JsonType("streamers")) {
companion object FieldNames {
val SITE_NAME = "siteName"
val LOGO = "logo"
val STREAMING_LINKS = "streamingLinks"
}
var siteName: String? = null
var logo: String? = null
/**
* This is left here for future generations, as streamers do not have streamingLinks implemented yet as relationships.
*
@Relationship("streamingLinks")
var streamingLinks: List<StreamingLink>? = null
@RelationshipLinks("streamingLinks")
var streamingLinksLinks: Links? = null
*/
} | gpl-3.0 | cd8a3ec0a7e54e0a018db948cc11d035 | 26.034483 | 118 | 0.721584 | 4.232432 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/WCOrderShipmentTrackingModel.kt | 2 | 900 | package org.wordpress.android.fluxc.model
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.Table
import org.wordpress.android.fluxc.persistence.WellSqlConfig
@Table(addOn = WellSqlConfig.ADDON_WOOCOMMERCE)
data class WCOrderShipmentTrackingModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable {
@Column var localSiteId = 0
@Column(name = "LOCAL_ORDER_ID") var orderId = 0L // The local db unique identifier for the parent order object
@Column var remoteTrackingId = ""
@Column var trackingNumber = ""
@Column var trackingProvider = ""
@Column var trackingLink = ""
@Column var dateShipped = ""
override fun setId(id: Int) {
this.id = id
}
override fun getId() = this.id
}
| gpl-2.0 | 885dfd83c8dfc61d5d6fe1105684fde9 | 36.5 | 115 | 0.744444 | 4.205607 | false | true | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/structure/latex/LatexSectionPresentation.kt | 1 | 874 | package nl.hannahsten.texifyidea.structure.latex
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.structure.EditableHintPresentation
/**
* @author Hannah Schellekens
*/
class LatexSectionPresentation(sectionCommand: LatexCommands) : EditableHintPresentation {
private val sectionName: String
private var hint = ""
init {
if (sectionCommand.commandToken.text != "\\section") {
throw IllegalArgumentException("command is no \\section-command")
}
this.sectionName = sectionCommand.requiredParameters[0]
}
override fun getPresentableText() = sectionName
override fun getLocationString() = hint
override fun getIcon(b: Boolean) = TexifyIcons.DOT_SECTION
override fun setHint(hint: String) {
this.hint = hint
}
} | mit | c87dccf491b399c2fdb1c16fa9ca26ff | 26.34375 | 90 | 0.726545 | 4.937853 | false | false | false | false |
zhufucdev/PCtoPE | app/src/main/java/com/zhufucdev/pctope/utils/CompressImage.kt | 1 | 1096 | package com.zhufucdev.pctope.utils
import android.graphics.Bitmap
import android.graphics.Matrix
/**
* Created by zhufu on 17-8-11.
*/
object CompressImage {
fun getBitmap(bitmap: Bitmap, Height: Int, Width: Int): Bitmap? {
val matrix = Matrix()
val oldHeight = bitmap.height
val oldWidth = bitmap.width
if (oldHeight <= 0 || oldWidth <= 0)
return null
val scaleHeight = Height.toFloat() / oldHeight
val scaleWidth = Width.toFloat() / oldWidth
matrix.postScale(scaleWidth, scaleHeight)
return Bitmap.createBitmap(bitmap, 0, 0, oldWidth, oldHeight, matrix, false)
}
fun getBitmap(bitmap: Bitmap, scale: Float): Bitmap {
val matrix = Matrix()
val height = bitmap.height
val width = bitmap.width
matrix.postScale(scale, scale)
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false)
}
fun testBitmap(testWidth: Int, testHeight: Int, bitmap: Bitmap): Boolean {
return bitmap.height > testHeight || bitmap.width > testWidth
}
}
| gpl-3.0 | a3e5416baca14765ec40ce746eab3f12 | 28.621622 | 84 | 0.645073 | 4.215385 | false | true | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/index/IndexKeys.kt | 1 | 1357 | package nl.hannahsten.texifyidea.index
import com.intellij.psi.stubs.StubIndexKey
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexEnvironment
import nl.hannahsten.texifyidea.psi.LatexMagicComment
/**
* @author Hannah Schellekens
*/
object IndexKeys {
val COMMANDS_KEY =
StubIndexKey.createIndexKey<String, LatexCommands>("nl.hannahsten.texifyidea.commands")
val INCLUDES_KEY =
StubIndexKey.createIndexKey<String, LatexCommands>("nl.hannahsten.texifyidea.includes")
val DEFINITIONS_KEY =
StubIndexKey.createIndexKey<String, LatexCommands>("nl.hannahsten.texifyidea.definitions")
val ENVIRONMENTS_KEY =
StubIndexKey.createIndexKey<String, LatexEnvironment>("nl.hannahsten.texifyidea.environments")
val MAGIC_COMMENTS_KEY =
StubIndexKey.createIndexKey<String, LatexMagicComment>("nl.hannahsten.texifyidea.magiccomment")
val LABELED_ENVIRONMENTS_KEY =
StubIndexKey.createIndexKey<String, LatexEnvironment>("nl.hannahsten.texifyidea.parameterlabeledenvironments")
val LABELED_COMMANDS_KEY =
StubIndexKey.createIndexKey<String, LatexCommands>("nl.hannahsten.texifyidea.parameterlabeledcommands")
val GLOSSARY_ENTRIES_KEY =
StubIndexKey.createIndexKey<String, LatexCommands>("nl.hannahsten.texifyidea.glossaryentries")
} | mit | ea1a3feecfd0136ec9dab803d0ab55cb | 45.827586 | 118 | 0.781872 | 4.829181 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/ui/views/LikeButton.kt | 1 | 1738 | package com.duopoints.android.ui.views
import android.content.Context
import android.content.res.ColorStateList
import android.support.v4.content.ContextCompat
import android.support.v4.widget.ImageViewCompat
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
import com.duopoints.android.R
import com.duopoints.android.utils.UiUtils
import com.github.florent37.viewanimator.ViewAnimator
class LikeButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
AppCompatImageView(context, attrs, defStyleAttr) {
var like = false
fun setLike(like: Boolean, animate: Boolean) {
if (like) {
this.like = true
this.setImageResource(R.drawable.ic_thumb_up_black)
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, UiUtils.getResId(context, R.attr.colorLikeIconTint))))
if (animate) {
ViewAnimator.animate(this)
.scaleY(1f, 1.3f, 1f)
.scaleX(1f, 1.3f, 1f)
.duration(500)
.start()
}
} else {
this.like = false
this.setImageResource(R.drawable.ic_thumb_up_black)
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, UiUtils.getResId(context, R.attr.colorNotLikeIconTint))))
if (animate) {
ViewAnimator.animate(this)
.scaleY(1f, 1.3f, 1f)
.scaleX(1f, 1.3f, 1f)
.duration(500)
.start()
}
}
}
}
| gpl-3.0 | 4cdcb02ba7074c3129c70cf196d8ab84 | 36.782609 | 163 | 0.617952 | 4.312655 | false | false | false | false |
gumil/basamto | app/src/main/kotlin/io/github/gumil/basamto/extensions/UiExtensions.kt | 1 | 2654 | /*
* The MIT License (MIT)
*
* Copyright 2017 Miguel Panelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.gumil.basamto.extensions
import android.os.Build
import android.support.annotation.LayoutRes
import android.support.annotation.StyleRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import io.github.gumil.basamto.widget.html.fromHtml
fun ViewGroup.inflateLayout(@LayoutRes layout: Int, addToRoot: Boolean = false) =
LayoutInflater.from(context).inflate(layout, this, addToRoot)
@Suppress("deprecation")
internal fun TextView.textAppearance(@StyleRes style: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setTextAppearance(style)
} else {
setTextAppearance(context, style)
}
}
internal fun TextView.fromHtml(html: String) {
text = html.fromHtml().trim()
}
internal fun ImageView.load(url: String?) {
post {
url?.let {
Picasso.with(context)
.load(it)
.apply {
if (width > 0 && height > 0) {
resize(width, height)
.centerCrop()
}
}
.into(this)
}
}
}
internal fun View.setVisible(visible: Boolean) {
visibility = if (visible) {
View.VISIBLE
} else {
View.GONE
}
}
internal fun View.setPadding(dp: Int) {
setPadding(dp, dp, dp, dp)
} | mit | c969bac68430c568ea5b5c6e9329bb59 | 31.777778 | 81 | 0.675584 | 4.301459 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/brvah/diff/BrvahAsyncDiffer.kt | 1 | 5855 | package com.didichuxing.doraemonkit.widget.brvah.diff
import android.os.Handler
import android.os.Looper
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DiffUtil.DiffResult
import androidx.recyclerview.widget.ListUpdateCallback
import com.didichuxing.doraemonkit.widget.brvah.BaseQuickAdapter
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Executor
class BrvahAsyncDiffer<T>(private val adapter: BaseQuickAdapter<T, *>,
private val config: BrvahAsyncDifferConfig<T>) : DifferImp<T> {
private val mUpdateCallback: ListUpdateCallback = BrvahListUpdateCallback(adapter)
private var mMainThreadExecutor: Executor
private class MainThreadExecutor internal constructor() : Executor {
val mHandler = Handler(Looper.getMainLooper())
override fun execute(command: Runnable) {
mHandler.post(command)
}
}
private val sMainThreadExecutor: Executor = MainThreadExecutor()
init {
mMainThreadExecutor = config.mainThreadExecutor ?: sMainThreadExecutor
}
private val mListeners: MutableList<ListChangeListener<T>> = CopyOnWriteArrayList()
private var mMaxScheduledGeneration = 0
@JvmOverloads
fun submitList(newList: MutableList<T>?, commitCallback: Runnable? = null) {
// incrementing generation means any currently-running diffs are discarded when they finish
val runGeneration: Int = ++mMaxScheduledGeneration
if (newList === adapter.data) {
// nothing to do (Note - still had to inc generation, since may have ongoing work)
commitCallback?.run()
return
}
val oldList: List<T> = adapter.data
// fast simple remove all
if (newList == null) {
val countRemoved: Int = adapter.data.size
adapter.data = arrayListOf()
// notify last, after list is updated
mUpdateCallback.onRemoved(0, countRemoved)
onCurrentListChanged(oldList, commitCallback)
return
}
// fast simple first insert
if (adapter.data.isEmpty()) {
adapter.data = newList
// notify last, after list is updated
mUpdateCallback.onInserted(0, newList.size)
onCurrentListChanged(oldList, commitCallback)
return
}
config.backgroundThreadExecutor.execute {
val result = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem: T? = oldList[oldItemPosition]
val newItem: T? = newList[newItemPosition]
return if (oldItem != null && newItem != null) {
config.diffCallback.areItemsTheSame(oldItem, newItem)
} else oldItem == null && newItem == null
// If both items are null we consider them the same.
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem: T? = oldList[oldItemPosition]
val newItem: T? = newList[newItemPosition]
if (oldItem != null && newItem != null) {
return config.diffCallback.areContentsTheSame(oldItem, newItem)
}
if (oldItem == null && newItem == null) {
return true
}
throw AssertionError()
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldItem: T? = oldList[oldItemPosition]
val newItem: T? = newList[newItemPosition]
if (oldItem != null && newItem != null) {
return config.diffCallback.getChangePayload(oldItem, newItem)
}
throw AssertionError()
}
})
mMainThreadExecutor.execute {
if (mMaxScheduledGeneration == runGeneration) {
latchList(newList, result, commitCallback)
}
}
}
}
private fun latchList(
newList: MutableList<T>,
diffResult: DiffResult,
commitCallback: Runnable?) {
val previousList: List<T> = adapter.data
adapter.data = newList
diffResult.dispatchUpdatesTo(mUpdateCallback)
onCurrentListChanged(previousList, commitCallback)
}
private fun onCurrentListChanged(previousList: List<T>,
commitCallback: Runnable?) {
for (listener in mListeners) {
listener.onCurrentListChanged(previousList, adapter.data)
}
commitCallback?.run()
}
/**
* Add a ListListener to receive updates when the current List changes.
*
* @param listener Listener to receive updates.
*
* @see .getCurrentList
* @see .removeListListener
*/
override fun addListListener(listener: ListChangeListener<T>) {
mListeners.add(listener)
}
/**
* Remove a previously registered ListListener.
*
* @param listener Previously registered listener.
* @see .getCurrentList
* @see .addListListener
*/
fun removeListListener(listener: ListChangeListener<T>) {
mListeners.remove(listener)
}
fun clearAllListListener() {
mListeners.clear()
}
} | apache-2.0 | 53d60cfd0d7890b745cf4953e22b225e | 36.780645 | 102 | 0.598292 | 5.431354 | false | false | false | false |
Guardsquare/proguard | gradle-plugin/src/test/kotlin/testutils/AndroidProjectBuilder.kt | 1 | 12169 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2021 Guardsquare NV
*/
package testutils
import java.io.File
import java.nio.file.Files.createTempDirectory
import org.intellij.lang.annotations.Language
interface ProjectFile {
val path: String
fun create(moduleDir: File)
}
class SourceFile(override val path: String, val source: String = "") : ProjectFile {
override fun create(moduleDir: File) {
val file = File(moduleDir, path)
file.parentFile.mkdirs()
file.writeText(source)
}
}
class ResourceFile(override val path: String, private val resourceName: String) : ProjectFile {
override fun create(moduleDir: File) {
val file = File(moduleDir, path)
file.parentFile.mkdirs()
javaClass.getResourceAsStream(resourceName).use { input ->
file.outputStream().use { output -> input.copyTo(output) }
}
}
}
data class Module(val name: String, val files: List<ProjectFile>) {
val projectPath get() = ":$name"
}
fun androidModule(
name: String,
buildDotGradle: String,
androidManifest: String,
javaSources: Map<String, String>,
additionalFiles: List<ProjectFile>
) = Module(name, additionalFiles + listOf(
SourceFile("build.gradle", buildDotGradle),
SourceFile("src/main/AndroidManifest.xml", androidManifest)) +
javaSources.map { (k, v) ->
SourceFile("src/main/java/$k", v)
})
fun libraryModule(
name: String,
@Language("Groovy") buildDotGradle: String = defaultBuildDotGradle(ProjectType.LIBRARY),
@Language("xml") androidManifest: String = defaultAndroidLibraryManifest,
javaSources: Map<String, String> = defaultLibrarySources,
additionalFiles: List<ProjectFile> = emptyList()
) = androidModule(name, buildDotGradle, androidManifest, javaSources, additionalFiles)
fun applicationModule(
name: String,
@Language("Groovy") buildDotGradle: String = defaultBuildDotGradle(ProjectType.APPLICATION),
@Language("xml") androidManifest: String = defaultAndroidApplicationManifest,
javaSources: Map<String, String> = defaultApplicationSources,
additionalFiles: List<ProjectFile> = emptyList()
) = androidModule(name, buildDotGradle, androidManifest, javaSources, additionalFiles)
fun baseFeatureModule(
name: String,
@Language("Groovy") buildDotGradle: String = defaultBaseFeatureBuildDotGradle,
@Language("xml") androidManifest: String = defaultAndroidApplicationManifest,
javaSources: Map<String, String> = defaultApplicationSources,
additionalFiles: List<ProjectFile> = defaultBaseFeatureAdditionalFiles
) = androidModule(name, buildDotGradle, androidManifest, javaSources, additionalFiles)
fun dynamicFeatureModule(
name: String,
@Language("Groovy") buildDotGradle: String = defaultDynamicFeatureBuildDotGradle,
@Language("xml") androidManifest: String = defaultDynamicFeatureManifest,
javaSources: Map<String, String> = defaultDynamicFeatureSources,
additionalFiles: List<ProjectFile> = emptyList()
) = androidModule(name, buildDotGradle, androidManifest, javaSources, additionalFiles)
fun jarModule(
name: String,
@Language("Groovy") buildDotGradle: String = defaultJarBuildDotGradle,
javaSources: Map<String, String> = defaultJarSources,
additionalFiles: List<ProjectFile> = emptyList()
) = Module(name, additionalFiles + listOf(
SourceFile("build.gradle", buildDotGradle)) +
javaSources.map { (k, v) -> SourceFile("src/main/java/$k", v) })
class AndroidProject(
@Language("Groovy") val buildDotGradle: String = defaultRootBuildDotGradle,
@Language("Groovy") private val overrideSettingsDotGradle: String? = null,
private val gradleDotProperties: String? = null
) : AutoCloseable {
val rootDir: File = createTempDirectory("proguard-gradle").toFile()
private val modules = mutableListOf<Module>()
private val settingsDotGradle: String get() =
overrideSettingsDotGradle ?: defaultSettingsDotGradle(modules)
fun addModule(module: Module) {
modules.add(module)
}
fun module(name: String): Module? = modules.find { it.name == name }
fun moduleBuildDir(name: String): File? = with(module(name)) {
if (this != null) File(rootDir, "${this.name}/build") else null
}
fun create(): AndroidProject {
rootDir.mkdirs()
File(rootDir, "build.gradle").writeText(buildDotGradle)
File(rootDir, "settings.gradle").writeText(settingsDotGradle)
if (gradleDotProperties != null) {
File(rootDir, "gradle.properties").writeText(gradleDotProperties)
}
for (module in modules) {
val moduleDir = File(rootDir, module.name)
moduleDir.mkdirs()
for (file in module.files) {
file.create(moduleDir)
}
}
return this
}
override fun close() {
if (!rootDir.deleteRecursively()) throw Exception("Could not delete root dir '$rootDir'")
}
}
fun defaultSettingsDotGradle(modules: List<Module>) =
modules.joinToString(prefix = "include ") { "'${it.projectPath}'" }
private val defaultRootBuildDotGradle = """
buildscript {
repositories {
mavenCentral() // For anything else.
google() // For the Android plugin.
flatDir {
dirs "${System.getProperty("local.repo")}"
}
}
dependencies {
classpath "com.android.tools.build:gradle:${System.getProperty("agp.version")}"
classpath ":proguard-gradle:${System.getProperty("proguard.version")}"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
""".trimIndent()
enum class ProjectType(val plugin: String) {
APPLICATION("com.android.application"),
DYNAMIC_FEATURE("com.android.dynamic-feature"),
LIBRARY("com.android.library")
}
private fun defaultBuildDotGradle(type: ProjectType) = """
plugins {
id '${type.plugin}'
id 'com.guardsquare.proguard'
}
android {
compileSdkVersion 29
defaultConfig {
targetSdkVersion 29
minSdkVersion 14
versionCode 1
}
buildTypes {
release {}
debug {}
}
}
""".trimIndent()
private val defaultBaseFeatureBuildDotGradle = """
plugins {
id 'com.android.application'
id 'com.guardsquare.proguard'
}
android {
compileSdkVersion 29
defaultConfig {
targetSdkVersion 29
minSdkVersion 14
versionCode 1
}
buildTypes {
release {}
debug {}
}
dynamicFeatures = [':feature']
}
""".trimIndent()
private val defaultDynamicFeatureBuildDotGradle = """
plugins {
id 'com.android.dynamic-feature'
id 'com.guardsquare.proguard'
}
android {
compileSdkVersion 29
defaultConfig {
targetSdkVersion 29
minSdkVersion 14
}
buildTypes {
release {}
debug {}
}
}
dependencies {
implementation project(':app')
}
""".trimIndent()
private val defaultJarBuildDotGradle = """
plugins {
id 'java-library'
}
""".trimIndent()
private val defaultAndroidApplicationManifest = """
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<application android:label="Sample">
<activity android:name="MainActivity"
android:label="Sample">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
""".trimIndent()
private val defaultDynamicFeatureManifest = """
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.feature">
<dist:module dist:onDemand="true"
dist:title="@string/feature_name">
<dist:fusing dist:include="true" />
</dist:module>
<application>
<activity android:name="com.example.feature.FeatureActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
</application>
</manifest>
""".trimIndent()
private val defaultAndroidLibraryManifest = """
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lib">
</manifest>
""".trimIndent()
private val defaultApplicationSources = mutableMapOf(
"com/example/app/MainActivity.java" to """
package com.example.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.*;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
view.setText("Hello World!");
view.setGravity(Gravity.CENTER);
setContentView(view);
}
}
""".trimIndent())
private val defaultDynamicFeatureSources = mutableMapOf(
"com/example/feature/FeatureActivity.java" to """
package com.example.feature;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.*;
public class FeatureActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
view.setText("Hello World!");
view.setGravity(Gravity.CENTER);
setContentView(view);
}
}
""".trimIndent())
private val defaultLibrarySources = mutableMapOf(
"com/example/lib/LibraryClass.java" to """
package com.example.lib;
public class LibraryClass
{
public String getMessage()
{
return "Hello World!";
}
}
""".trimIndent()
)
private val defaultJarSources = mutableMapOf(
"com/example/jar/JarClass.java" to """
package com.example.jar;
public class JarClass
{
public String getMessage()
{
return "Hello World!";
}
}
""".trimIndent()
)
val defaultBaseFeatureAdditionalFiles = listOf(
SourceFile("src/main/res/values/module_names.xml", """
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="feature_name">dynamic-feature</string>
</resources>
""".trimIndent())
)
val defaultGoogleServicesResourceFiles = listOf(
SourceFile("src/main/res/values/strings.xml", """
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- This API key matches the com.example package -->
<string name="google_app_id">1:260040693598:android:2009aac2b4e342544221cf</string>
</resources>
""".trimIndent())
)
| gpl-2.0 | 4ef77b47a50b4da0b598e9f7fc2300d0 | 31.537433 | 99 | 0.606459 | 4.711189 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/tips/TipManager.kt | 1 | 12195 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.tips
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import mozilla.components.browser.session.Session
import org.mozilla.focus.R.string.app_name
import org.mozilla.focus.R.string.tip_add_to_homescreen
import org.mozilla.focus.R.string.tip_autocomplete_url
import org.mozilla.focus.R.string.tip_disable_tips2
import org.mozilla.focus.R.string.tip_disable_tracking_protection
import org.mozilla.focus.R.string.tip_explain_allowlist
import org.mozilla.focus.R.string.tip_open_in_new_tab
import org.mozilla.focus.R.string.tip_request_desktop
import org.mozilla.focus.R.string.tip_set_default_browser
import org.mozilla.focus.R.string.tip_take_survey
import org.mozilla.focus.exceptions.ExceptionDomains
import org.mozilla.focus.ext.components
import org.mozilla.focus.locale.LocaleAwareAppCompatActivity
import org.mozilla.focus.locale.LocaleManager
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.Browsers
import org.mozilla.focus.utils.Settings
import org.mozilla.focus.utils.SupportUtils
import org.mozilla.focus.utils.homeScreenTipsExperimentDescriptor
import org.mozilla.focus.utils.isInExperiment
import java.util.Locale
import java.util.Random
class Tip(val id: Int, val text: String, val shouldDisplay: () -> Boolean, val deepLink: (() -> Unit)? = null) {
companion object {
private const val FORCE_SHOW_DISABLE_TIPS_LAUNCH_COUNT = 2
private const val FORCE_SHOW_DISABLE_TIPS_INTERVAL = 30
fun createAllowlistTip(context: Context): Tip {
val id = tip_explain_allowlist
val name = context.resources.getString(id)
val url = SupportUtils.getSumoURLForTopic(context, SupportUtils.SumoTopic.ALLOWLIST)
val deepLink = {
val session = Session(url, source = Session.Source.MENU)
context.components.sessionManager.add(session, selected = true)
TelemetryWrapper.pressTipEvent(id)
}
val shouldDisplayAllowListTip = {
ExceptionDomains.load(context).isEmpty()
}
return Tip(id, name, shouldDisplayAllowListTip, deepLink)
}
fun createTrackingProtectionTip(context: Context): Tip {
val id = tip_disable_tracking_protection
val name = context.resources.getString(id)
val shouldDisplayTrackingProtection = {
Settings.getInstance(context).shouldBlockOtherTrackers() ||
Settings.getInstance(context).shouldBlockAdTrackers() ||
Settings.getInstance(context).shouldBlockAnalyticTrackers()
}
return Tip(id, name, shouldDisplayTrackingProtection)
}
fun createHomescreenTip(context: Context): Tip {
val id = tip_add_to_homescreen
val name = context.resources.getString(id)
val homescreenURL =
"https://support.mozilla.org/en-US/kb/add-web-page-shortcuts-your-home-screen"
val deepLinkAddToHomescreen = {
val session = Session(homescreenURL, source = Session.Source.MENU)
context.components.sessionManager.add(session, selected = true)
TelemetryWrapper.pressTipEvent(id)
}
val shouldDisplayAddToHomescreen = { !Settings.getInstance(context).hasAddedToHomeScreen }
return Tip(id, name, shouldDisplayAddToHomescreen, deepLinkAddToHomescreen)
}
fun createDefaultBrowserTip(context: Context): Tip {
val appName = context.resources.getString(app_name)
val id = tip_set_default_browser
val name = context.resources.getString(id, appName)
val browsers = Browsers(context, Browsers.TRADITIONAL_BROWSER_URL)
val shouldDisplayDefaultBrowser = {
!Browsers(context, Browsers.TRADITIONAL_BROWSER_URL).isDefaultBrowser(context)
}
val deepLinkDefaultBrowser = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
SupportUtils.openDefaultAppsSettings(context)
} else if (!browsers.hasDefaultBrowser(context)) {
// Open in method:
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(SupportUtils.OPEN_WITH_DEFAULT_BROWSER_URL))
context.startActivity(intent)
} else {
SupportUtils.openDefaultBrowserSumoPage(context)
}
TelemetryWrapper.pressTipEvent(id)
}
return Tip(id, name, shouldDisplayDefaultBrowser, deepLinkDefaultBrowser)
}
fun createAutocompleteURLTip(context: Context): Tip {
val id = tip_autocomplete_url
val name = context.resources.getString(id)
val autocompleteURL =
"https://support.mozilla.org/en-US/kb/autocomplete-settings-firefox-focus-address-bar"
val shouldDisplayAutocompleteUrl = {
!Settings.getInstance(context).shouldAutocompleteFromCustomDomainList()
}
val deepLinkAutocompleteUrl = {
val session = Session(autocompleteURL, source = Session.Source.MENU)
context.components.sessionManager.add(session, selected = true)
TelemetryWrapper.pressTipEvent(id)
}
return Tip(id, name, shouldDisplayAutocompleteUrl, deepLinkAutocompleteUrl)
}
fun createOpenInNewTabTip(context: Context): Tip {
val id = tip_open_in_new_tab
val name = context.resources.getString(id)
val newTabURL =
"https://support.mozilla.org/en-US/kb/open-new-tab-firefox-focus-android"
val shouldDisplayOpenInNewTab = {
!Settings.getInstance(context).hasOpenedInNewTab()
}
val deepLinkOpenInNewTab = {
val session = Session(newTabURL, source = Session.Source.MENU)
context.components.sessionManager.add(session, selected = true)
TelemetryWrapper.pressTipEvent(id)
}
return Tip(id, name, shouldDisplayOpenInNewTab, deepLinkOpenInNewTab)
}
fun createRequestDesktopTip(context: Context): Tip {
val id = tip_request_desktop
val name = context.resources.getString(id)
val requestDesktopURL =
"https://support.mozilla.org/en-US/kb/switch-desktop-view-firefox-focus-android"
val shouldDisplayRequestDesktop = {
!Settings.getInstance(context).hasRequestedDesktop()
}
val deepLinkRequestDesktop = {
val session = Session(requestDesktopURL, source = Session.Source.MENU)
context.components.sessionManager.add(session, selected = true)
TelemetryWrapper.pressTipEvent(id)
}
return Tip(id, name, shouldDisplayRequestDesktop, deepLinkRequestDesktop)
}
fun createDisableTipsTip(context: Context): Tip {
val id = tip_disable_tips2
val name = context.resources.getString(id)
val shouldDisplayDisableTips = {
// Count number of app launches
val launchCount = Settings.getInstance(context).getAppLaunchCount()
var shouldDisplay = false
if (launchCount != 0 && (launchCount == FORCE_SHOW_DISABLE_TIPS_LAUNCH_COUNT ||
launchCount % FORCE_SHOW_DISABLE_TIPS_INTERVAL == 0)) {
shouldDisplay = true
}
shouldDisplay
}
val deepLinkDisableTips = {
val activity = context as Activity
(activity as LocaleAwareAppCompatActivity).openMozillaSettings()
TelemetryWrapper.pressTipEvent(id)
}
return Tip(id, name, shouldDisplayDisableTips, deepLinkDisableTips)
}
}
}
// Yes, this a large class with a lot of functions. But it's very simple and still easy to read.
@Suppress("TooManyFunctions")
object TipManager {
private const val MAX_TIPS_TO_DISPLAY = 3
private val listOfTips = mutableListOf<Tip>()
private val random = Random()
private var listInitialized = false
private var tipsShown = 0
private var locale: Locale? = null
private fun populateListOfTips(context: Context) {
addAllowlistTip(context)
addTrackingProtectionTip(context)
addHomescreenTip(context)
addDefaultBrowserTip(context)
addAutocompleteUrlTip(context)
addOpenInNewTabTip(context)
addRequestDesktopTip(context)
addDisableTipsTip(context)
}
// Will not return a tip if tips are disabled or if MAX TIPS have already been shown.
@Suppress("ReturnCount", "ComplexMethod") // Using early returns
fun getNextTipIfAvailable(context: Context): Tip? {
if (!context.isInExperiment(homeScreenTipsExperimentDescriptor)) return null
if (!Settings.getInstance(context).shouldDisplayHomescreenTips()) return null
val currentLocale = LocaleManager.getInstance().getCurrentLocale(context)
if (!listInitialized || currentLocale != locale) {
locale = currentLocale
populateListOfTips(context)
listInitialized = true
}
// Only show three tips before going back to the "Focus" branding
if (tipsShown == MAX_TIPS_TO_DISPLAY || listOfTips.count() <= 0) {
return null
}
// Show the survey tip first
for (tip in listOfTips) {
if (tip.id == tip_take_survey && tip.shouldDisplay()) {
listOfTips.remove(tip)
return tip
}
}
// Always show the disable tip if it's ready to be displayed
for (tip in listOfTips) {
if (tip.id == tip_disable_tips2 && tip.shouldDisplay()) {
listOfTips.remove(tip)
return tip
}
}
var tip = listOfTips[getRandomTipIndex()]
// Find a random tip that the user doesn't already know about
while (!tip.shouldDisplay()) {
listOfTips.remove(tip)
if (listOfTips.count() == 0) { return null }
tip = listOfTips[getRandomTipIndex()]
}
listOfTips.remove(tip)
tipsShown += 1
TelemetryWrapper.displayTipEvent(tip.id)
return tip
}
private fun getRandomTipIndex(): Int {
return if (listOfTips.count() == 1) 0 else random.nextInt(listOfTips.count() - 1)
}
private fun addAllowlistTip(context: Context) {
val tip = Tip.createAllowlistTip(context)
listOfTips.add(tip)
}
private fun addTrackingProtectionTip(context: Context) {
val tip = Tip.createTrackingProtectionTip(context)
listOfTips.add(tip)
}
private fun addHomescreenTip(context: Context) {
val tip = Tip.createHomescreenTip(context)
listOfTips.add(tip)
}
private fun addDefaultBrowserTip(context: Context) {
val tip = Tip.createDefaultBrowserTip(context)
listOfTips.add(tip)
}
private fun addAutocompleteUrlTip(context: Context) {
val tip = Tip.createAutocompleteURLTip(context)
listOfTips.add(tip)
}
private fun addOpenInNewTabTip(context: Context) {
val tip = Tip.createOpenInNewTabTip(context)
listOfTips.add(tip)
}
private fun addRequestDesktopTip(context: Context) {
val tip = Tip.createRequestDesktopTip(context)
listOfTips.add(tip)
}
private fun addDisableTipsTip(context: Context) {
val tip = Tip.createDisableTipsTip(context)
listOfTips.add(tip)
}
}
| mpl-2.0 | abb23a98f10f42eac663b19f49254c85 | 37.83758 | 114 | 0.639196 | 4.645714 | false | false | false | false |
ylegall/BrainSaver | src/main/java/org/ygl/LibraryFunctions.kt | 1 | 1455 | package org.ygl
import org.antlr.v4.runtime.misc.ParseCancellationException
typealias SymbolList = List<Symbol?>
typealias Procedure = (SymbolList) -> Symbol?
class LibraryFunctions(val cg: CodeGen, val tree: TreeWalker)
{
val procedures: HashMap<String, Procedure> = hashMapOf(
"println" to this::println,
"readStr" to this::readStr
)
private fun println(args: SymbolList): Symbol? {
if (args.isEmpty()) {
cg.io.print("\n")
} else {
args.filterNotNull().forEach {
if (tree.isConstant(it)) {
cg.io.print(it.value)
} else {
cg.io.print(it)
}
cg.io.print("\n")
}
}
return null
}
private fun readStr(args: SymbolList): Symbol? {
if (args.size != 1 || !tree.isConstant(args[0]!!)) {
throw ParseCancellationException("function readStr accepts 1 constant integer argument")
}
val arg = args[0]!!
val len = arg.value as Int
val str = cg.currentScope().getTempSymbol(type = Type.STRING, size = len)
for (i in 0 until len) {
cg.io.readChar(str.offset(i))
}
return str
}
fun invoke(name: String, args: SymbolList): Symbol? {
val fn = procedures[name] ?: throw Exception("undefined function $name")
return fn.invoke(args)
}
} | gpl-3.0 | 57c69babb2d37d280d06f8cdf267c9c8 | 28.12 | 100 | 0.553265 | 4.098592 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/Transfer.kt | 3 | 3321 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Parcel
import android.os.Parcelable
import androidx.core.os.ParcelCompat.readBoolean
import androidx.core.os.ParcelCompat.writeBoolean
import java.io.Serializable
enum class TransferStatus(val status: Int) {
ERR_GIVEUP_DOWNLOAD(-114),
ERR_GIVEUP_UPLOAD(-115)
}
data class Transfer(
var name: String = "",
var projectUrl: String = "",
var noOfBytes: Long = 0,
var status: Int = 0,
var nextRequestTime: Long = 0,
var timeSoFar: Long = 0,
var bytesTransferred: Long = 0,
var transferSpeed: Float = 0f,
var projectBackoff: Long = 0,
var generatedLocally: Boolean = false,
var isTransferActive: Boolean = false,
var isUpload: Boolean = false
) : Serializable, Parcelable {
private constructor (parcel: Parcel) :
this(parcel.readString() ?: "", parcel.readString() ?: "",
parcel.readLong(), parcel.readInt(), parcel.readLong(), parcel.readLong(),
parcel.readLong(), parcel.readFloat(), parcel.readLong(), readBoolean(parcel),
readBoolean(parcel), readBoolean(parcel))
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(name)
dest.writeString(projectUrl)
dest.writeLong(noOfBytes)
dest.writeInt(status)
dest.writeLong(nextRequestTime)
dest.writeLong(timeSoFar)
dest.writeLong(bytesTransferred)
dest.writeFloat(transferSpeed)
dest.writeLong(projectBackoff)
writeBoolean(dest, generatedLocally)
writeBoolean(dest, isTransferActive)
writeBoolean(dest, isUpload)
}
object Fields {
const val GENERATED_LOCALLY = "generated_locally"
const val NBYTES = "nbytes"
const val IS_UPLOAD = "is_upload"
const val STATUS = "status"
const val NEXT_REQUEST_TIME = "next_request_time"
const val TIME_SO_FAR = "time_so_far"
const val BYTES_XFERRED = "bytes_xferred"
const val XFER_SPEED = "xfer_speed"
const val PROJECT_BACKOFF = "project_backoff"
}
companion object {
private const val serialVersionUID = 1L
@JvmField
val CREATOR: Parcelable.Creator<Transfer> = object : Parcelable.Creator<Transfer> {
override fun createFromParcel(parcel: Parcel) = Transfer(parcel)
override fun newArray(size: Int) = arrayOfNulls<Transfer>(size)
}
}
}
| lgpl-3.0 | 191a99a2f1b144e866332d9e115bab57 | 35.494505 | 98 | 0.663354 | 4.324219 | false | false | false | false |
ptrgags/holo-pyramid | app/src/main/java/io/github/ptrgags/holopyramid/HoloPyramidActivity.kt | 1 | 2479 | package io.github.ptrgags.holopyramid
import android.os.Bundle
import android.support.v7.app.ActionBar
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.ViewGroup
import org.rajawali3d.view.ISurface
import org.rajawali3d.view.SurfaceView
class HoloPyramidActivity : AppCompatActivity() {
/** An object to handle transforming the model */
val transformer = ModelTransformer()
override fun onCreate(savedInstanceState: Bundle?) {
// Set up the activity
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_holopyramid)
// Create a view for Rajawali rendering
val surface = SurfaceView(this)
surface.setFrameRate(60.0)
surface.renderMode = ISurface.RENDERMODE_WHEN_DIRTY
addContentView(
surface,
ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT))
// Set up the custom renderer
val modelId = intent.extras.getInt("model_id")
val renderer = HoloPyramidRenderer(this, modelId, transformer)
surface.setSurfaceRenderer(renderer)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
return when(keyCode) {
KeyEvent.KEYCODE_BUTTON_A -> {
transformer.toggleMode()
true
}
KeyEvent.KEYCODE_BUTTON_START -> {
transformer.resetManualRotation()
true
}
else -> super.onKeyUp(keyCode, event)
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> {
transformer.adjustYaw(-1.0)
true
}
KeyEvent.KEYCODE_DPAD_RIGHT -> {
transformer.adjustYaw(1.0)
true
}
KeyEvent.KEYCODE_DPAD_UP -> {
transformer.adjustPitch(1.0)
true
}
KeyEvent.KEYCODE_DPAD_DOWN -> {
transformer.adjustPitch(-1.0)
true
}
KeyEvent.KEYCODE_BUTTON_L1 -> {
transformer.adjustHeight(1.0)
true
}
KeyEvent.KEYCODE_BUTTON_R1 -> {
transformer.adjustHeight(-1.0)
true
}
else -> super.onKeyDown(keyCode, event)
}
}
}
| gpl-3.0 | 84bad91533b6cc9505bea8820c390281 | 30.782051 | 76 | 0.573215 | 4.758157 | false | false | false | false |
Le-Chiffre/Yttrium | Core/src/com/rimmer/yttrium/Log.kt | 2 | 1125 | package com.rimmer.yttrium
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
enum class LogLevel {
Message,
Warning,
Error
}
val logFormat: DateTimeFormatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss")
fun log(level: LogLevel, where: Any?, text: String) {
val s = StringBuilder()
s.append("(")
s.append(logFormat.print(DateTime.now().withZone(DateTimeZone.UTC)))
s.append(") ")
if(level != LogLevel.Message) { s.append(level.name); s.append(' ') }
if(where != null) { s.append("at "); s.append(where.javaClass.simpleName); s.append(" - ") }
s.append(text)
println(s)
}
fun logError(text: String) = log(LogLevel.Error, null, text)
fun logWarning(text: String) = log(LogLevel.Warning, null, text)
fun logMessage(text: String) = log(LogLevel.Message, null, text)
fun Any.logError(text: String) = log(LogLevel.Error, this, text)
fun Any.logWarning(text: String) = log(LogLevel.Warning, this, text)
fun Any.logMessage(text: String) = log(LogLevel.Message, this, text)
| mit | 7bea3e5476d8594e39c96462aaabd572 | 31.142857 | 96 | 0.708444 | 3.378378 | false | false | false | false |
Andr3Carvalh0/mGBA | app/src/main/java/io/mgba/utilities/device/PreferencesManager.kt | 1 | 966 | package io.mgba.utilities.device
import android.annotation.SuppressLint
import android.content.Context.MODE_PRIVATE
import io.mgba.mgba
/**
* Controller responsible with the interaction of the SharedPreferences.
* It handles the saving/loading of the preferences.
*/
@SuppressLint("StaticFieldLeak")
object PreferencesManager {
val GAMES_DIRECTORY = "game_dir"
val SETUP_DONE = "setup_done"
private val preferences = mgba.context.getSharedPreferences("MeBeSafe", MODE_PRIVATE)
private val editor = preferences.edit()
fun save(key: String, value: String) {
editor.putString(key, value)
editor.apply()
}
fun save(key: String, value: Boolean) {
editor.putBoolean(key, value)
editor.apply()
}
fun get(key: String, defaultValue: String): String = preferences.getString(key, defaultValue)!!
fun get(key: String, defaultValue: Boolean): Boolean = preferences.getBoolean(key, defaultValue)
}
| mpl-2.0 | 47d78ae5e9681f4d36cc64aa2a59fd45 | 29.1875 | 100 | 0.716356 | 4.218341 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/colorpicker/slider/LightnessSlider.kt | 1 | 2308 | package com.tamsiree.rxui.view.colorpicker.slider
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.PorterDuff
import android.util.AttributeSet
import com.tamsiree.rxkit.RxImageTool.colorAtLightness
import com.tamsiree.rxkit.RxImageTool.lightnessOfColor
import com.tamsiree.rxui.view.colorpicker.ColorPickerView
import com.tamsiree.rxui.view.colorpicker.builder.PaintBuilder
/**
* @author tamsiree
* @date 2018/6/11 11:36:40 整合修改
*/
class LightnessSlider : AbsCustomSlider {
private var color = 0
private val barPaint = PaintBuilder.newPaint().build()
private val solid = PaintBuilder.newPaint().build()
private val clearingStroke = PaintBuilder.newPaint().color(-0x1).xPerMode(PorterDuff.Mode.CLEAR).build()
private var colorPicker: ColorPickerView? = null
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun drawBar(barCanvas: Canvas) {
val width = barCanvas.width
val height = barCanvas.height
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
val l = Math.max(2, width / 256)
var x = 0
while (x <= width) {
hsv[2] = x.toFloat() / (width - 1)
barPaint.color = Color.HSVToColor(hsv)
barCanvas.drawRect(x.toFloat(), 0f, x + l.toFloat(), height.toFloat(), barPaint)
x += l
}
}
override fun onValueChanged(value: Float) {
if (colorPicker != null) {
colorPicker!!.setLightness(value)
}
}
override fun drawHandle(canvas: Canvas, x: Float, y: Float) {
solid.color = colorAtLightness(color, value)
canvas.drawCircle(x, y, handleRadius.toFloat(), clearingStroke)
canvas.drawCircle(x, y, handleRadius * 0.75f, solid)
}
fun setColorPicker(colorPicker: ColorPickerView?) {
this.colorPicker = colorPicker
}
fun setColor(color: Int) {
this.color = color
value = lightnessOfColor(color)
if (bar != null) {
updateBar()
invalidate()
}
}
} | apache-2.0 | 54387d680e2daf67adeb6df54fab2a2f | 33.343284 | 113 | 0.666087 | 3.979239 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityContact.kt | 1 | 2195 | package com.tamsiree.rxdemo.activity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxDeviceTool.setPortrait
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.model.ModelContactCity
import com.tamsiree.rxui.view.wavesidebar.ComparatorLetter
import com.tamsiree.rxui.view.wavesidebar.PinnedHeaderDecoration
import com.tamsiree.rxui.view.wavesidebar.adapter.AdapterContactCity
import kotlinx.android.synthetic.main.activity_contact.*
import java.util.*
/**
* @author tamsiree
*/
class ActivityContact : ActivityBase() {
private var mAdapterContactCity: AdapterContactCity? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_contact)
setPortrait(this)
}
override fun initView() {
rx_title.setLeftFinish(mContext)
recycler_view.layoutManager = LinearLayoutManager(this)
val decoration = PinnedHeaderDecoration()
decoration.registerTypePinnedHeader(1) { parent, adapterPosition -> true }
recycler_view.addItemDecoration(decoration)
side_view.setOnTouchLetterChangeListener { letter ->
val pos = mAdapterContactCity!!.getLetterPosition(letter)
if (pos != -1) {
recycler_view.scrollToPosition(pos)
val mLayoutManager = recycler_view.layoutManager as LinearLayoutManager?
mLayoutManager!!.scrollToPositionWithOffset(pos, 0)
}
}
}
override fun initData() {
Thread(Runnable {
val listType = object : TypeToken<ArrayList<ModelContactCity?>?>() {}.type
val gson = Gson()
val list = gson.fromJson<List<ModelContactCity>>(ModelContactCity.DATA, listType)
Collections.sort(list, ComparatorLetter())
runOnUiThread {
mAdapterContactCity = AdapterContactCity(mContext, list)
recycler_view.adapter = mAdapterContactCity
}
}).start()
}
} | apache-2.0 | 7c8399c01f402c539cc91c00f70c8e56 | 36.220339 | 93 | 0.701595 | 4.7103 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/Constants.kt | 1 | 4902 | package org.wikipedia
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.WikiSite
object Constants {
const val ACTIVITY_REQUEST_ADD_A_LANGUAGE = 59
const val ACTIVITY_REQUEST_BROWSE_TABS = 61
const val ACTIVITY_REQUEST_DESCRIPTION_EDIT = 55
const val ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL = 56
const val ACTIVITY_REQUEST_FEED_CONFIGURE = 58
const val ACTIVITY_REQUEST_GALLERY = 52
const val ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT = 64
const val ACTIVITY_REQUEST_IMAGE_TAGS_EDIT = 66
const val ACTIVITY_REQUEST_IMAGE_TAGS_ONBOARDING = 65
const val ACTIVITY_REQUEST_LANGLINKS = 50
const val ACTIVITY_REQUEST_LOGIN = 53
const val ACTIVITY_REQUEST_OPEN_SEARCH_ACTIVITY = 62
const val ACTIVITY_REQUEST_SETTINGS = 41
const val ACTIVITY_REQUEST_VOICE_SEARCH = 45
const val ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 44
const val INTENT_APP_SHORTCUT_CONTINUE_READING = "appShortcutContinueReading"
const val INTENT_APP_SHORTCUT_RANDOMIZER = "appShortcutRandomizer"
const val INTENT_APP_SHORTCUT_SEARCH = "appShortcutSearch"
const val INTENT_EXTRA_ACTION = "intentAction"
const val INTENT_EXTRA_DELETE_READING_LIST = "deleteReadingList"
const val INTENT_EXTRA_GO_TO_MAIN_TAB = "goToMainTab"
const val INTENT_EXTRA_GO_TO_SE_TAB = "goToSETab"
const val INTENT_EXTRA_HAS_TRANSITION_ANIM = "hasTransitionAnim"
const val INTENT_EXTRA_INVOKE_SOURCE = "invokeSource"
const val INTENT_EXTRA_IMPORT_READING_LISTS = "importReadingLists"
const val INTENT_EXTRA_NOTIFICATION_ID = "notificationId"
const val INTENT_EXTRA_NOTIFICATION_SYNC_CANCEL = "syncCancel"
const val INTENT_EXTRA_NOTIFICATION_SYNC_PAUSE_RESUME = "syncPauseResume"
const val INTENT_EXTRA_NOTIFICATION_TYPE = "notificationType"
const val INTENT_EXTRA_REVERT_QNUMBER = "revertQNumber"
const val INTENT_FEATURED_ARTICLE_FROM_WIDGET = "featuredArticleFromWidget"
const val INTENT_RETURN_TO_MAIN = "returnToMain"
const val MAX_READING_LIST_ARTICLE_LIMIT = 5000
const val MAX_READING_LISTS_LIMIT = 100
const val MAX_TABS = 100
const val MIN_LANGUAGES_TO_UNLOCK_TRANSLATION = 2
const val PLAIN_TEXT_MIME_TYPE = "text/plain"
const val PREFERRED_CARD_THUMBNAIL_SIZE = 800
const val PREFERRED_GALLERY_IMAGE_SIZE = 1280
const val SUGGESTION_REQUEST_ITEMS = 5
const val WIKI_CODE_COMMONS = "commons"
const val COMMONS_DB_NAME = "commonswiki"
const val WIKI_CODE_WIKIDATA = "wikidata"
const val WIKIDATA_DB_NAME = "wikidatawiki"
val commonsWikiSite = WikiSite(Service.COMMONS_URL)
val wikidataWikiSite = WikiSite(Service.WIKIDATA_URL)
enum class InvokeSource(val value: String) {
ANNOUNCEMENT("announcement"),
APP_SHORTCUTS("appShortcuts"),
ARCHIVED_TALK_ACTIVITY("archivedTalkActivity"),
BOOKMARK_BUTTON("bookmark"),
CONTEXT_MENU("contextMenu"),
DIFF_ACTIVITY("diffActivity"),
FEED("feed"),
FEED_BAR("feedBar"),
FILE_PAGE_ACTIVITY("filePage"),
GALLERY_ACTIVITY("gallery"),
INTENT_PROCESS_TEXT("intentProcessText"),
INTENT_SHARE("intentShare"),
INTENT_UNKNOWN("intentUnknown"),
LANG_VARIANT_DIALOG("lang_variant_dialog"),
LEAD_IMAGE("leadImage"),
LINK_PREVIEW_MENU("linkPreviewMenu"),
MAIN_ACTIVITY("main"),
MOST_READ_ACTIVITY("mostRead"),
NAV_MENU("navMenu"),
NEWS_ACTIVITY("news"),
NOTIFICATION("notification"),
ON_THIS_DAY_ACTIVITY("onThisDay"),
ON_THIS_DAY_CARD_BODY("onThisDayCard"),
ON_THIS_DAY_CARD_FOOTER("onThisDayCardFooter"),
ON_THIS_DAY_CARD_YEAR("onThisDayCardYear"),
ONBOARDING_DIALOG("onboarding"),
PAGE_ACTION_TAB("pageActionTab"),
PAGE_ACTIVITY("page"),
PAGE_DESCRIPTION_CTA("pageDescCta"),
PAGE_EDIT_PENCIL("pageEditPencil"),
PAGE_EDIT_HIGHLIGHT("pageEditHighlight"),
PAGE_OVERFLOW_MENU("pageOverflowMenu"),
RANDOM_ACTIVITY("random"),
READ_MORE_BOOKMARK_BUTTON("readMoreBookmark"),
READING_LIST_ACTIVITY("readingList"),
SEARCH("search"),
SETTINGS("settings"),
SNACKBAR_ACTION("snackbar"),
SUGGESTED_EDITS("suggestedEdits"),
TABS_ACTIVITY("tabsActivity"),
TALK_TOPICS_ACTIVITY("talkTopicsActivity"),
TALK_TOPIC_ACTIVITY("talkTopicActivity"),
TALK_REPLY_ACTIVITY("talkReplyActivity"),
EDIT_ACTIVITY("editActivity"),
TOOLBAR("toolbar"),
VOICE("voice"),
WATCHLIST_ACTIVITY("watchlist"),
WIDGET("widget"),
USER_CONTRIB_ACTIVITY("userContribActivity"),
}
enum class ImageEditType(name: String) {
ADD_CAPTION("addCaption"),
ADD_CAPTION_TRANSLATION("addCaptionTranslation"),
ADD_TAGS("addTags")
}
}
| apache-2.0 | 7267a6415da6aad1f0673370cbdd768a | 41.258621 | 81 | 0.68931 | 4.098662 | false | false | false | false |
andimage/PCBridge | src/main/kotlin/com/projectcitybuild/features/chat/ChatGroupFormatBuilder.kt | 1 | 4883 | package com.projectcitybuild.features.chat
import com.projectcitybuild.modules.config.ConfigKey
import com.projectcitybuild.modules.config.PlatformConfig
import com.projectcitybuild.modules.permissions.Permissions
import net.md_5.bungee.api.chat.BaseComponent
import net.md_5.bungee.api.chat.HoverEvent
import net.md_5.bungee.api.chat.TextComponent
import net.md_5.bungee.api.chat.hover.content.Text
import org.bukkit.entity.Player
import javax.inject.Inject
class ChatGroupFormatBuilder @Inject constructor(
private val permissions: Permissions,
private val config: PlatformConfig
) {
data class Aggregate(
val prefix: Array<out BaseComponent>,
val suffix: Array<out BaseComponent>,
val groups: TextComponent,
)
private val trustedGroups = config.get(ConfigKey.GROUPS_TRUST_PRIORITY)
private val builderGroups = config.get(ConfigKey.GROUPS_BUILD_PRIORITY)
private val donorGroups = config.get(ConfigKey.GROUPS_DONOR_PRIORITY)
fun format(player: Player): Aggregate {
val groupNames = permissions.getUserGroups(player.uniqueId)
var highestTrust: Pair<Int, String>? = null
var highestBuild: Pair<Int, String>? = null
var highestDonor: Pair<Int, String>? = null
for (groupName in groupNames) {
val lowercaseGroupName = groupName.lowercase()
val trustIndex = trustedGroups.indexOf(lowercaseGroupName)
if (trustIndex != -1) {
if (highestTrust == null || trustIndex < highestTrust.first) {
highestTrust = Pair(trustIndex, groupName)
}
}
val builderIndex = builderGroups.indexOf(lowercaseGroupName)
if (builderIndex != -1) {
if (highestBuild == null || builderIndex < highestBuild.first) {
highestBuild = Pair(builderIndex, groupName)
}
}
val donorIndex = donorGroups.indexOf(lowercaseGroupName)
if (donorIndex != -1) {
if (highestDonor == null || donorIndex < highestDonor.first) {
highestDonor = Pair(donorIndex, groupName)
}
}
}
val groupTC = TextComponent()
if (highestDonor != null) {
val hoverName = config.get(path = "groups.appearance.${highestDonor.second}.hover_name") as? String
var displayName = config.get(path = "groups.appearance.${highestDonor.second}.display_name") as? String
if (displayName.isNullOrBlank()) {
displayName = permissions.getGroupDisplayName(highestDonor.second)
}
TextComponent
.fromLegacyText(displayName)
.forEach { c ->
if (hoverName != null && hoverName.isNotEmpty()) {
c.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(hoverName))
}
groupTC.addExtra(c)
}
}
if (highestTrust != null) {
val hoverName = config.get(path = "groups.appearance.${highestTrust.second}.hover_name") as? String
var displayName = config.get(path = "groups.appearance.${highestTrust.second}.display_name") as? String
if (displayName.isNullOrBlank()) {
displayName = permissions.getGroupDisplayName(highestTrust.second)
}
TextComponent
.fromLegacyText(displayName)
.forEach { c ->
if (hoverName != null && hoverName.isNotEmpty()) {
c.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(hoverName))
}
groupTC.addExtra(c)
}
}
if (highestBuild != null) {
val hoverName = config.get(path = "groups.appearance.${highestBuild.second}.hover_name") as? String
var displayName = config.get(path = "groups.appearance.${highestBuild.second}.display_name") as? String
if (displayName.isNullOrBlank()) {
displayName = permissions.getGroupDisplayName(highestBuild.second)
}
TextComponent
.fromLegacyText(displayName)
.forEach { c ->
if (hoverName != null && hoverName.isNotEmpty()) {
c.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(hoverName))
}
groupTC.addExtra(c)
}
}
return Aggregate(
prefix = TextComponent.fromLegacyText(
permissions.getUserPrefix(player.uniqueId)
),
suffix = TextComponent.fromLegacyText(
permissions.getUserSuffix(player.uniqueId)
),
groups = groupTC,
)
}
}
| mit | 719c609f27ebb2eba140d7c1a554ca46 | 40.735043 | 115 | 0.591235 | 4.773216 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/splashscreen/SplashScreenView.kt | 2 | 1210 | package abi44_0_0.expo.modules.splashscreen
import android.annotation.SuppressLint
import android.content.Context
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
// this needs to stay for versioning to work
/* ktlint-disable no-unused-imports */
import expo.modules.splashscreen.SplashScreenImageResizeMode
/* ktlint-enable no-unused-imports */
@SuppressLint("ViewConstructor")
class SplashScreenView(
context: Context
) : RelativeLayout(context) {
val imageView: ImageView = ImageView(context).also { view ->
view.layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT
)
}
init {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
isClickable = true
addView(imageView)
}
fun configureImageViewResizeMode(resizeMode: SplashScreenImageResizeMode) {
imageView.scaleType = resizeMode.scaleType
when (resizeMode) {
SplashScreenImageResizeMode.NATIVE -> {}
SplashScreenImageResizeMode.CONTAIN -> {
imageView.adjustViewBounds = true
}
SplashScreenImageResizeMode.COVER -> {}
}
}
}
| bsd-3-clause | 9987ac264e3021c0ae6a67fd90026dc2 | 27.809524 | 115 | 0.753719 | 4.801587 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/game/GameRepo.kt | 2 | 4120 | package de.sudoq.persistence.game
import de.sudoq.model.game.Game
import de.sudoq.model.game.GameSettings
import de.sudoq.model.game.GameStateHandler
import de.sudoq.model.persistence.IRepo
import de.sudoq.model.sudoku.Sudoku
import de.sudoq.model.sudoku.complexity.Complexity
import de.sudoq.model.sudoku.sudokuTypes.SudokuType
import de.sudoq.persistence.XmlHelper
import java.io.File
import java.io.IOException
/**
* repo for the games of one specific profile
*/
class GameRepo(
profilesDir: File,
profileId: Int,
private val sudokuTypeRepo: IRepo<SudokuType>
) : IRepo<Game> {
private val gamesDir: File
val gamesFile: File
/**
* do not use the generated game for anything other than obtaining its id!
*/
override fun create(): Game {
val id = getNextFreeGameId()
val dummySudoku = Sudoku(-1, 0, SudokuType(9, 9, 9), Complexity.arbitrary, HashMap())
return Game(id, dummySudoku)
}
private fun createBE(): GameBE {
val newGame = GameBE()
newGame.id = getNextFreeGameId()
newGame.gameSettings = GameSettings()
newGame.time = 0
newGame.stateHandler = GameStateHandler()
//serialization cannot handle null value for sudoku yet
// and I don't want to change it at this time
/*val file = File(gamesDir, "game_${newGame.id}.xml")
try {
XmlHelper().saveXml(newGame.toXmlTree(), file)
} catch (e: IOException) {
throw IllegalStateException("Error saving game xml tree", e)
}*/
return newGame
}
/**
* Gibt die naechste verfuegbare ID fuer ein Game zurueck
*
* @return naechste verfuegbare ID
*/
fun getNextFreeGameId(): Int {
return gamesDir.list().size + 1
}
/**
* Gibt die XML eines Games des aktuellen Profils anhand seiner ID zurueck
*
* @param id
* ID des Games
* @return File, welcher auf die XML Datei des Games zeigt
*/
fun getGameFile(id: Int): File {
return File(gamesDir, "game_$id.xml")
}
override fun read(id: Int): Game {
val game = readBE(id)
return GameMapper.fromBE(game)
}
private fun readBE(id: Int): GameBE {
val obj = GameBE()
val helper = XmlHelper()
val gameFile: File = getGameFile(id)
//todo is exception catching necessary? profilerepo doesn't catch them
try {
obj.fillFromXml(helper.loadXml(gameFile)!!, sudokuTypeRepo)
} catch (e: IOException) {
throw IllegalArgumentException("Something went wrong when reading xml $gameFile", e)
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Something went wrong when filling obj from xml ", e)
}
return obj
}
override fun update(g: Game): Game {
val gameBE = GameMapper.toBE(g)
val gameLoaded = updateBE(gameBE)
return GameMapper.fromBE(gameLoaded)
}
private fun updateBE(g: GameBE): GameBE {
val file = File(gamesDir, "game_${g.id}.xml")
try {
XmlHelper().saveXml(g.toXmlTree(), file)
} catch (e: IOException) {
throw IllegalStateException("Error saving game xml tree", e)
}
return readBE(g.id)
}
override fun delete(id: Int) {
getGameFile(id).delete()
getGameThumbnailFile(id).delete()
}
// Thumbnails
/**
* Returns the .png File for thumbnail of the game with id gameID
*
* @param gameID
* The ID of the game whos thumbnail is requested.
*
* @return The thumbnail File.
*/
fun getGameThumbnailFile(gameID: Int): File {
return File(
gamesDir.toString() + File.separator + "game_" +
gameID + ".png"
)
}
init {
val profile = File(profilesDir, "profile_$profileId")
this.gamesDir = File(profile, "games")
this.gamesFile = File(profile, "games.xml")
}
override fun ids(): List<Int> {
TODO("Not yet implemented")
}
} | gpl-3.0 | 479a43d0655be12e27d98eeaf5c19284 | 27.42069 | 96 | 0.615534 | 4.03526 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/handlers/HandlerServlet.kt | 1 | 1374 | package au.com.codeka.warworlds.server.handlers
import au.com.codeka.warworlds.common.Log
import java.util.regex.Matcher
import javax.servlet.GenericServlet
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Base [javax.servlet.Servlet] for working with handlers.
*/
open class HandlerServlet protected constructor(private val routes: List<Route>)
: GenericServlet() {
private val log = Log("HandlerServlet")
override fun service(request: ServletRequest, response: ServletResponse) {
val httpRequest = request as HttpServletRequest
val httpResponse = response as HttpServletResponse
for (route in routes) {
val matcher = route.matches(httpRequest)
if (matcher != null) {
handle(matcher, route, httpRequest, httpResponse)
return
}
}
log.info("Could not find handler for URL: ${httpRequest.pathInfo}")
httpResponse.status = 404
}
protected open fun handle(
matcher: Matcher, route: Route, request: HttpServletRequest, response: HttpServletResponse) {
try {
val handler = route.createRequestHandler()
handler.setup(matcher, route.extraOption, request, response)
handler.handle()
} catch (e: RequestException) {
e.populate(response)
}
}
}
| mit | a7fee82d4435c6690ec407442db6c209 | 30.227273 | 99 | 0.729985 | 4.490196 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/completion/RsCommonCompletionProvider.kt | 2 | 24352 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
import com.google.common.annotations.VisibleForTesting
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import com.intellij.util.containers.MultiMap
import org.rust.ide.refactoring.RsNamesValidator
import org.rust.ide.settings.RsCodeInsightSettings
import org.rust.ide.utils.import.*
import org.rust.lang.core.RsPsiPattern
import org.rust.lang.core.macros.findElementExpandedFrom
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psiElement
import org.rust.lang.core.resolve.*
import org.rust.lang.core.resolve.ref.FieldResolveVariant
import org.rust.lang.core.resolve.ref.MethodResolveVariant
import org.rust.lang.core.types.Substitution
import org.rust.lang.core.types.expectedTypeCoercable
import org.rust.lang.core.types.implLookup
import org.rust.lang.core.types.infer.ExpectedType
import org.rust.lang.core.types.infer.containsTyOfClass
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.type
import org.rust.openapiext.Testmark
object RsCommonCompletionProvider : RsCompletionProvider() {
override fun addCompletions(
parameters: CompletionParameters,
processingContext: ProcessingContext,
result: CompletionResultSet
) {
// Use original position if possible to re-use caches of the real file
val position = parameters.position.safeGetOriginalOrSelf()
val element = position.parent as RsReferenceElement
if (position !== element.referenceNameElement) return
// This set will contain the names of all paths that have been added to the `result` by this provider.
val processedPathElements = MultiMap<String, RsElement>()
val context = RsCompletionContext(
element,
getExpectedTypeForEnclosingPathOrDotExpr(element),
isSimplePath = RsPsiPattern.simplePathPattern.accepts(parameters.position)
)
addCompletionVariants(element, result, context, processedPathElements)
if (element is RsMethodOrField) {
addMethodAndFieldCompletion(element, result, context)
}
if (element is RsPath && RsCodeInsightSettings.getInstance().suggestOutOfScopeItems) {
if (context.isSimplePath && !element.isInsideDocLink) {
addCompletionsForOutOfScopeItems(position, element, result, processedPathElements, context.expectedTy)
}
if (processedPathElements.isEmpty) {
addCompletionsForOutOfScopeFirstPathSegment(element, result, context)
}
}
}
@VisibleForTesting
fun addCompletionVariants(
element: RsReferenceElement,
result: CompletionResultSet,
context: RsCompletionContext,
processedElements: MultiMap<String, RsElement>
) {
collectCompletionVariants(result, context) {
val processor = filterNotCfgDisabledItemsAndTestFunctions(it)
when (element) {
is RsAssocTypeBinding -> processAssocTypeVariants(element, processor)
is RsExternCrateItem -> processExternCrateResolveVariants(element, true, processor)
is RsLabel -> processLabelResolveVariants(element, processor)
is RsLifetime -> processLifetimeResolveVariants(element, processor)
is RsMacroReference -> processMacroReferenceVariants(element, processor)
is RsModDeclItem -> processModDeclResolveVariants(element, processor)
is RsPatBinding -> processPatBindingResolveVariants(element, true, processor)
is RsStructLiteralField -> processStructLiteralFieldResolveVariants(element, true, processor)
is RsPath -> {
val processor2 = addProcessedPathName(processor, processedElements)
processPathVariants(element, processor2)
}
}
}
}
private fun processPathVariants(element: RsPath, processor: RsResolveProcessor) {
val parent = element.parent
when {
parent is RsMacroCall -> {
val filtered = filterNotAttributeAndDeriveProcMacros(processor)
processMacroCallPathResolveVariants(element, true, filtered)
}
parent is RsMetaItem -> {
// Derive is handled by [RsDeriveCompletionProvider]
if (!RsProcMacroPsiUtil.canBeProcMacroAttributeCall(parent)) return
val filtered = filterAttributeProcMacros(processor)
processProcMacroResolveVariants(element, filtered, isCompletion = true)
}
// Handled by [RsVisRestrictionCompletionProvider]
parent is RsVisRestriction && parent.`in` == null -> return
else -> {
val lookup = ImplLookup.relativeTo(element)
var filtered: RsResolveProcessor = filterPathCompletionVariantsByTraitBounds(processor, lookup)
if (parent !is RsUseSpeck) {
filtered = filterNotAttributeAndDeriveProcMacros(filtered)
}
// Filters are applied in reverse order (the last filter is applied first)
val filters = listOf(
::filterCompletionVariantsByVisibility,
::filterAssocTypes,
::filterVisRestrictionPaths,
::filterTraitRefPaths
)
for (filter in filters) {
filtered = filter(element, filtered)
}
// RsPathExpr can become a macro by adding a trailing `!`, so we add macros to completion
if (element.parent is RsPathExpr && !(element.hasColonColon && element.isAtLeastEdition2018)) {
processMacroCallPathResolveVariants(element, isCompletion = true, filtered)
}
val possibleTypeArgs = parent?.parent
if (possibleTypeArgs is RsTypeArgumentList) {
val trait = (possibleTypeArgs.parent as? RsPath)?.reference?.resolve() as? RsTraitItem
if (trait != null) {
processAssocTypeVariants(trait, filtered)
}
}
processPathResolveVariants(
lookup,
element,
true,
filtered
)
}
}
}
@VisibleForTesting
fun addMethodAndFieldCompletion(
element: RsMethodOrField,
result: CompletionResultSet,
context: RsCompletionContext
) {
val receiver = element.receiver.safeGetOriginalOrSelf()
val lookup = ImplLookup.relativeTo(receiver)
val receiverTy = receiver.type
val processResolveVariants = if (element is RsMethodCall) {
::processMethodCallExprResolveVariants
} else {
::processDotExprResolveVariants
}
val processor = methodAndFieldCompletionProcessor(element, result, context)
processResolveVariants(
lookup,
receiverTy,
element,
filterCompletionVariantsByVisibility(
receiver,
filterMethodCompletionVariantsByTraitBounds(
lookup,
receiverTy,
deduplicateMethodCompletionVariants(processor)
)
)
)
}
private fun addCompletionsForOutOfScopeItems(
position: PsiElement,
path: RsPath,
result: CompletionResultSet,
processedPathElements: MultiMap<String, RsElement>,
expectedTy: ExpectedType?
) {
run {
val originalFile = position.containingFile.originalFile
// true if delegated from RsPartialMacroArgumentCompletionProvider
val ignoreCodeFragment = originalFile is RsExpressionCodeFragment
&& originalFile.getUserData(FORCE_OUT_OF_SCOPE_COMPLETION) != true
if (ignoreCodeFragment) return
// Not null if delegated from RsMacroCallBodyCompletionProvider
val positionInMacroArgument = position.findElementExpandedFrom()
// Checks that macro call and expanded element are located in the same modules
if (positionInMacroArgument != null && !isInSameRustMod(positionInMacroArgument, position)) {
return
}
}
if (TyPrimitive.fromPath(path) != null) return
val parent = path.parent
if (parent is RsMetaItem && !RsProcMacroPsiUtil.canBeProcMacroAttributeCall(parent)) return
Testmarks.OutOfScopeItemsCompletion.hit()
val context = RsCompletionContext(path, expectedTy, isSimplePath = true)
val importContext = ImportContext.from(path, ImportContext.Type.COMPLETION) ?: return
val candidates = ImportCandidatesCollector.getCompletionCandidates(importContext, result.prefixMatcher, processedPathElements)
for (candidate in candidates) {
val item = candidate.item
val scopeEntry = SimpleScopeEntry(candidate.itemName, item)
if (item is RsEnumItem
&& (context.expectedTy?.ty?.stripReferences() as? TyAdt)?.item == (item.declaredType as? TyAdt)?.item) {
val variants = collectVariantsForEnumCompletion(item, context, scopeEntry.subst, candidate)
result.addAllElements(variants)
}
val lookupElement = createLookupElementWithImportCandidate(scopeEntry, context, candidate)
result.addElement(lookupElement)
}
}
/** Adds completions for the case `HashMap::/*caret*/` where `HashMap` is not imported. */
private fun addCompletionsForOutOfScopeFirstPathSegment(path: RsPath, result: CompletionResultSet, context: RsCompletionContext) {
val qualifier = path.path ?: return
val isApplicablePath = (qualifier.path == null && qualifier.typeQual == null && !qualifier.hasColonColon
&& qualifier.resolveStatus == PathResolveStatus.UNRESOLVED)
if (!isApplicablePath) return
// We don't use `Type.COMPLETION` because we're importing the first segment of the 2-segment path,
// so we don't want to relax the namespace filter
val importContext = ImportContext.from(qualifier, ImportContext.Type.AUTO_IMPORT) ?: return
val referenceName = qualifier.referenceName ?: return
val itemToCandidates = ImportCandidatesCollector.getImportCandidates(importContext, referenceName)
.groupBy { it.item }
for ((_, candidates) in itemToCandidates) {
// Here all use path resolves to the same item, so we can just use the first of them
val firstUsePath = candidates.first().info.usePath
val newPath = RsCodeFragmentFactory(path.project).createPathInTmpMod(
path.text,
importContext.rootMod,
path.pathParsingMode,
path.allowedNamespaces(isCompletion = true),
firstUsePath,
null
)
if (newPath != null) {
val processor = filterNotCfgDisabledItemsAndTestFunctions(createProcessor { e ->
for (candidate in candidates) {
result.addElement(createLookupElementWithImportCandidate(e, context, candidate))
}
false
})
processPathVariants(newPath, processor)
}
}
}
private fun createLookupElementWithImportCandidate(
scopeEntry: ScopeEntry,
context: RsCompletionContext,
candidate: ImportCandidate
): RsImportLookupElement {
return createLookupElement(
scopeEntry = scopeEntry,
context = context,
locationString = candidate.info.usePath,
insertHandler = object : RsDefaultInsertHandler() {
override fun handleInsert(
element: RsElement,
scopeName: String,
context: InsertionContext,
item: LookupElement
) {
super.handleInsert(element, scopeName, context, item)
context.import(candidate)
}
}
).withImportCandidate(candidate)
}
private fun isInSameRustMod(element1: PsiElement, element2: PsiElement): Boolean =
element1.contextOrSelf<RsElement>()?.containingMod ==
element2.contextOrSelf<RsElement>()?.containingMod
override val elementPattern: ElementPattern<PsiElement>
get() = PlatformPatterns.psiElement().withParent(psiElement<RsReferenceElement>())
object Testmarks {
object OutOfScopeItemsCompletion : Testmark()
}
}
data class RsCompletionContext(
val context: RsElement? = null,
val expectedTy: ExpectedType? = null,
val isSimplePath: Boolean = false
) {
val lookup: ImplLookup? = context?.implLookup
}
/**
* Ignore items that are not an ancestor module of the given path
* in path completion inside visibility restriction:
* `pub(in <here>)`
*/
private fun filterVisRestrictionPaths(
path: RsPath,
processor: RsResolveProcessor
): RsResolveProcessor {
return if (path.parent is RsVisRestriction) {
val allowedModules = path.containingMod.superMods
createProcessor(processor.names) {
when (it.element) {
!is RsMod -> false
!in allowedModules -> false
else -> processor(it)
}
}
} else {
processor
}
}
/**
* Ignore items that are not traits (or modules, which could lead to traits) inside trait refs:
* `impl /*here*/ for <type>`
* `fn foo<T: /*here*/>() {}
*/
private fun filterTraitRefPaths(
path: RsPath,
processor: RsResolveProcessor
): RsResolveProcessor {
val parent = path.parent
return if (parent is RsTraitRef) {
createProcessor(processor.names) {
if (it.element is RsTraitItem || it.element is RsMod) {
processor(it)
} else {
false
}
}
} else {
processor
}
}
private fun filterAssocTypes(
path: RsPath,
processor: RsResolveProcessor
): RsResolveProcessor {
val qualifier = path.path
val allAssocItemsAllowed =
qualifier == null || qualifier.hasCself || qualifier.reference?.resolve() is RsTypeParameter
return if (allAssocItemsAllowed) processor else createProcessor(processor.names) {
if (it is AssocItemScopeEntry && (it.element is RsTypeAlias)) false
else processor(it)
}
}
private fun filterPathCompletionVariantsByTraitBounds(
processor: RsResolveProcessor,
lookup: ImplLookup
): RsResolveProcessor {
val cache = hashMapOf<TraitImplSource, Boolean>()
return createProcessor(processor.names) {
if (it !is AssocItemScopeEntry) return@createProcessor processor(it)
val receiver = it.subst[TyTypeParameter.self()] ?: return@createProcessor processor(it)
// Don't filter partially unknown types
if (receiver.containsTyOfClass(TyUnknown::class.java)) return@createProcessor processor(it)
// Filter members by trait bounds (try to select all obligations for each impl)
// We're caching evaluation results here because we can often complete members
// in the same impl and always have the same receiver type
val canEvaluate = cache.getOrPut(it.source) {
lookup.ctx.canEvaluateBounds(it.source, receiver)
}
if (canEvaluate) return@createProcessor processor(it)
false
}
}
private fun filterMethodCompletionVariantsByTraitBounds(
lookup: ImplLookup,
receiver: Ty,
processor: RsResolveProcessor
): RsResolveProcessor {
// Don't filter partially unknown types
if (receiver.containsTyOfClass(TyUnknown::class.java)) return processor
val cache = mutableMapOf<Pair<TraitImplSource, Int>, Boolean>()
return createProcessor(processor.names) {
// If not a method (actually a field) or a trait method - just process it
if (it !is MethodResolveVariant) return@createProcessor processor(it)
// Filter methods by trait bounds (try to select all obligations for each impl)
// We're caching evaluation results here because we can often complete methods
// in the same impl and always have the same receiver type
val canEvaluate = cache.getOrPut(it.source to it.derefCount) {
lookup.ctx.canEvaluateBounds(it.source, it.selfTy)
}
if (canEvaluate) return@createProcessor processor(it)
false
}
}
/**
* There can be multiple impls of the same trait on different dereference levels.
* For example, trait `Debug` is implemented for `str` and for `&str`. In this case
* we receive completion variants for both `str` and `&str` implementation, but they
* are absolutely identical for a user.
*
* Here we deduplicate method completion variants by a method name and a trait.
*
* Should be applied after [filterMethodCompletionVariantsByTraitBounds]
*/
private fun deduplicateMethodCompletionVariants(processor: RsResolveProcessor): RsResolveProcessor {
val processedNamesAndTraits = mutableSetOf<Pair<String, RsTraitItem?>>()
return createProcessor(processor.names) {
if (it !is MethodResolveVariant) return@createProcessor processor(it)
val shouldProcess = processedNamesAndTraits.add(it.name to it.source.implementedTrait?.element)
if (shouldProcess) return@createProcessor processor(it)
false
}
}
private fun methodAndFieldCompletionProcessor(
methodOrField: RsMethodOrField,
result: CompletionResultSet,
context: RsCompletionContext
): RsResolveProcessor = createProcessor { e ->
when (e) {
is FieldResolveVariant -> result.addElement(createLookupElement(
scopeEntry = e,
context = context
))
is MethodResolveVariant -> {
if (e.element.isTest) return@createProcessor false
result.addElement(createLookupElement(
scopeEntry = e,
context = context,
insertHandler = object : RsDefaultInsertHandler() {
override fun handleInsert(
element: RsElement,
scopeName: String,
context: InsertionContext,
item: LookupElement
) {
val traitImportCandidate = findTraitImportCandidate(methodOrField, e)
super.handleInsert(element, scopeName, context, item)
if (traitImportCandidate != null) {
context.commitDocument()
context.getElementOfType<RsElement>()?.let { traitImportCandidate.import(it) }
}
}
}
))
}
}
false
}
private fun findTraitImportCandidate(methodOrField: RsMethodOrField, resolveVariant: MethodResolveVariant): ImportCandidate? {
if (!RsCodeInsightSettings.getInstance().importOutOfScopeItems) return null
val ancestor = PsiTreeUtil.getParentOfType(methodOrField, RsBlock::class.java, RsMod::class.java) ?: return null
// `ImportCandidatesCollector.getImportCandidates` expects original scope element for correct item filtering
val scope = CompletionUtil.getOriginalElement(ancestor) as? RsElement ?: return null
val candidates = ImportCandidatesCollector.getImportCandidates(scope, listOf(resolveVariant))?.asSequence()
return candidates.orEmpty().singleOrNull()
}
private fun addProcessedPathName(
processor: RsResolveProcessor,
processedPathElements: MultiMap<String, RsElement>
): RsResolveProcessor = createProcessor(processor.names) {
val element = it.element
if (element != null) {
processedPathElements.putValue(it.name, element)
}
processor(it)
}
private fun getExpectedTypeForEnclosingPathOrDotExpr(element: RsReferenceElement): ExpectedType? {
for (ancestor in element.ancestors) {
if (element.endOffset < ancestor.endOffset) continue
if (element.endOffset > ancestor.endOffset) break
when (ancestor) {
is RsPathExpr -> return ancestor.expectedTypeCoercable
is RsDotExpr -> return ancestor.expectedTypeCoercable
}
}
return null
}
fun LookupElement.withImportCandidate(candidate: ImportCandidate): RsImportLookupElement {
return RsImportLookupElement(this, candidate)
}
/**
* Provides [equals] and [hashCode] that take into account the corresponding [ImportCandidate].
* We need to distinguish lookup elements with the same psi element and the same lookup text
* but belong to different import candidates, otherwise the platform shows only one such item.
*
* See [#5415](https://github.com/intellij-rust/intellij-rust/issues/5415)
*/
class RsImportLookupElement(
delegate: LookupElement,
private val candidate: ImportCandidate
) : LookupElementDecorator<LookupElement>(delegate) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as RsImportLookupElement
if (candidate != other.candidate) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + candidate.hashCode()
return result
}
}
fun collectVariantsForEnumCompletion(
element: RsEnumItem,
context: RsCompletionContext,
substitution: Substitution,
candidate: ImportCandidate? = null
): List<LookupElement> {
val enumName = element.name ?: return emptyList()
return element.enumBody?.childrenOfType<RsEnumVariant>().orEmpty().mapNotNull { enumVariant ->
val variantName = enumVariant.name ?: return@mapNotNull null
return@mapNotNull createLookupElement(
scopeEntry = SimpleScopeEntry("${enumName}::${variantName}", enumVariant, substitution),
context = context,
null,
object : RsDefaultInsertHandler() {
override fun handleInsert(element: RsElement, scopeName: String, context: InsertionContext, item: LookupElement) {
// move start offset from enum to its variant to escape it
val enumStartOffset = context.startOffset
val variantStartOffset = enumStartOffset + (enumName.length + 2)
context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, variantStartOffset)
super.handleInsert(enumVariant, variantName, context, item)
// escape enum name if needed
if (element is RsNameIdentifierOwner && !RsNamesValidator.isIdentifier(enumName) && enumName !in CAN_NOT_BE_ESCAPED)
context.document.insertString(enumStartOffset, RS_RAW_PREFIX)
if (candidate != null && RsCodeInsightSettings.getInstance().importOutOfScopeItems) {
context.commitDocument()
context.getElementOfType<RsElement>()?.let { it -> candidate.import(it) }
}
}
}
).let { if (candidate != null) it.withImportCandidate(candidate) else it }
}
}
fun InsertionContext.import(candidate: ImportCandidate) {
if (RsCodeInsightSettings.getInstance().importOutOfScopeItems) {
commitDocument()
getElementOfType<RsElement>()?.let { candidate.import(it) }
}
}
| mit | 1e144dd6ccb98db71b97cade3f618eef | 40.414966 | 136 | 0.654484 | 5.163698 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/test/java/com/habitrpg/android/habitica/utils/DateDeserializerTest.kt | 2 | 2550 | package com.habitrpg.android.habitica.utils
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.habitrpg.android.habitica.BaseAnnotationTestCase
import io.kotest.matchers.shouldBe
import java.lang.reflect.Type
import java.util.Date
class DateDeserializerTest : BaseAnnotationTestCase() {
var deserializer = DateDeserializer()
lateinit var deserializationContext: JsonDeserializationContext
lateinit var serializationContext: JsonSerializationContext
var referenceTimestamp: Long = 1443445200000
@Before
fun setup() {
deserializationContext = object : JsonDeserializationContext {
override fun <T> deserialize(json: JsonElement, typeOfT: Type): T? {
return null
}
}
serializationContext = object : JsonSerializationContext {
override fun serialize(src: Any): JsonElement? {
return null
}
override fun serialize(src: Any, typeOfSrc: Type): JsonElement? {
return null
}
}
}
@Test
fun validateNormalDateDeserialize() {
val date = deserializer.deserialize(
JsonPrimitive("2015-09-28T13:00:00.000Z"),
Date::class.java,
deserializationContext
)
date shouldBe Date(referenceTimestamp)
}
@Test
fun validateTimestampDeserialize() {
val date = deserializer.deserialize(
JsonPrimitive(referenceTimestamp),
Date::class.java,
deserializationContext
)
date shouldBe Date(referenceTimestamp)
}
@Test
fun validateEmptyDeserialize() {
val date =
deserializer.deserialize(JsonPrimitive(""), Date::class.java, deserializationContext)
date shouldBe null
}
@Test
fun validateNormalDateSerialize() {
val dateElement: JsonElement = deserializer!!.serialize(
Date(
referenceTimestamp!!
),
Date::class.java, serializationContext
)
dateElement.asString shouldBe "2015-09-28T13:00:00.000Z"
}
@Test
fun validateEmptySerialize() {
val dateElement: JsonElement =
deserializer!!.serialize(null, Date::class.java, serializationContext)
dateElement.asString shouldBe ""
}
}
| gpl-3.0 | ac53af8d0d6f82f44e22f26446a2a0a3 | 29.875 | 97 | 0.630196 | 5.301455 | false | true | false | false |
erva/CellAdapter | sample-x-kotlin/src/main/kotlin/io/erva/sample/base/BaseSampleActivity.kt | 1 | 2667 | package io.erva.sample.base
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import io.erva.celladapter.x.CellAdapter
import io.erva.sample.DividerItemDecoration
import io.erva.sample.R
import io.erva.sample.base.cell.AlphaCell
import io.erva.sample.base.cell.BetaCell
import io.erva.sample.base.cell.GammaCell
import io.erva.sample.base.model.AlphaModel
import io.erva.sample.base.model.BetaModel
import io.erva.sample.base.model.GammaModel
import kotlinx.android.synthetic.main.activity_with_recycler_view.*
class BaseSampleActivity : AppCompatActivity() {
private var toast: Toast? = null
private var adapter: CellAdapter = CellAdapter().let {
it.cell(AlphaCell::class) {
item(AlphaModel::class)
listener(object : AlphaCell.Listener {
override fun onPressOne(item: AlphaModel) {
showToast(String.format("%s%npress button %d", item.alpha, 1))
}
override fun onPressTwo(item: AlphaModel) {
showToast(String.format("%s%npress button %d", item.alpha, 2))
}
override fun onCellClicked(item: AlphaModel) {
showToast(item.alpha)
}
})
}
it.cell(BetaCell::class) {
item(BetaModel::class)
listener(object : BetaCell.Listener {
override fun onCellClicked(item: BetaModel) {
showToast(item.beta)
}
})
}
it.cell(GammaCell::class) {
item(GammaModel::class)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_with_recycler_view)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.addItemDecoration(DividerItemDecoration(this))
recycler_view.adapter = adapter
for (i in 0..33) {
adapter.items.add(AlphaModel(String.format("AlphaModel %d", i)))
adapter.items.add(BetaModel(String.format("BetaModel %d", i)))
adapter.items.add(GammaModel(String.format("GammaModel %d", i)))
}
adapter.notifyDataSetChanged()
}
override fun onStop() {
super.onStop()
dismissToast()
}
private fun showToast(text: String) {
dismissToast()
toast = Toast.makeText(this, text, Toast.LENGTH_SHORT)
toast?.show()
}
private fun dismissToast() {
toast?.cancel()
}
} | mit | b63fe498b78b4a4da77e45a8f6c6725a | 31.536585 | 82 | 0.626547 | 4.274038 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/management/MapItemController.kt | 1 | 6815 | package nl.rsdt.japp.jotial.maps.management
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import com.google.android.gms.maps.model.CircleOptions
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.BundleIdentifiable
import nl.rsdt.japp.jotial.Identifiable
import nl.rsdt.japp.jotial.IntentCreatable
import nl.rsdt.japp.jotial.Recreatable
import nl.rsdt.japp.jotial.io.StorageIdentifiable
import nl.rsdt.japp.jotial.maps.MapItemHolder
import nl.rsdt.japp.jotial.maps.Mergable
import nl.rsdt.japp.jotial.maps.management.controllers.*
import nl.rsdt.japp.jotial.maps.management.transformation.AbstractTransducer
import nl.rsdt.japp.jotial.maps.management.transformation.Transducable
import nl.rsdt.japp.jotial.maps.management.transformation.async.AsyncTransduceTask
import nl.rsdt.japp.jotial.maps.searching.Searchable
import nl.rsdt.japp.jotial.maps.wrapper.*
import nl.rsdt.japp.service.cloud.data.UpdateInfo
import org.acra.ACRA
import org.acra.ktx.sendWithAcra
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
import kotlin.collections.HashMap
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 31-7-2016
* Description...
*/
abstract class MapItemController<I, O : AbstractTransducer.Result>(protected val jotiMap: IJotiMap) : MapItemDateControl(), Recreatable, MapItemHolder, MapItemUpdatable<I>, Transducable<I, O>, Identifiable, StorageIdentifiable, BundleIdentifiable, AsyncTransduceTask.OnTransduceCompletedCallback<O>, IntentCreatable, Searchable, Callback<I>, Mergable<O>, SharedPreferences.OnSharedPreferenceChangeListener {
override var markers: MutableList<IMarker> = ArrayList()
protected set
override var polylines: MutableList<IPolyline> = ArrayList()
protected set
override var polygons: MutableList<IPolygon> = ArrayList()
protected set
var circlesController: MutableMap<ICircle, Int> = HashMap()
override val circles: List<ICircle>
get() {
return circlesController.keys.toList()
}
var visiblity = true
set(value) {
field= value
for (i in markers.indices) {
markers[i].isVisible = visiblity
}
for (i in polylines.indices) {
polylines[i].setVisible(visiblity)
}
for (i in polygons.indices) {
polygons[i].setVisible(visiblity)
}
val circles = ArrayList(this.circlesController.keys)
for (i in circles.indices) {
circles[i].setVisible(visiblity)
}
}
init{
JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onIntentCreate(bundle: Bundle) {
val result = bundle.getParcelable<O>(bundleId)
if (result != null) {
processResult(result)
}
}
override fun onUpdateInvoked() {
val call = update(MapItemUpdatable.MODE_ALL, this)
}
override fun onUpdateMessage(info: UpdateInfo) {
val call: Call<I>?
when (info.action) {
UpdateInfo.ACTION_NEW -> update(MapItemUpdatable.MODE_ALL,this)
UpdateInfo.ACTION_UPDATE -> update(MapItemUpdatable.MODE_ALL, this)
else -> call = null
}
}
override fun onResponse(call: Call<I>, response: Response<I>) {
val body = response.body()
if (body != null){
transducer.enqueue(body, this)
}else{
Log.println(Log.ERROR, TAG, response.message())
ACRA.errorReporter.handleException(null)
}
}
override fun onFailure(call: Call<I>, t: Throwable) {
t.sendWithAcra()
Log.e(TAG, t.toString(), t)
}
override fun onTransduceCompleted(result: O) {
if (markers.isNotEmpty() || polylines.isNotEmpty() || polygons.isNotEmpty()) {
merge(result)
} else {
processResult(result)
}
}
protected open fun processResult(result: O) {
val markers = result.markers
var marker: IMarker
for (m in markers.indices) {
marker = jotiMap.addMarker(markers[m])
marker.isVisible = visiblity
this.markers.add(marker)
}
val polylines = result.polylines
var polyline: IPolyline
for (p in polylines.indices) {
polyline = jotiMap.addPolyline(polylines[p])
polyline.setVisible(visiblity)
this.polylines.add(polyline)
}
val polygons = result.polygons
var polygon: IPolygon
for (g in polygons.indices) {
polygon = jotiMap.addPolygon(polygons[g])
polygon.setVisible(visiblity)
this.polygons.add(polygon)
}
val circles = result.circles ?: emptyList<CircleOptions>()
for (c in circles.indices) {
val circle = jotiMap.addCircle(circles[c])
circle.setVisible(visiblity)
this.circlesController[circle] = circle.fillColor
if (!JappPreferences.fillCircles()) {
circle.fillColor = Color.TRANSPARENT
}
}
}
protected open fun clear() {
for (i in markers.indices) {
markers[i].remove()
}
markers.clear()
for (i in polylines.indices) {
polylines[i].remove()
}
polylines.clear()
for (i in polygons.indices) {
polygons[i].remove()
}
polygons.clear()
val circles = ArrayList(this.circlesController.keys)
for (i in circles.indices) {
circles[i].remove()
}
circles.clear()
}
override fun searchFor(query: String): IMarker? {
var marker: IMarker
for (i in markers.indices) {
marker = markers[i]
if (marker.title == query) {
return marker
}
}
return null
}
override fun onDestroy() {
markers.clear()
polylines.clear()
polygons.clear()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == JappPreferences.FILL_CIRCLES) {
if (JappPreferences.fillCircles()) {
for ((key1, value) in circlesController) {
key1.fillColor = value
}
} else {
for ((key1) in circlesController) {
key1.fillColor = Color.TRANSPARENT
}
}
}
}
companion object {
val TAG = "MapItemController"
}
}
| apache-2.0 | 10df57069484168f63c0e384823113ba | 29.698198 | 407 | 0.617608 | 4.377007 | false | false | false | false |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationSpotifyThemeTrackDaoDelegate.kt | 1 | 1726 | package data.tinder.recommendation
import data.database.DaoDelegate
import domain.recommendation.DomainRecommendationSpotifyThemeTrack
internal class RecommendationSpotifyThemeTrackDaoDelegate(
private val spotifyThemeTrackDelegate: RecommendationUserSpotifyThemeTrackDao,
private val spotifyArtistDaoDelegate: RecommendationSpotifyArtistDaoDelegate,
private val spotifyAlbumDaoDelegate: RecommendationSpotifyAlbumDaoDelegate)
: DaoDelegate<String?, DomainRecommendationSpotifyThemeTrack?>() {
override fun selectByPrimaryKey(primaryKey: String?): DomainRecommendationSpotifyThemeTrack? {
if (primaryKey == null) {
return null
}
return spotifyThemeTrackDelegate.selectSpotifyThemeTrackById(primaryKey).firstOrNull()
?.let {
val artists = spotifyArtistDaoDelegate.collectByPrimaryKeys(it.artists)
it.recommendationUserSpotifyThemeTrackEntity.let {
DomainRecommendationSpotifyThemeTrack(
artists = artists,
album = spotifyAlbumDaoDelegate.selectByPrimaryKey(it.album),
previewUrl = it.previewUrl,
name = it.name,
id = it.id,
uri = it.uri)
}
}
}
override fun insertResolved(source: DomainRecommendationSpotifyThemeTrack?) {
source?.apply {
spotifyAlbumDaoDelegate.insertResolved(album)
spotifyArtistDaoDelegate.insertResolvedForTrackId(id, artists)
spotifyThemeTrackDelegate.insertSpotifyThemeTrack(
RecommendationUserSpotifyThemeTrackEntity(
album = album.id,
previewUrl = previewUrl,
name = name,
id = id,
uri = uri))
}
}
}
| mit | 612db5d4cde9b3945296038e15c0a2b0 | 39.139535 | 96 | 0.702781 | 5.03207 | false | false | false | false |
EddieVanHalen98/vision-kt | main/out/production/core/com/evh98/vision/screens/GameScreen.kt | 2 | 1868 | package com.evh98.vision.screens
import com.badlogic.gdx.graphics.OrthographicCamera
import com.evh98.vision.Vision
import com.evh98.vision.models.Models
import com.evh98.vision.ui.GamePane
import com.evh98.vision.util.Controller
import com.evh98.vision.util.Palette
class GameScreen(vision: Vision): VisionScreen(vision) {
var scrollCamera = OrthographicCamera()
var x = -1
var y = -1
val gamePanes = mutableListOf<GamePane>()
init {
scrollCamera.setToOrtho(true, vision.WIDTH, vision.HEIGHT)
}
override fun show() {
super.show()
start(Palette.RED)
generatePanes()
}
override fun draw(delta: Float) {
scrollCamera.update()
sprite_batch.projectionMatrix = scrollCamera.combined
renderPanes()
}
override fun update() {
super.update()
if (Controller.isNavigationKey()) {
val newCoords = Controller.getNewXY(x, y, 3, gamePanes.size / 3, gamePanes.size)
x = newCoords[0]
y = newCoords[1]
if ((y - 1) % 3 == 0) {
scrollCamera.position.y = ((y / 3) * 2160).toFloat()
}
println(scrollCamera.position.y)
println(y)
}
else if (Controller.isRed()) {
vision.screen = vision.homeScreen
}
}
private fun generatePanes() {
for (i in 0 .. Models.games.size - 1) {
val gamePane = GamePane(Models.games[i], i % 3, i / 3)
gamePanes.add(gamePane)
}
}
private fun renderPanes() {
for (gamePane in gamePanes) {
if (gamePane.xPos == (x - 1) && gamePane.yPos == (y - 1)) {
gamePane.renderSelect(sprite_batch, shape_renderer)
} else {
gamePane.renderUnselect(sprite_batch)
}
}
}
} | mit | a65cca2573852438d5ebc0959189a749 | 24.256757 | 92 | 0.57334 | 3.820041 | false | false | false | false |
IRA-Team/VKPlayer | app/src/main/java/com/irateam/vkplayer/activity/AudioActivity.kt | 1 | 4612 | /*
* Copyright (C) 2015 IRA-Team
*
* 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.irateam.vkplayer.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import com.irateam.vkplayer.R
import com.irateam.vkplayer.api.service.VKAudioService
import com.irateam.vkplayer.controller.ActivityPlayerController
import com.irateam.vkplayer.controller.PlayerController
import com.irateam.vkplayer.event.DownloadFinishedEvent
import com.irateam.vkplayer.model.VKAudio
import com.irateam.vkplayer.player.Player
import com.irateam.vkplayer.service.DownloadService
import com.irateam.vkplayer.service.PlayerService
import com.irateam.vkplayer.util.EventBus
import com.irateam.vkplayer.util.extension.execute
import com.irateam.vkplayer.util.extension.getViewById
import com.irateam.vkplayer.util.extension.startService
import com.melnykov.fab.FloatingActionButton
import org.greenrobot.eventbus.Subscribe
class AudioActivity : AppCompatActivity() {
private val audioService = VKAudioService(this)
private lateinit var playerController: PlayerController
private lateinit var menu: Menu
private lateinit var toolbar: Toolbar
private lateinit var fab: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_audio)
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up)
toolbar = getViewById(R.id.toolbar_transparent)
setSupportActionBar(toolbar)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
title = ""
}
fab = getViewById(R.id.fab)
fab.setOnClickListener { finish() }
playerController = ActivityPlayerController(this, findViewById(R.id.activity_player_panel)!!)
playerController.initialize()
startService<PlayerService>()
EventBus.register(this)
EventBus.register(playerController)
}
override fun onDestroy() {
EventBus.unregister(this)
EventBus.unregister(playerController)
super.onDestroy()
}
@Subscribe
fun onDownloadFinished(e: DownloadFinishedEvent) {
val audio = e.audio
when (audio) {
is VKAudio -> setCacheAction(audio.isCached)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
this.menu = menu
menuInflater.inflate(R.menu.menu_audio, menu)
val audio = Player.audio
when (audio) {
is VKAudio -> setCacheAction(audio.isCached)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
android.R.id.home -> {
finish()
true
}
R.id.action_cache -> {
saveCurrentAudioToCache()
true
}
R.id.action_remove_from_cache -> {
removeCurrentAudioFromCache()
true
}
else -> {
super.onOptionsItemSelected(item)
}
}
private fun saveCurrentAudioToCache() {
Player.audio?.let {
DownloadService.download(this, listOf(it))
}
}
private fun removeCurrentAudioFromCache() {
val audio = Player.audio
if (audio is VKAudio) {
audioService.removeFromCache(listOf(audio)).execute {
onSuccess {
setCacheAction(false)
}
}
}
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.slide_out_up_close, R.anim.slide_out_down)
}
fun setCacheAction(isCached: Boolean) = if (isCached) {
menu.findItem(R.id.action_remove_from_cache).isVisible = true
menu.findItem(R.id.action_cache).isVisible = false
} else {
menu.findItem(R.id.action_remove_from_cache).isVisible = false
menu.findItem(R.id.action_cache).isVisible = true
}
}
| apache-2.0 | 542ed53bbaa77f64c089bb9b69ff958e | 30.589041 | 101 | 0.677147 | 4.49075 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/widgets/dialog/MessageDialogView.kt | 2 | 4469 | package ru.fantlab.android.ui.widgets.dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.message_dialog.*
import ru.fantlab.android.R
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.helper.InputHelper
import ru.fantlab.android.ui.base.BaseBottomSheetDialog
open class MessageDialogView : BaseBottomSheetDialog() {
interface MessageDialogViewActionCallback {
fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?)
fun onDialogDismissed()
}
private var callback: MessageDialogViewActionCallback? = null
override fun onAttach(context: Context) {
super.onAttach(context)
if (parentFragment != null && parentFragment is MessageDialogViewActionCallback) {
callback = parentFragment as MessageDialogViewActionCallback
} else if (context is MessageDialogViewActionCallback) {
callback = context
}
}
override fun onDetach() {
super.onDetach()
callback = null
}
override fun layoutRes(): Int {
return R.layout.message_dialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val bundle = arguments
title.text = bundle?.getString("bundleTitle")
val editorMode = bundle?.getBoolean("editorMode")!!
if (editorMode) {
message.visibility = View.GONE
editText.visibility = View.VISIBLE
val msg = bundle?.getString("bundleMsg")
editText.setText(msg ?: "")
} else {
editText.visibility = View.GONE
message.visibility = View.VISIBLE
val msg = bundle?.getString("bundleMsg")
message.text = msg
}
bundle?.let {
val hideCancel = it.getBoolean("hideCancel")
if (hideCancel) cancel.visibility = View.GONE
initButton(it)
}
ok.setOnClickListener {
callback?.let {
isAlreadyHidden = true
val resBundle = arguments?.getBundle("bundle")
if (editorMode) {
resBundle?.putString("edit_text", editText?.text.toString())
}
it.onMessageDialogActionClicked(true, resBundle)
}
dismiss()
}
cancel.setOnClickListener {
callback?.let {
isAlreadyHidden = true
it.onMessageDialogActionClicked(false, arguments?.getBundle("bundle"))
}
dismiss()
}
}
private fun initButton(bundle: Bundle) {
val extra = bundle.getBundle("bundle")
if (extra != null) {
val yesNo = extra.getBoolean(BundleConstant.YES_NO_EXTRA)
if (yesNo) {
ok.setText(R.string.yes)
cancel.setText(R.string.no)
} else {
val hideButtons = extra.getBoolean("hide_buttons")
val primaryExtra = extra.getString("primary_extra")
val secondaryExtra = extra.getString("secondary_extra")
if (hideButtons) {
ok.visibility = View.GONE
cancel.visibility = View.GONE
} else if (!InputHelper.isEmpty(primaryExtra)) {
ok.text = primaryExtra
if (!InputHelper.isEmpty(secondaryExtra)) cancel.text = secondaryExtra
ok.visibility = View.VISIBLE
cancel.visibility = View.VISIBLE
}
}
}
}
override fun onDismissedByScrolling() {
super.onDismissedByScrolling()
callback?.onDialogDismissed()
}
override fun onHidden() {
callback?.onDialogDismissed()
super.onHidden()
}
companion object {
val TAG: String = MessageDialogView::class.java.simpleName
fun newInstance(bundleTitle: String, bundleMsg: String, hideCancel: Boolean = false, bundle: Bundle? = null): MessageDialogView {
val messageDialogView = MessageDialogView()
messageDialogView.arguments = getBundle(bundleTitle, bundleMsg, bundle, hideCancel, false)
return messageDialogView
}
fun newInstanceForEdit(bundleTitle: String, bundleMsg: String, bundle: Bundle? = null): MessageDialogView {
val messageDialogView = MessageDialogView()
messageDialogView.arguments = getBundle(bundleTitle, bundleMsg, bundle, false, true)
return messageDialogView
}
private fun getBundle(bundleTitle: String, bundleMsg: String, bundle: Bundle?, hideCancel: Boolean, editorMode: Boolean): Bundle {
return Bundler.start()
.put("bundleTitle", bundleTitle)
.put("bundleMsg", bundleMsg)
.put("bundle", bundle)
.put("hideCancel", hideCancel)
.put("editorMode", editorMode)
.end()
}
fun getYesNoBundle(context: Context): Bundle {
return Bundler.start()
.put("primary_extra", context.getString(R.string.yes))
.put("secondary_extra", context.getString(R.string.no))
.end()
}
}
} | gpl-3.0 | a15bee5cf240b5c44dcd0137511a60bf | 28.8 | 132 | 0.724994 | 3.78088 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-compose-material3/src/main/kotlin/org/ccci/gto/android/common/androidx/compose/material3/ui/tabs/PagerTabIndicatorOffsetModifier.kt | 1 | 2454 | package org.ccci.gto.android.common.androidx.compose.material3.ui.tabs
import androidx.compose.material3.TabPosition
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.lerp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.PagerState
/**
* Copied from https://github.com/google/accompanist/blob/main/pager-indicators/src/main/java/com/google/accompanist/pager/PagerTab.kt
* and updated to support material3 TabRow
*/
@ExperimentalPagerApi
fun Modifier.pagerTabIndicatorOffset(
pagerState: PagerState,
tabPositions: List<TabPosition>,
pageIndexMapping: (Int) -> Int = { it },
): Modifier = layout { measurable, constraints ->
if (tabPositions.isEmpty()) {
// If there are no pages, nothing to show
layout(constraints.maxWidth, 0) {}
} else {
val currentPage = minOf(tabPositions.lastIndex, pageIndexMapping(pagerState.currentPage))
val currentTab = tabPositions[currentPage]
val previousTab = tabPositions.getOrNull(currentPage - 1)
val nextTab = tabPositions.getOrNull(currentPage + 1)
val fraction = pagerState.currentPageOffset
val indicatorWidth = if (fraction > 0 && nextTab != null) {
lerp(currentTab.width, nextTab.width, fraction).roundToPx()
} else if (fraction < 0 && previousTab != null) {
lerp(currentTab.width, previousTab.width, -fraction).roundToPx()
} else {
currentTab.width.roundToPx()
}
val indicatorOffset = if (fraction > 0 && nextTab != null) {
lerp(currentTab.left, nextTab.left, fraction).roundToPx()
} else if (fraction < 0 && previousTab != null) {
lerp(currentTab.left, previousTab.left, -fraction).roundToPx()
} else {
currentTab.left.roundToPx()
}
val placeable = measurable.measure(
Constraints(
minWidth = indicatorWidth,
maxWidth = indicatorWidth,
minHeight = 0,
maxHeight = constraints.maxHeight
)
)
layout(constraints.maxWidth, maxOf(placeable.height, constraints.minHeight)) {
placeable.placeRelative(
indicatorOffset,
maxOf(constraints.minHeight - placeable.height, 0)
)
}
}
}
| mit | ec74497ba7bddb95b43eb054c95c7c95 | 40.59322 | 134 | 0.656072 | 4.502752 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/controller/rest/InfoSourceRestController.kt | 1 | 5260 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Rest controller responsible for handling info sources.
*/
package dk.etiktak.backend.controller.rest
import dk.etiktak.backend.controller.rest.json.add
import dk.etiktak.backend.model.contribution.TrustVote
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.security.CurrentlyLoggedClient
import dk.etiktak.backend.service.client.ClientService
import dk.etiktak.backend.service.infosource.InfoSourceService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
@RestController
@RequestMapping("/service/infosource")
class InfoSourceRestController @Autowired constructor(
private val infoSourceService: InfoSourceService,
private val clientService: ClientService) : BaseRestController() {
@RequestMapping(value = "/create/", method = arrayOf(RequestMethod.POST))
fun createInfoSource(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam domainList: List<String>,
@RequestParam(required = false) name: String?): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val infoSource = infoSourceService.createInfoSource(client, domainList, name)
return okMap().add(infoSource, client, infoSourceService)
}
@RequestMapping(value = "/", method = arrayOf(RequestMethod.POST))
fun getInfoSourceReference(
@CurrentlyLoggedClient loggedClient: Client?,
@RequestParam(required = false) url: String?,
@RequestParam(required = false) uuid: String?): HashMap<String, Any> {
val client = if (loggedClient!= null) clientService.getByUuid(loggedClient.uuid) else null
url?.let {
val infoSource = infoSourceService.getInfoSourceByUrl(url) ?: return notFoundMap("Info source")
return okMap().add(infoSource, client, infoSourceService)
}
uuid?.let {
val infoSource = infoSourceService.getInfoSourceByUuid(uuid) ?: return notFoundMap("Info source")
return okMap().add(infoSource, client, infoSourceService)
}
return notFoundMap("Info source")
}
@RequestMapping(value = "/edit/", method = arrayOf(RequestMethod.POST))
fun editInfoSource(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam infoSourceUuid: String,
@RequestParam(required = false) name: String?): HashMap<String, Any> {
var client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
var infoSource = infoSourceService.getInfoSourceByUuid(infoSourceUuid) ?: return notFoundMap("Info source")
name?.let {
infoSourceService.editInfoSourceName(client, infoSource, name,
modifyValues = {modifiedClient, modifiedInfoSource -> client = modifiedClient; infoSource = modifiedInfoSource})
}
return okMap().add(infoSource, client, infoSourceService)
}
@RequestMapping(value = "/trust/name/", method = arrayOf(RequestMethod.POST))
fun trustVoteInfoSourceName(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam infoSourceUuid: String,
@RequestParam vote: TrustVote.TrustVoteType): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val infoSource = infoSourceService.getInfoSourceByUuid(infoSourceUuid) ?: return notFoundMap("Info source")
infoSourceService.trustVoteInfoSourceName(client, infoSource, vote)
return okMap().add(infoSource, client, infoSourceService)
}
} | bsd-3-clause | c9372f787e66dc3af24caa294bf95ad0 | 45.973214 | 132 | 0.728517 | 4.79927 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/equipment/EquipmentOverviewView.kt | 1 | 2448 | package com.habitrpg.android.habitica.ui.views.equipment
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.EquipmentOverviewViewBinding
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.extensions.setScaledPadding
import com.habitrpg.android.habitica.models.user.Outfit
class EquipmentOverviewView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var onNavigate: ((String, String) -> Unit)? = null
private var binding: EquipmentOverviewViewBinding = EquipmentOverviewViewBinding.inflate(context.layoutInflater, this)
init {
background = ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_gray_50)
setScaledPadding(context, 12, 12, 12, 12)
orientation = VERTICAL
binding.weaponItem.setOnClickListener { onNavigate?.invoke("weapon", binding.weaponItem.identifier) }
binding.shieldItem.setOnClickListener { onNavigate?.invoke("shield", binding.shieldItem.identifier) }
binding.headItem.setOnClickListener { onNavigate?.invoke("head", binding.headItem.identifier) }
binding.armorItem.setOnClickListener { onNavigate?.invoke("armor", binding.armorItem.identifier) }
binding.headAccessoryItem.setOnClickListener { onNavigate?.invoke("headAccessory", binding.headAccessoryItem.identifier) }
binding.bodyItem.setOnClickListener { onNavigate?.invoke("body", binding.bodyItem.identifier) }
binding.backItem.setOnClickListener { onNavigate?.invoke("back", binding.backItem.identifier) }
binding.eyewearItem.setOnClickListener { onNavigate?.invoke("eyewear", binding.eyewearItem.identifier) }
}
fun updateData(outfit: Outfit?, isWeaponTwoHanded: Boolean = false) {
binding.weaponItem.set(outfit?.weapon, isWeaponTwoHanded)
binding.shieldItem.set(outfit?.shield, false, isWeaponTwoHanded)
binding.headItem.set(outfit?.head)
binding.armorItem.set(outfit?.armor)
binding.headAccessoryItem.set(outfit?.headAccessory)
binding.bodyItem.set(outfit?.body)
binding.backItem.set(outfit?.back)
binding.eyewearItem.set(outfit?.eyeWear)
}
}
| gpl-3.0 | 1756b0be4a0a652b8aea6955a2a1025b | 51.085106 | 130 | 0.761438 | 4.27972 | false | false | false | false |
robfletcher/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/metrics/ZombieExecutionCheckingAgent.kt | 3 | 3478 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.metrics
import com.netflix.spectator.api.BasicTag
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.Tag
import com.netflix.spinnaker.orca.notifications.AbstractPollingNotificationAgent
import com.netflix.spinnaker.orca.notifications.NotificationClusterLock
import com.netflix.spinnaker.orca.q.ZombieExecutionService
import com.netflix.spinnaker.q.metrics.MonitorableQueue
import java.time.Clock
import java.time.Duration
import net.logstash.logback.argument.StructuredArguments.kv
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.stereotype.Component
/**
* Monitors a queue and generates Atlas metrics.
*/
@Component
@ConditionalOnExpression(
"\${queue.zombie-check.enabled:false}"
)
@ConditionalOnBean(MonitorableQueue::class)
class ZombieExecutionCheckingAgent(
private val zombieExecutionService: ZombieExecutionService,
private val registry: Registry,
private val clock: Clock,
conch: NotificationClusterLock,
@Value("\${queue.zombie-check.interval-ms:3600000}") private val pollingIntervalMs: Long,
@Value("\${queue.zombie-check.enabled:false}") private val zombieCheckEnabled: Boolean,
@Value("\${queue.zombie-check.cutoff-minutes:10}") private val zombieCheckCutoffMinutes: Long,
@Value("\${keiko.queue.enabled:true}") private val queueEnabled: Boolean
) : AbstractPollingNotificationAgent(conch) {
private val log = LoggerFactory.getLogger(javaClass)
override fun getPollingInterval() = pollingIntervalMs
override fun getNotificationType() = javaClass.getSimpleName()
override fun tick() {
checkForZombies()
}
fun checkForZombies() {
if (!queueEnabled) {
return
}
if (!zombieCheckEnabled) {
log.info("Not running zombie check: checkEnabled: $zombieCheckEnabled")
return
}
try {
MDC.put(AGENT_MDC_KEY, this.javaClass.simpleName)
val startedAt = clock.instant()
val zombies = zombieExecutionService.findAllZombies(Duration.ofMinutes(zombieCheckCutoffMinutes))
log.info("Completed zombie check in ${Duration.between(startedAt, clock.instant())}")
zombies.forEach {
log.error(
"Found zombie {} {} {} {}",
kv("executionType", it.type),
kv("application", it.application),
kv("executionName", it.name),
kv("executionId", it.id)
)
val tags = mutableListOf<Tag>(
BasicTag("application", it.application),
BasicTag("type", it.type.name)
)
registry.counter("queue.zombies", tags).increment()
}
} finally {
MDC.remove(AGENT_MDC_KEY)
}
}
}
| apache-2.0 | 17ccb8c683403e221144782a757aa0b8 | 34.489796 | 103 | 0.738068 | 4.17527 | false | false | false | false |
robfletcher/orca | keiko-test-common/src/main/kotlin/com/netflix/spinnaker/time/MutableClock.kt | 5 | 1170 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.time
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.time.temporal.TemporalAmount
class MutableClock(
private var instant: Instant = Instant.now(),
private val zone: ZoneId = ZoneId.systemDefault()
) : Clock() {
override fun withZone(zone: ZoneId) = MutableClock(instant, zone)
override fun getZone() = zone
override fun instant() = instant
fun incrementBy(amount: TemporalAmount) {
instant = instant.plus(amount)
}
fun instant(newInstant: Instant) {
instant = newInstant
}
}
| apache-2.0 | 1321837886f864be7c4c08973e529e49 | 26.857143 | 75 | 0.735897 | 4.034483 | false | false | false | false |
Obaied/Dinger-kotlin | app/src/main/java/com/obaied/sohan/data/DataManager.kt | 1 | 1984 | package com.joseph.sohan.data
import com.joseph.sohan.data.local.DatabaseHelper
import com.joseph.sohan.data.model.Quote
import com.joseph.sohan.data.remote.QuoteService
import com.joseph.sohan.data.remote.ServicesHelper
import io.reactivex.Observable
import io.reactivex.Single
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by ab on 02/04/2017.
*/
@Singleton
class DataManager
@Inject constructor(val quoteService: QuoteService,
val databaseHelper: DatabaseHelper,
val servicesHelper: ServicesHelper) {
private val random = Random()
fun fetchQuotesFromDb(): Observable<List<Quote>> {
return databaseHelper.fetchQuotesFromDb()
}
fun fetchQuotesFromApi(limit: Int): Observable<List<Quote>> {
val listOfSingleQuotes: List<Single<Quote>> = servicesHelper.getListOfQuotes(limit)
val observable: Observable<List<Quote>> = Observable.create<List<Quote>> {
val allQuotes = listOfSingleQuotes
.map {
it
.onErrorReturn {
Quote("", "")
}
.blockingGet()
}
.toMutableList()
.filter { !it.author.isEmpty() || !it.text.isEmpty() }
if (allQuotes.isEmpty()) {
it.onError(Throwable())
}
//Assign a random tag for each image
//PS: This is hardcoded to Unsplash.it's current number of images (1050)
// for (quote in allQuotes) {
// quote.imageTag = random.nextInt(1050).toString()
// }
it.onNext(allQuotes)
it.onComplete()
}
return observable
}
fun setQuotesToDb(quotes: Collection<Quote>): Observable<Quote> {
return databaseHelper.setQuotesToDb(quotes)
}
} | mit | cdfb9ee358ef6bf65af2c99aa2b54a17 | 31.016129 | 91 | 0.579133 | 4.603248 | false | false | false | false |
jayrave/moshi-pristine-models | src/main/kotlin/com/jayrave/moshi/pristineModels/Mapper.kt | 1 | 4033 | package com.jayrave.moshi.pristineModels
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
abstract class Mapper<T : Any> {
private var jsonAdapter: JsonAdapter<T>? = null
private val jsonAdapterBuilt = AtomicBoolean(false)
private val fieldMappings = LinkedHashMap<String, FieldMappingImpl<T, *>>()
/**
* @param [name] of the JSON field
* @param [valueCanBeNull] whether this property & JSON can be null
* @param [propertyExtractor] to extract the property ([F]) from an instance of [T]
* @param [jsonAdapter] to be used to map this property from/to JSON. If `null`, whatever
* [Moshi] provides is used
*/
fun <F> field(
name: String, valueCanBeNull: Boolean, propertyExtractor: PropertyExtractor<T, F>,
jsonAdapter: JsonAdapter<F>? = null): FieldMapping<T, F> {
return when (jsonAdapterBuilt.get()) {
true -> throw IllegalStateException("Trying to add a field mapping too late")
else -> {
val fieldMapping = FieldMappingImpl(
name, valueCanBeNull, propertyExtractor, jsonAdapter
)
fieldMappings.put(name, fieldMapping)
fieldMapping
}
}
}
internal fun getJsonAdapter(moshi: Moshi): JsonAdapter<T> {
synchronized(jsonAdapterBuilt) { // Use flag to not have a separate lock object
// Do the following only if it hasn't been already done
if (jsonAdapterBuilt.compareAndSet(false, true)) {
// Let all the field mappings acquire the adapter they need
fieldMappings.values.forEach { it.acquireJsonAdapterIfRequired(moshi) }
// Build the adapter this mapper needs (make it null safe too)
jsonAdapter = JsonAdapterForMapper().nullSafe()
}
}
return jsonAdapter!!
}
/**
* @return A object representing a single JSON object this class deals with.
* The values should be extracted out of the passed in [Value] instance
*/
abstract fun create(value: Value<T>): T
private inner class JsonAdapterForMapper : JsonAdapter<T>() {
override fun fromJson(reader: JsonReader): T {
// Clear cached values in field mappings
fieldMappings.values.forEach { it.clearLastReadValueInCurrentThread() }
// Start object
reader.beginObject()
// Extract all the possible field values
while (reader.hasNext()) {
val fieldName = reader.nextName()
val fieldMapping = fieldMappings[fieldName]
when (fieldMapping) {
null -> reader.skipValue()
else -> fieldMapping.read(reader)
}
}
// End object
reader.endObject()
// Build & return object
return create(object : Value<T> {
override fun <F> of(fieldMapping: FieldMapping<T, F>): F {
return when (fieldMapping) {
is FieldMappingImpl -> fieldMapping.lastReadValueInCurrentThread()
else -> throw IllegalArgumentException(
"Pass in ${FieldMapping::class.java.canonicalName} " +
"built by calling Mapper#field"
)
}
}
})
}
override fun toJson(writer: JsonWriter, value: T) {
// Start object
writer.beginObject()
// Write each field
fieldMappings.values.forEach {
writer.name(it.name)
it.write(writer, value)
}
// End object
writer.endObject()
}
}
} | apache-2.0 | a858b97b6d52ef3a53e31fa1e534907c | 33.478632 | 94 | 0.571783 | 5.124524 | false | false | false | false |
k0kubun/githubranking | worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/db/RepositoryQuery.kt | 1 | 4512 | package com.github.k0kubun.gitstar_ranking.db
import com.github.k0kubun.gitstar_ranking.core.Repository
import com.github.k0kubun.gitstar_ranking.core.StarsCursor
import com.github.k0kubun.gitstar_ranking.core.table
import java.sql.Timestamp
import org.jooq.DSLContext
import org.jooq.Record
import org.jooq.RecordMapper
import org.jooq.impl.DSL.field
import org.jooq.impl.DSL.now
class RepositoryQuery(private val database: DSLContext) {
private val repositoryColumns = listOf(
field("id"),
field("full_name"),
field("stargazers_count"),
)
private val repositoryMapper = RecordMapper<Record, Repository> { record ->
Repository(
id = record.get("id", Long::class.java),
fullName = record.get("full_name", String::class.java),
stargazersCount = record.get("stargazers_count", Long::class.java),
)
}
fun insertAll(allRepos: List<Repository>) {
allRepos.chunked(100).forEach { repos ->
database
.insertInto(table("repositories", primaryKey = "id"))
.columns(
field("id"),
field("owner_id"),
field("name"),
field("full_name"),
field("description"),
field("fork"),
field("homepage"),
field("stargazers_count"),
field("language"),
field("created_at"),
field("updated_at"),
field("fetched_at"),
)
.let {
repos.fold(it) { query, repo ->
query.values(
repo.id,
repo.ownerId,
repo.name,
repo.fullName,
repo.description,
repo.fork,
repo.homepage,
repo.stargazersCount,
repo.language,
now(), // created_at
now(), // updated_at
now(), // fetched_at
)
}
}
.onDuplicateKeyUpdate()
.set(field("owner_id", Long::class.java), field("excluded.owner_id", Long::class.java))
.set(field("name", String::class.java), field("excluded.name", String::class.java))
.set(field("full_name", String::class.java), field("excluded.full_name", String::class.java))
.set(field("description", String::class.java), field("excluded.description", String::class.java))
.set(field("fork", Boolean::class.java), field("excluded.fork", Boolean::class.java))
.set(field("homepage", String::class.java), field("excluded.homepage", String::class.java))
.set(field("stargazers_count", Long::class.java), field("excluded.stargazers_count", Long::class.java))
.set(field("language", String::class.java), field("excluded.language", String::class.java))
.set(field("updated_at", Timestamp::class.java), field("excluded.updated_at", Timestamp::class.java))
.set(field("fetched_at", Timestamp::class.java), field("excluded.fetched_at", Timestamp::class.java))
.execute()
}
}
fun deleteAll(ownerId: Long) {
database
.delete(table("repositories"))
.where(field("owner_id").eq(ownerId))
.execute()
}
fun count(stars: Long? = null): Long {
return database
.selectCount()
.from("repositories")
.run {
if (stars != null) {
where("stargazers_count = ?", stars)
} else this
}
.fetchOne(0, Long::class.java)!!
}
fun orderByStarsDesc(limit: Int, after: StarsCursor? = null): List<Repository> {
return database
.select(repositoryColumns)
.from("repositories")
.run {
if (after != null) {
where("(stargazers_count, id) < (?, ?)", after.stars, after.id)
} else this
}
.orderBy(field("stargazers_count").desc(), field("id").desc())
.limit(limit)
.fetch(repositoryMapper)
}
}
| mit | 07e7978375798277d64e9fc106fec7bc | 39.648649 | 119 | 0.499778 | 4.719665 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/PaymentMethodCreateParamsFactory.kt | 2 | 16148 | package abi43_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk
import abi43_0_0.com.facebook.react.bridge.ReadableMap
import com.stripe.android.model.*
class PaymentMethodCreateParamsFactory(
private val clientSecret: String,
private val params: ReadableMap,
private val cardFieldView: StripeSdkCardView?,
private val cardFormView: CardFormView?,
) {
private val billingDetailsParams = mapToBillingDetails(getMapOrNull(params, "billingDetails"), cardFieldView?.cardAddress ?: cardFormView?.cardAddress)
@Throws(PaymentMethodCreateParamsException::class)
fun createConfirmParams(paymentMethodType: PaymentMethod.Type): ConfirmPaymentIntentParams {
try {
return when (paymentMethodType) {
PaymentMethod.Type.Card -> createCardPaymentConfirmParams()
PaymentMethod.Type.Ideal -> createIDEALPaymentConfirmParams()
PaymentMethod.Type.Alipay -> createAlipayPaymentConfirmParams()
PaymentMethod.Type.Sofort -> createSofortPaymentConfirmParams()
PaymentMethod.Type.Bancontact -> createBancontactPaymentConfirmParams()
PaymentMethod.Type.SepaDebit -> createSepaPaymentConfirmParams()
PaymentMethod.Type.Oxxo -> createOXXOPaymentConfirmParams()
PaymentMethod.Type.Giropay -> createGiropayPaymentConfirmParams()
PaymentMethod.Type.Eps -> createEPSPaymentConfirmParams()
PaymentMethod.Type.GrabPay -> createGrabPayPaymentConfirmParams()
PaymentMethod.Type.P24 -> createP24PaymentConfirmParams()
PaymentMethod.Type.Fpx -> createFpxPaymentConfirmParams()
PaymentMethod.Type.AfterpayClearpay -> createAfterpayClearpayPaymentConfirmParams()
PaymentMethod.Type.AuBecsDebit -> createAuBecsDebitPaymentConfirmParams()
else -> {
throw Exception("This paymentMethodType is not supported yet")
}
}
} catch (error: PaymentMethodCreateParamsException) {
throw error
}
}
@Throws(PaymentMethodCreateParamsException::class)
fun createSetupParams(paymentMethodType: PaymentMethod.Type): ConfirmSetupIntentParams {
try {
return when (paymentMethodType) {
PaymentMethod.Type.Card -> createCardPaymentSetupParams()
PaymentMethod.Type.Ideal -> createIDEALPaymentSetupParams()
PaymentMethod.Type.Sofort -> createSofortPaymentSetupParams()
PaymentMethod.Type.Bancontact -> createBancontactPaymentSetupParams()
PaymentMethod.Type.SepaDebit -> createSepaPaymentSetupParams()
PaymentMethod.Type.AuBecsDebit -> createAuBecsDebitPaymentSetupParams()
else -> {
throw Exception("This paymentMethodType is not supported yet")
}
}
} catch (error: PaymentMethodCreateParamsException) {
throw error
}
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createIDEALPaymentConfirmParams(): ConfirmPaymentIntentParams {
val bankName = getValOr(params, "bankName", null)
val idealParams = PaymentMethodCreateParams.Ideal(bankName)
val createParams =
PaymentMethodCreateParams.create(ideal = idealParams, billingDetails = billingDetailsParams)
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = createParams,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createP24PaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createP24(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createCardPaymentConfirmParams(): ConfirmPaymentIntentParams {
val paymentMethodId = getValOr(params, "paymentMethodId", null)
val token = getValOr(params, "token", null)
val cardParams = cardFieldView?.cardParams ?: cardFormView?.cardParams
if (cardParams == null && paymentMethodId == null && token == null) {
throw PaymentMethodCreateParamsException("Card details not complete")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
if (paymentMethodId != null) {
val cvc = getValOr(params, "cvc", null)
val paymentMethodOptionParams =
if (cvc != null) PaymentMethodOptionsParams.Card(cvc) else null
return ConfirmPaymentIntentParams.createWithPaymentMethodId(
paymentMethodId = paymentMethodId,
paymentMethodOptions = paymentMethodOptionParams,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
} else {
var card = cardParams
if (token != null) {
card = PaymentMethodCreateParams.Card.create(token)
}
val paymentMethodCreateParams = PaymentMethodCreateParams.create(card!!, billingDetailsParams)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = paymentMethodCreateParams,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createIDEALPaymentSetupParams(): ConfirmSetupIntentParams {
val bankName = getValOr(params, "bankName", null)
val idealParams = PaymentMethodCreateParams.Ideal(bankName)
val createParams =
PaymentMethodCreateParams.create(ideal = idealParams, billingDetails = billingDetailsParams)
return ConfirmSetupIntentParams.create(
paymentMethodCreateParams = createParams,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSepaPaymentSetupParams(): ConfirmSetupIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val iban = getValOr(params, "iban", null)?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide IBAN")
}
val sepaParams = PaymentMethodCreateParams.SepaDebit(iban)
val createParams =
PaymentMethodCreateParams.create(sepaDebit = sepaParams, billingDetails = billingDetails)
return ConfirmSetupIntentParams.create(
paymentMethodCreateParams = createParams,
clientSecret = clientSecret
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createCardPaymentSetupParams(): ConfirmSetupIntentParams {
val cardParams = cardFieldView?.cardParams ?: cardFormView?.cardParams
?: throw PaymentMethodCreateParamsException("Card details not complete")
val paymentMethodCreateParams =
PaymentMethodCreateParams.create(cardParams, billingDetailsParams)
return ConfirmSetupIntentParams
.create(paymentMethodCreateParams, clientSecret)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAlipayPaymentConfirmParams(): ConfirmPaymentIntentParams {
return ConfirmPaymentIntentParams.createAlipay(clientSecret)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSofortPaymentConfirmParams(): ConfirmPaymentIntentParams {
val country = getValOr(params, "country", null)?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide bank account country")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
val params = PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Sofort(country = country),
billingDetailsParams
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSofortPaymentSetupParams(): ConfirmSetupIntentParams {
val country = getValOr(params, "country", null)
?: throw PaymentMethodCreateParamsException("You must provide country")
val params = PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Sofort(country = country),
billingDetailsParams
)
return ConfirmSetupIntentParams.create(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createGrabPayPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams ?: PaymentMethod.BillingDetails()
val params = PaymentMethodCreateParams.createGrabPay(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createBancontactPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
val params = PaymentMethodCreateParams.createBancontact(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
private fun createBancontactPaymentSetupParams(): ConfirmSetupIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createBancontact(billingDetails)
return ConfirmSetupIntentParams
.create(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createOXXOPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createOxxo(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createEPSPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createEps(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createGiropayPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createGiropay(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSepaPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val iban = getValOr(params, "iban", null)?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide IBAN")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
val params = PaymentMethodCreateParams.create(
sepaDebit = PaymentMethodCreateParams.SepaDebit(iban),
billingDetails = billingDetails
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createFpxPaymentConfirmParams(): ConfirmPaymentIntentParams {
val bank = getBooleanOrFalse(params, "testOfflineBank").let { "test_offline_bank" }
val params = PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Fpx(bank)
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAfterpayClearpayPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createAfterpayClearpay(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAuBecsDebitPaymentConfirmParams(): ConfirmPaymentIntentParams {
val formDetails = getMapOrNull(params, "formDetails")?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide form details")
}
val bsbNumber = getValOr(formDetails, "bsbNumber") as String
val accountNumber = getValOr(formDetails, "accountNumber") as String
val name = getValOr(formDetails, "name") as String
val email = getValOr(formDetails, "email") as String
val billingDetails = PaymentMethod.BillingDetails.Builder()
.setName(name)
.setEmail(email)
.build()
val params = PaymentMethodCreateParams.create(
auBecsDebit = PaymentMethodCreateParams.AuBecsDebit(
bsbNumber = bsbNumber,
accountNumber = accountNumber
),
billingDetails = billingDetails
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAuBecsDebitPaymentSetupParams(): ConfirmSetupIntentParams {
val formDetails = getMapOrNull(params, "formDetails")?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide form details")
}
val bsbNumber = getValOr(formDetails, "bsbNumber") as String
val accountNumber = getValOr(formDetails, "accountNumber") as String
val name = getValOr(formDetails, "name") as String
val email = getValOr(formDetails, "email") as String
val billingDetails = PaymentMethod.BillingDetails.Builder()
.setName(name)
.setEmail(email)
.build()
val params = PaymentMethodCreateParams.create(
auBecsDebit = PaymentMethodCreateParams.AuBecsDebit(
bsbNumber = bsbNumber,
accountNumber = accountNumber
),
billingDetails = billingDetails
)
return ConfirmSetupIntentParams
.create(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
}
class PaymentMethodCreateParamsException(message: String) : Exception(message)
| bsd-3-clause | 656cff8a0bf677c42cf16574a8be7530 | 37.447619 | 153 | 0.745603 | 5.552957 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl-plugins/src/integTest/kotlin/org/gradle/kotlin/dsl/plugins/precompiled/PrecompiledScriptPluginTemplatesTest.kt | 3 | 19989 | package org.gradle.kotlin.dsl.plugins.precompiled
import com.nhaarman.mockito_kotlin.KStubbing
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doAnswer
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.same
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import org.gradle.api.plugins.Convention
import org.gradle.api.plugins.ObjectConfigurationAction
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.fixtures.FoldersDslExpression
import org.gradle.kotlin.dsl.fixtures.assertFailsWith
import org.gradle.kotlin.dsl.fixtures.assertInstanceOf
import org.gradle.kotlin.dsl.fixtures.assertStandardOutputOf
import org.gradle.kotlin.dsl.fixtures.withFolders
import org.gradle.kotlin.dsl.precompile.v1.PrecompiledInitScript
import org.gradle.kotlin.dsl.precompile.v1.PrecompiledProjectScript
import org.gradle.kotlin.dsl.precompile.v1.PrecompiledSettingsScript
import org.gradle.test.fixtures.file.LeaksFileHandles
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.jetbrains.kotlin.name.NameUtils
import org.junit.Test
import org.mockito.invocation.InvocationOnMock
import java.io.File
@LeaksFileHandles("Kotlin Compiler Daemon working directory")
class PrecompiledScriptPluginTemplatesTest : AbstractPrecompiledScriptPluginTest() {
@Test
fun `Project scripts from regular source-sets are compiled via the PrecompiledProjectScript template`() {
givenPrecompiledKotlinScript(
"my-project-script.gradle.kts",
"""
task("my-task")
"""
)
val task = mock<Task>()
val project = mock<Project> {
on { task(any()) } doReturn task
}
assertInstanceOf<PrecompiledProjectScript>(
instantiatePrecompiledScriptOf(
project,
"My_project_script_gradle"
)
)
inOrder(project, task) {
verify(project).task("my-task")
verifyNoMoreInteractions()
}
}
@Test
fun `Settings scripts from regular source-sets are compiled via the PrecompiledSettingsScript template`() {
givenPrecompiledKotlinScript(
"my-settings-script.settings.gradle.kts",
"""
include("my-project")
"""
)
val settings = mock<Settings>()
assertInstanceOf<PrecompiledSettingsScript>(
instantiatePrecompiledScriptOf(
settings,
"My_settings_script_settings_gradle"
)
)
verify(settings).include("my-project")
}
@Test
fun `Gradle scripts from regular source-sets are compiled via the PrecompiledInitScript template`() {
givenPrecompiledKotlinScript(
"my-gradle-script.init.gradle.kts",
"""
useLogger("my-logger")
"""
)
val gradle = mock<Gradle>()
assertInstanceOf<PrecompiledInitScript>(
instantiatePrecompiledScriptOf(
gradle,
"My_gradle_script_init_gradle"
)
)
verify(gradle).useLogger("my-logger")
}
@Test
fun `plugin adapter doesn't mask exceptions thrown by precompiled script`() {
// given:
val expectedMessage = "Not on my watch!"
withKotlinDslPlugin()
withFile(
"src/main/kotlin/my-project-script.gradle.kts",
"""
throw IllegalStateException("$expectedMessage")
"""
)
// when:
compileKotlin()
// then:
@Suppress("unchecked_cast")
val pluginAdapter =
loadCompiledKotlinClass("MyProjectScriptPlugin")
.getConstructor()
.newInstance() as Plugin<Project>
val exception =
assertFailsWith(IllegalStateException::class) {
pluginAdapter.apply(mock())
}
assertThat(
exception.message,
equalTo(expectedMessage)
)
}
@Test
fun `implicit imports are available to precompiled scripts`() {
givenPrecompiledKotlinScript(
"my-project-script.gradle.kts",
"""
task<Jar>("jar")
"""
)
val task = mock<Jar>()
val tasks = mock<TaskContainer> {
on { create(any<String>(), any<Class<Task>>()) } doReturn task
}
val project = mock<Project> {
on { getTasks() } doReturn tasks
}
instantiatePrecompiledScriptOf(
project,
"My_project_script_gradle"
)
verify(tasks).create("jar", Jar::class.java)
}
@Test
fun `precompiled script plugin ids are honored by java-gradle-plugin plugin`() {
projectRoot.withFolders {
"plugin" {
"src/main/kotlin" {
// Plugin id for script with no package declaration is simply
// the file name minus the script file extension.
// Project plugins must be named `*.gradle.kts`
withFile(
"my-plugin.gradle.kts",
"""
println("my-plugin applied!")
"""
)
// Settings plugins must be named `*.settings.gradle.kts`
withFile(
"my-settings-plugin.settings.gradle.kts",
"""
println("my-settings-plugin applied!")
"""
)
// Gradle object plugins, a.k.a., precompiled init script plugins,
// must be named `*.init.gradle.kts`
withFile(
"my-init-plugin.init.gradle.kts",
"""
println("my-init-plugin applied!")
"""
)
// plugin id for script with package declaration is the
// package name dot the file name minus the `.gradle.kts` suffix
withFile(
"org/acme/my-other-plugin.gradle.kts",
"""
package org.acme
println("my-other-plugin applied!")
"""
)
}
withFile("settings.gradle.kts", defaultSettingsScript)
withFile(
"build.gradle.kts",
scriptWithKotlinDslPlugin()
)
}
}
executer.inDirectory(file("plugin")).withTasks("jar").run()
val pluginJar = file("plugin/build/libs/plugin.jar")
assertThat("pluginJar was built", pluginJar.exists())
val movedPluginJar = file("plugin.jar")
pluginJar.renameTo(movedPluginJar)
withSettings(
"""
buildscript {
dependencies {
classpath(files("${movedPluginJar.name}"))
}
}
gradle.apply<MyInitPluginPlugin>()
apply(plugin = "my-settings-plugin")
"""
)
withFile(
"buildSrc/build.gradle",
"""
dependencies {
api files("../${movedPluginJar.name}")
}
"""
)
withBuildScript(
"""
plugins {
id("my-plugin")
id("org.acme.my-other-plugin")
}
"""
)
assertThat(
build("help").output,
allOf(
containsString("my-init-plugin applied!"),
containsString("my-settings-plugin applied!"),
containsString("my-plugin applied!"),
containsString("my-other-plugin applied!")
)
)
}
@Test
fun `precompiled script plugins can be published by maven-publish plugin`() {
val repository = newDir("repository")
publishPluginsTo(repository) {
withFile(
"my-plugin.gradle.kts",
"""
println("my-plugin applied!")
"""
)
withFile(
"org/acme/my-other-plugin.gradle.kts",
"""
package org.acme
println("org.acme.my-other-plugin applied!")
"""
)
withFile(
"org/acme/plugins/my-init.init.gradle.kts",
"""
package org.acme.plugins
println("org.acme.plugins.my-init applied!")
"""
)
}
val repositoriesBlock = repositoriesBlockFor(repository)
withSettings(
"""
pluginManagement {
$repositoriesBlock
}
"""
)
withBuildScript(
"""
plugins {
id("my-plugin") version "1.0"
id("org.acme.my-other-plugin") version "1.0"
}
"""
)
val initScript =
withFile(
"my-init-script.init.gradle.kts",
"""
initscript {
$repositoriesBlock
dependencies {
classpath("org.acme:plugins:1.0")
}
}
apply<org.acme.plugins.MyInitPlugin>()
// TODO: can't apply plugin by id
// apply(plugin = "org.acme.plugins.my-init")
"""
)
assertThat(
build("help", "-I", initScript.canonicalPath).output,
allOf(
containsString("org.acme.plugins.my-init applied!"),
containsString("my-plugin applied!"),
containsString("org.acme.my-other-plugin applied!")
)
)
}
@Test
fun `precompiled script plugins can use Kotlin 1 dot 3 language features`() {
givenPrecompiledKotlinScript(
"my-plugin.gradle.kts",
"""
// Coroutines are no longer experimental
val coroutine = sequence {
// Unsigned integer types
yield(42UL)
}
when (val value = coroutine.first()) {
42UL -> print("42!")
else -> throw IllegalStateException()
}
"""
)
assertStandardOutputOf("42!") {
instantiatePrecompiledScriptOf(
mock<Project>(),
"My_plugin_gradle"
)
}
}
@Test
fun `precompiled project script template honors HasImplicitReceiver`() {
assertHasImplicitReceiverIsHonoredByScriptOf<Project>("my-project-plugin.gradle.kts")
}
@Test
fun `precompiled settings script template honors HasImplicitReceiver`() {
assertHasImplicitReceiverIsHonoredByScriptOf<Settings>("my-settings-plugin.settings.gradle.kts")
}
@Test
fun `precompiled init script template honors HasImplicitReceiver`() {
assertHasImplicitReceiverIsHonoredByScriptOf<Gradle>("my-init-plugin.init.gradle.kts")
}
@Test
fun `precompiled project script receiver is undecorated`() {
assertUndecoratedImplicitReceiverOf<Project>("my-project-plugin.gradle.kts")
}
@Test
fun `precompiled settings script receiver is undecorated`() {
assertUndecoratedImplicitReceiverOf<Settings>("my-settings-plugin.settings.gradle.kts")
}
@Test
fun `precompiled init script receiver is undecorated`() {
assertUndecoratedImplicitReceiverOf<Gradle>("my-init-plugin.init.gradle.kts")
}
@Test
fun `nested plugins block fails to compile with reasonable message`() {
withKotlinDslPlugin()
withPrecompiledKotlinScript(
"my-project-plugin.gradle.kts",
"""
project(":nested") {
plugins {
java
}
}
"""
)
buildAndFail("classes").run {
assertHasDescription(
"Execution failed for task ':compileKotlin'."
)
assertHasErrorOutput(
"""my-project-plugin.gradle.kts: (3, 17): Using 'plugins(PluginDependenciesSpec.() -> Unit): Nothing' is an error. The plugins {} block must not be used here. If you need to apply a plugin imperatively, please use apply<PluginType>() or apply(plugin = "id") instead."""
)
}
}
@Test
fun `can apply plugin using ObjectConfigurationAction syntax`() {
val pluginsRepository = newDir("repository")
publishPluginsTo(pluginsRepository) {
withFile(
"MyInit.init.gradle.kts",
"""
open class GradlePlugin : Plugin<Gradle> {
override fun apply(target: Gradle) = println("Gradle!")
}
apply { plugin<GradlePlugin>() }
"""
)
withFile(
"MySettings.settings.gradle.kts",
"""
open class SettingsPlugin : Plugin<Settings> {
override fun apply(target: Settings) = println("Settings!")
}
gradle.apply { plugin<MyInitPlugin>() }
apply { plugin<SettingsPlugin>() }
"""
)
withFile(
"MyProject.gradle.kts",
"""
open class ProjectPlugin : Plugin<Project> {
override fun apply(target: Project) {
val projectName = target.name
target.task("run") {
doLast { println("Project " + projectName + "!") }
}
}
}
apply { plugin<ProjectPlugin>() }
subprojects {
apply { plugin<ProjectPlugin>() }
}
"""
)
}
val pluginRepositoriesBlock = repositoriesBlockFor(pluginsRepository)
withSettings(
"""
pluginManagement {
$pluginRepositoriesBlock
}
plugins {
id("MySettings") version "1.0"
}
rootProject.name = "foo"
include("bar")
"""
)
withBuildScript(
"""
plugins { id("MyProject") }
"""
)
assertThat(
build("run", "-q").output,
allOf(
containsString("Gradle!"),
containsString("Settings!"),
containsString("Project foo!"),
containsString("Project bar!")
)
)
}
@Test
fun `can use PluginAware extensions against nested receiver`() {
val scriptFileName = "my-project-plugin.gradle.kts"
givenPrecompiledKotlinScript(
scriptFileName,
"""
project(":nested") {
apply(from = "./gradle/conventions.gradle.kts")
}
"""
)
val configurationAction = mock<ObjectConfigurationAction>()
val nestedReceiver = mock<Project> {
on { apply(any<Action<ObjectConfigurationAction>>()) } doAnswer {
it.executeActionArgument(0, configurationAction)
Unit
}
}
val project = mock<Project> {
onProject(":nested", nestedReceiver)
}
instantiatePrecompiledScriptOf(
project,
scriptClassNameForFile(scriptFileName)
)
inOrder(configurationAction) {
verify(configurationAction).from("./gradle/conventions.gradle.kts")
verifyNoMoreInteractions()
}
}
private
fun KStubbing<Project>.onProject(path: String, project: Project) {
on { project(eq(path), any<Action<Project>>()) } doAnswer {
it.executeActionArgument(1, project)
project
}
}
private
fun <T : Any> InvocationOnMock.executeActionArgument(index: Int, configurationAction: T) {
getArgument<Action<T>>(index).execute(configurationAction)
}
@Suppress("deprecation")
private
inline fun <reified T : Any> assertUndecoratedImplicitReceiverOf(fileName: String) {
givenPrecompiledKotlinScript(
fileName,
"""
val ${T::class.simpleName}.receiver get() = this
(receiver as ${org.gradle.api.internal.HasConvention::class.qualifiedName}).convention.add("receiver", receiver)
"""
)
val convention = mock<Convention>()
val receiver = mock<org.gradle.api.internal.HasConvention>(extraInterfaces = arrayOf(T::class)) {
on { getConvention() } doReturn convention
}
instantiatePrecompiledScriptOf(
receiver as T,
scriptClassNameForFile(fileName)
)
verify(convention).add(
eq("receiver"),
same(receiver)
)
}
private
inline fun <reified T : Any> assertHasImplicitReceiverIsHonoredByScriptOf(fileName: String) {
// Action<T> <=> T.() -> Unit because HasImplicitReceiver
givenPrecompiledKotlinScript(
fileName,
"""
fun <T> applyActionTo(a: T, action: ${Action::class.qualifiedName}<T>) = action(a)
object receiver
applyActionTo(receiver) {
require(this === receiver)
print("42!")
}
"""
)
assertStandardOutputOf("42!") {
instantiatePrecompiledScriptOf(
mock<T>(),
scriptClassNameForFile(fileName)
)
}
}
private
fun repositoriesBlockFor(repository: File): String = """
repositories {
maven { url = uri("${repository.toURI()}") }
}
"""
private
fun publishPluginsTo(
repository: File,
group: String = "org.acme",
version: String = "1.0",
sourceFiles: FoldersDslExpression
) {
withFolders {
"plugins" {
"src/main/kotlin" {
sourceFiles()
}
withFile("settings.gradle.kts", defaultSettingsScript)
withFile(
"build.gradle.kts",
"""
plugins {
`kotlin-dsl`
`maven-publish`
}
group = "$group"
version = "$version"
$repositoriesBlock
publishing {
${repositoriesBlockFor(repository)}
}
"""
)
}
}
build(
existing("plugins"),
"publish"
)
}
private
fun scriptClassNameForFile(fileName: String) =
NameUtils.getScriptNameForFile(fileName).asString()
}
| apache-2.0 | 7b639a3950d9cf0f8f58b686344e610b | 26.685596 | 285 | 0.519986 | 5.296502 | false | false | false | false |
yeoupooh/WoLa | src/test/kotlin/com/subakstudio/wifi/WiFiTest.kt | 1 | 2606 | package com.subakstudio.wifi
import com.subakstudio.util.RedirectIO
import org.junit.Assert.assertNotNull
import org.junit.Ignore
import org.junit.Test
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
/**
* Created by yeoupooh on 4/11/16.
*/
public class WiFiTest {
// Macosx
// http://www.infoworld.com/article/2614879/mac-os-x/mac-os-x-top-20-os-x-command-line-secrets-for-power-users.html
// http://osxdaily.com/2007/01/18/airport-the-little-known-command-line-wireless-utility/http://osxdaily.com/2007/01/18/airport-the-little-known-command-line-wireless-utility/
@Ignore
@Test fun testOnMacosx() {
var p = ProcessBuilder().command("/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport", "-s").start()
RedirectIO.redirect(p.inputStream, System.out)
RedirectIO.redirect(p.errorStream, System.out)
// inheritIO(p.inputStream, System.out)
// inheritIO(p.errorStream, System.err)
p.waitFor()
}
@Ignore
@Test fun testUpdateSignalOnMacOSX() {
var wifi = WifiMacOSX()
var aps = wifi.updateSignals()
assertNotNull(aps)
for (ap in aps) {
println("ap=[$ap]")
}
}
// Windows
// http://stackoverflow.com/questions/5378103/finding-ssid-of-a-wireless-network-with-java
@Ignore
@Test fun testOnWindows() {
var ssids = ArrayList<String>()
var signals = ArrayList<String>()
var builder = ProcessBuilder(
"cmd.exe", "/c", "netsh wlan show all")
builder.redirectErrorStream(true)
var p = builder.start()
var r = BufferedReader(InputStreamReader(p.getInputStream()))
var line: String?
while (true) {
line = r.readLine();
if (line.contains("SSID") || line.contains("Signal")) {
if (!line.contains("BSSID"))
if (line.contains("SSID") && !line.contains("name") && !line.contains("SSIDs")) {
line = line.substring(8)
ssids.add(line)
}
if (line?.contains("Signal")!!) {
line = line?.substring(30)
signals.add(line!!)
}
if (signals.size == 7) {
break
}
}
}
for ((i, value) in ssids.withIndex()) {
System.out.println("SSID name == " + ssids.get(i) + " and its signal == " + signals.get(i))
}
}
}
| gpl-3.0 | 4443474dc11e1f3e0b993c9512c96c03 | 33.289474 | 179 | 0.572909 | 3.85503 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/LineChartAccessibilityHelper.kt | 1 | 3103 | package org.wordpress.android.ui.stats.refresh.utils
import android.graphics.Rect
import android.graphics.RectF
import android.os.Bundle
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat
import androidx.customview.widget.ExploreByTouchHelper
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.YAxis.AxisDependency
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
class LineChartAccessibilityHelper(
private val lineChart: LineChart,
private val contentDescriptions: List<String>,
private val accessibilityEvent: LineChartAccessibilityEvent
) : ExploreByTouchHelper(lineChart) {
private val dataSet: ILineDataSet = lineChart.data.dataSets.first()
interface LineChartAccessibilityEvent {
fun onHighlight(entry: Entry, index: Int)
}
init {
lineChart.setOnHoverListener { _, event -> dispatchHoverEvent(event) }
}
override fun getVirtualViewAt(x: Float, y: Float): Int {
val entry = lineChart.getEntryByTouchPoint(x, y)
return when {
entry != null -> {
dataSet.getEntryIndex(entry as Entry?)
}
else -> {
INVALID_ID
}
}
}
override fun getVisibleVirtualViews(virtualViewIds: MutableList<Int>?) {
for (i in 0 until dataSet.entryCount) {
virtualViewIds?.add(i)
}
}
override fun onPerformActionForVirtualView(
virtualViewId: Int,
action: Int,
arguments: Bundle?
): Boolean {
when (action) {
AccessibilityNodeInfoCompat.ACTION_CLICK -> {
val entry = dataSet.getEntryForIndex(virtualViewId)
accessibilityEvent.onHighlight(entry, virtualViewId)
return true
}
}
return false
}
@Suppress("DEPRECATION")
override fun onPopulateNodeForVirtualView(
virtualViewId: Int,
node: AccessibilityNodeInfoCompat
) {
node.contentDescription = contentDescriptions[virtualViewId]
lineChart.highlighted?.let { highlights ->
highlights.forEach { highlight ->
if (highlight.dataIndex == virtualViewId) {
node.isSelected = true
}
}
}
node.addAction(AccessibilityActionCompat.ACTION_CLICK)
val entry = dataSet.getEntryForIndex(virtualViewId)
val position = lineChart.getPosition(entry, AxisDependency.LEFT)
val entryRectF = RectF(
position.x - CIRCLE_RADIUS,
position.y - CIRCLE_RADIUS,
position.x + CIRCLE_RADIUS,
position.y + CIRCLE_RADIUS
)
val entryRect = Rect()
entryRectF.round(entryRect)
node.setBoundsInParent(entryRect)
}
companion object {
private const val CIRCLE_RADIUS = 10
}
}
| gpl-2.0 | 9b4a4eb09b1f19dd2dbb74ff7fa82614 | 30.989691 | 93 | 0.651305 | 4.863636 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/datasets/ReaderBlogTableWrapper.kt | 1 | 1514 | package org.wordpress.android.datasets
import org.wordpress.android.models.ReaderBlog
import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper
import javax.inject.Inject
class ReaderBlogTableWrapper
@Inject constructor(private val readerUtilsWrapper: ReaderUtilsWrapper) {
fun getFollowedBlogs(): List<ReaderBlog> = ReaderBlogTable.getFollowedBlogs()!!
fun getBlogInfo(blogId: Long): ReaderBlog? = ReaderBlogTable.getBlogInfo(blogId)
fun getFeedInfo(feedId: Long): ReaderBlog? = ReaderBlogTable.getFeedInfo(feedId)
fun isNotificationsEnabled(blogId: Long): Boolean = ReaderBlogTable.isNotificationsEnabled(blogId)
fun setNotificationsEnabledByBlogId(blogId: Long, isEnabled: Boolean) =
ReaderBlogTable.setNotificationsEnabledByBlogId(blogId, isEnabled)
fun getReaderBlog(blogId: Long, feedId: Long): ReaderBlog? {
return if (readerUtilsWrapper.isExternalFeed(blogId, feedId)) {
ReaderBlogTable.getFeedInfo(feedId)
} else {
ReaderBlogTable.getBlogInfo(blogId)
}
}
fun isSiteFollowed(blogId: Long, feedId: Long): Boolean {
return if (readerUtilsWrapper.isExternalFeed(blogId, feedId)) {
ReaderBlogTable.isFollowedFeed(feedId)
} else {
ReaderBlogTable.isFollowedBlog(blogId)
}
}
fun incrementUnseenCount(blogId: Long) = ReaderBlogTable.incrementUnseenCount(blogId)
fun decrementUnseenCount(blogId: Long) = ReaderBlogTable.decrementUnseenCount(blogId)
}
| gpl-2.0 | af111a348e350de69774eaadbe24332b | 43.529412 | 102 | 0.746367 | 4.350575 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/data/LocalTrackDataSource.kt | 1 | 5740 | package com.kelsos.mbrc.repository.data
import com.kelsos.mbrc.data.db.RemoteDatabase
import com.kelsos.mbrc.data.library.Track
import com.kelsos.mbrc.data.library.Track_Table
import com.kelsos.mbrc.di.modules.AppDispatchers
import com.kelsos.mbrc.extensions.escapeLike
import com.raizlabs.android.dbflow.kotlinextensions.and
import com.raizlabs.android.dbflow.kotlinextensions.database
import com.raizlabs.android.dbflow.kotlinextensions.delete
import com.raizlabs.android.dbflow.kotlinextensions.from
import com.raizlabs.android.dbflow.kotlinextensions.modelAdapter
import com.raizlabs.android.dbflow.kotlinextensions.select
import com.raizlabs.android.dbflow.kotlinextensions.where
import com.raizlabs.android.dbflow.list.FlowCursorList
import com.raizlabs.android.dbflow.sql.language.OperatorGroup.clause
import com.raizlabs.android.dbflow.sql.language.SQLite
import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction
import kotlinx.coroutines.withContext
import javax.inject.Inject
class LocalTrackDataSource
@Inject constructor(private val dispatchers: AppDispatchers) : LocalDataSource<Track> {
override suspend fun deleteAll() = withContext(dispatchers.db) {
delete(Track::class).execute()
}
override suspend fun saveAll(list: List<Track>) = withContext(dispatchers.db) {
val adapter = modelAdapter<Track>()
val transaction = FastStoreModelTransaction.insertBuilder(adapter)
.addAll(list)
.build()
database<RemoteDatabase>().executeTransaction(transaction)
}
override suspend fun loadAllCursor(): FlowCursorList<Track> = withContext(dispatchers.db) {
val query = (select from Track::class)
.orderBy(Track_Table.album_artist, true)
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
return@withContext FlowCursorList.Builder(Track::class.java).modelQueriable(query).build()
}
suspend fun getAlbumTracks(album: String, artist: String): FlowCursorList<Track> =
withContext(dispatchers.db) {
val query = (select from Track::class
where Track_Table.album.`is`(album)
and Track_Table.album_artist.`is`(artist))
.orderBy(Track_Table.album_artist, true)
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
return@withContext FlowCursorList.Builder(Track::class.java).modelQueriable(query)
.build()
}
suspend fun getNonAlbumTracks(artist: String): FlowCursorList<Track> =
withContext(dispatchers.db) {
val query = (select from Track::class
where Track_Table.album.`is`("")
and Track_Table.artist.`is`(artist))
.orderBy(Track_Table.album_artist, true)
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
return@withContext FlowCursorList.Builder(Track::class.java).modelQueriable(query)
.build()
}
override suspend fun search(term: String): FlowCursorList<Track> = withContext(dispatchers.db) {
val query = (select from Track::class where Track_Table.title.like("%${term.escapeLike()}%"))
return@withContext FlowCursorList.Builder(Track::class.java).modelQueriable(query)
.build()
}
suspend fun getGenreTrackPaths(genre: String): List<String> =
withContext(dispatchers.db) {
return@withContext (select from Track::class
where Track_Table.genre.`is`(genre))
.orderBy(Track_Table.album_artist, true)
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
.queryList().filter { !it.src.isNullOrEmpty() }.map { it.src!! }
}
suspend fun getArtistTrackPaths(artist: String): List<String> =
withContext(dispatchers.db) {
return@withContext SQLite.select().from(Track::class).where(Track_Table.artist.`is`(artist))
.or(Track_Table.album_artist.`is`(artist))
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
.queryList().filter { !it.src.isNullOrEmpty() }.map { it.src!! }
}
suspend fun getAlbumTrackPaths(album: String, artist: String): List<String> =
withContext(dispatchers.db) {
return@withContext (select from Track::class
where Track_Table.album.`is`(album)
and Track_Table.album_artist.`is`(artist))
.orderBy(Track_Table.album_artist, true)
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
.queryList().filter { !it.src.isNullOrEmpty() }.map { it.src!! }
}
suspend fun getAllTrackPaths(): List<String> = withContext(dispatchers.db) {
return@withContext (select from Track::class)
.orderBy(Track_Table.album_artist, true)
.orderBy(Track_Table.album, true)
.orderBy(Track_Table.disc, true)
.orderBy(Track_Table.trackno, true)
.queryList().filter { !it.src.isNullOrEmpty() }.map { it.src!! }
}
override suspend fun isEmpty(): Boolean = withContext(dispatchers.db) {
return@withContext SQLite.selectCountOf().from(Track::class.java).longValue() == 0L
}
override suspend fun count(): Long = withContext(dispatchers.db) {
return@withContext SQLite.selectCountOf().from(Track::class.java).longValue()
}
override suspend fun removePreviousEntries(epoch: Long) {
withContext(dispatchers.db) {
SQLite.delete()
.from(Track::class.java)
.where(clause(Track_Table.date_added.lessThan(epoch)).or(Track_Table.date_added.isNull))
.execute()
}
}
}
| gpl-3.0 | 6b738b6cd900f6ea029e36b90838eccf | 39.70922 | 98 | 0.710105 | 3.983345 | false | false | false | false |
icela/FriceEngine | src/org/frice/obj/FObject.kt | 1 | 774 | package org.frice.obj
import org.frice.anim.FAnim
import org.frice.resource.FResource
import java.util.*
/**
* The base class of all concrete game objects
*
* Created by ice1000 on 2016/8/13.
* @author ice1000
* @since v0.1
*/
abstract class FObject(x: Double, y: Double) : PhysicalObject(x, y) {
var id = -1
val anims = LinkedList<FAnim>()
@Deprecated("Replace with `addAnim` or `clearAnim`", level = DeprecationLevel.WARNING) get
abstract val resource: FResource
abstract fun scale(x: Double, y: Double)
@Suppress("FunctionName", "DEPRECATION")
internal fun `{-# runAnims #-}`() = anims.forEach { it.`{-# do #-}`(this) }
@Suppress("DEPRECATION")
fun addAnim(anim: FAnim) = anims.add(anim)
@Suppress("DEPRECATION")
fun stopAnims() = anims.clear()
}
| agpl-3.0 | fdb18b1b494b57dde7373dac693ab5fe | 24.8 | 92 | 0.692506 | 3.108434 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/internal/statistic/libraryJar/libraryJarUtil.kt | 3 | 2314 | // 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.internal.statistic.libraryJar
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.jrt.JrtFileSystem
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPackage
import com.intellij.psi.search.ProjectScope
import java.util.jar.Attributes
private const val DIGIT_VERSION_PATTERN_PART = "(\\d+.\\d+|\\d+)"
private val JAR_FILE_NAME_PATTERN = Regex("[\\w|\\-.]+-($DIGIT_VERSION_PATTERN_PART[\\w|.]*)jar")
private val JRT_ROOT_FILE_NAME_PATTERN = Regex("[\\w|\\-.]+-($DIGIT_VERSION_PATTERN_PART[\\w|.]*)")
private fun versionByJarManifest(file: VirtualFile): String? {
return JarUtil.getJarAttribute(
VfsUtilCore.virtualToIoFile(file),
Attributes.Name.IMPLEMENTATION_VERSION,
)
}
private fun versionByJarFileName(fileName: String): String? {
val fileNameMatcher = JAR_FILE_NAME_PATTERN.matchEntire(fileName) ?: return null
val value = fileNameMatcher.groups[1]?.value ?: return null
return value.trimEnd('.')
}
private fun versionByJrtRootName(fileName: String): String? {
val fileNameMatcher = JRT_ROOT_FILE_NAME_PATTERN.matchEntire(fileName) ?: return null
val value = fileNameMatcher.groups[1]?.value ?: return null
return value.trimEnd('.')
}
private fun PsiElement.findCorrespondingVirtualFile(): VirtualFile? {
return if (this is PsiPackage)
getDirectories(ProjectScope.getLibrariesScope(project)).firstOrNull()?.virtualFile
else
containingFile?.virtualFile
}
internal fun findJarVersion(elementFromJar: PsiElement): String? {
val vFile = elementFromJar.findCorrespondingVirtualFile() ?: return null
if (vFile.fileSystem is JrtFileSystem) {
val fileName = (vFile.fileSystem as JrtFileSystem).getLocalByEntry(vFile)?.name ?: return null
return versionByJrtRootName(fileName)
}
val jarFile = JarFileSystem.getInstance().getVirtualFileForJar(vFile) ?: return null
val version = versionByJarManifest(jarFile) ?: versionByJarFileName(jarFile.name) ?: return null
return version.takeIf(String::isNotEmpty)
}
| apache-2.0 | 6843f98c0245607be313d5c774d21896 | 41.851852 | 158 | 0.768799 | 3.996546 | false | false | false | false |
GunoH/intellij-community | platform/configuration-store-impl/src/ProjectSaveSessionProducerManager.kt | 5 | 3616 | // 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.configurationStore
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.UnableToSaveProjectNotification
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VirtualFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
open class ProjectSaveSessionProducerManager(protected val project: Project) : SaveSessionProducerManager() {
suspend fun saveWithAdditionalSaveSessions(extraSessions: List<SaveSession>): SaveResult {
val saveSessions = mutableListOf<SaveSession>()
collectSaveSessions(saveSessions)
if (saveSessions.isEmpty() && extraSessions.isEmpty()) {
return SaveResult.EMPTY
}
val saveResult = withContext(Dispatchers.EDT) {
ApplicationManager.getApplication().runWriteAction(Computable {
val r = SaveResult()
saveSessions(extraSessions, r)
saveSessions(saveSessions, r)
r
})
}
validate(saveResult)
return saveResult
}
private suspend fun validate(saveResult: SaveResult) {
val notifications = getUnableToSaveNotifications()
val readonlyFiles = saveResult.readonlyFiles
if (readonlyFiles.isEmpty()) {
notifications.forEach(UnableToSaveProjectNotification::expire)
return
}
if (notifications.isNotEmpty()) {
throw UnresolvedReadOnlyFilesException(readonlyFiles.map { it.file })
}
val status = ensureFilesWritable(project, getFilesList(readonlyFiles))
if (status.hasReadonlyFiles()) {
val unresolvedReadOnlyFiles = status.readonlyFiles.toList()
dropUnableToSaveProjectNotification(project, unresolvedReadOnlyFiles)
saveResult.addError(UnresolvedReadOnlyFilesException(unresolvedReadOnlyFiles))
return
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
withContext(Dispatchers.EDT) {
ApplicationManager.getApplication().runWriteAction(Computable {
val r = SaveResult()
for (entry in oldList) {
executeSave(entry.session, r)
}
r
})
}.appendTo(saveResult)
if (readonlyFiles.isNotEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
saveResult.addError(UnresolvedReadOnlyFilesException(readonlyFiles.map { it.file }))
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: List<VirtualFile>) {
val notifications = getUnableToSaveNotifications()
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].files = readOnlyFiles
}
}
private fun getUnableToSaveNotifications(): Array<out UnableToSaveProjectNotification> {
val notificationManager = serviceIfCreated<NotificationsManager>() ?: return emptyArray()
return notificationManager.getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
}
}
private fun getFilesList(readonlyFiles: List<SaveSessionAndFile>) = readonlyFiles.map { it.file } | apache-2.0 | 3e72dd38b4f26f09b960b248139733a8 | 37.892473 | 120 | 0.764657 | 5.29429 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/impl-base/src/org/jetbrains/kotlin/idea/codeinsights/impl/base/applicators/RemoveEmptyParenthesesFromLambdaCallApplicator.kt | 1 | 1858 | // 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.codeinsights.impl.base.applicators
import org.jetbrains.kotlin.idea.base.psi.getLineNumber
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
object RemoveEmptyParenthesesFromLambdaCallApplicator {
val applicator = applicator<KtValueArgumentList, KotlinApplicatorInput.Empty> {
isApplicableByPsi { list: KtValueArgumentList ->
if (list.arguments.isNotEmpty()) return@isApplicableByPsi false
val parent = list.parent as? KtCallExpression ?: return@isApplicableByPsi false
if (parent.calleeExpression?.text == KtTokens.SUSPEND_KEYWORD.value) return@isApplicableByPsi false
val singleLambdaArgument = parent.lambdaArguments.singleOrNull() ?: return@isApplicableByPsi false
if (list.getLineNumber(start = false) != singleLambdaArgument.getLineNumber(start = true)) return@isApplicableByPsi false
val prev = list.getPrevSiblingIgnoringWhitespaceAndComments()
prev !is KtCallExpression && (prev as? KtQualifiedExpression)?.selectorExpression !is KtCallExpression
}
applyTo { list: KtValueArgumentList, _ -> list.delete() }
familyAndActionName { KotlinBundle.message("remove.unnecessary.parentheses.from.function.call.with.lambda") }
}
} | apache-2.0 | e3054607ca9ba175a4a1b8427abf7db1 | 65.392857 | 133 | 0.784177 | 5.204482 | false | false | false | false |
google/accompanist | placeholder-material/src/main/java/com/google/accompanist/placeholder/material/Placeholder.kt | 1 | 5663 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.placeholder.material
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.Transition
import androidx.compose.animation.core.spring
import androidx.compose.material.MaterialTheme
import androidx.compose.material.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.isSpecified
import com.google.accompanist.placeholder.PlaceholderDefaults
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.placeholder
/**
* Returns the value used as the the `color` parameter value on [Modifier.placeholder].
*
* @param backgroundColor The current background color of the layout. Defaults to
* `MaterialTheme.colors.surface`.
* @param contentColor The content color to be used on top of [backgroundColor].
* @param contentAlpha The alpha component to set on [contentColor] when compositing the color
* on top of [backgroundColor]. Defaults to `0.1f`.
*/
@Composable
fun PlaceholderDefaults.color(
backgroundColor: Color = MaterialTheme.colors.surface,
contentColor: Color = contentColorFor(backgroundColor),
contentAlpha: Float = 0.1f,
): Color = contentColor.copy(contentAlpha).compositeOver(backgroundColor)
/**
* Returns the value used as the the `highlightColor` parameter value of
* [PlaceholderHighlight.Companion.fade].
*
* @param backgroundColor The current background color of the layout. Defaults to
* `MaterialTheme.colors.surface`.
* @param alpha The alpha component to set on [backgroundColor]. Defaults to `0.3f`.
*/
@Composable
fun PlaceholderDefaults.fadeHighlightColor(
backgroundColor: Color = MaterialTheme.colors.surface,
alpha: Float = 0.3f,
): Color = backgroundColor.copy(alpha = alpha)
/**
* Returns the value used as the the `highlightColor` parameter value of
* [PlaceholderHighlight.Companion.shimmer].
*
* @param backgroundColor The current background color of the layout. Defaults to
* `MaterialTheme.colors.surface`.
* @param alpha The alpha component to set on [backgroundColor]. Defaults to `0.75f`.
*/
@Composable
fun PlaceholderDefaults.shimmerHighlightColor(
backgroundColor: Color = MaterialTheme.colors.surface,
alpha: Float = 0.75f,
): Color {
return backgroundColor.copy(alpha = alpha)
}
/**
* Draws some skeleton UI which is typically used whilst content is 'loading'.
*
* To customize the color and shape of the placeholder, you can use the foundation version of
* [Modifier.placeholder], along with the values provided by [PlaceholderDefaults].
*
* A cross-fade transition will be applied to the content and placeholder UI when the [visible]
* value changes. The transition can be customized via the [contentFadeTransitionSpec] and
* [placeholderFadeTransitionSpec] parameters.
*
* You can provide a [PlaceholderHighlight] which runs an highlight animation on the placeholder.
* The [shimmer] and [fade] implementations are provided for easy usage.
*
* You can find more information on the pattern at the Material Theming
* [Placeholder UI](https://material.io/design/communication/launch-screen.html#placeholder-ui)
* guidelines.
*
* @sample com.google.accompanist.sample.placeholder.DocSample_Material_Placeholder
*
* @param visible whether the placeholder should be visible or not.
* @param color the color used to draw the placeholder UI. If [Color.Unspecified] is provided,
* the placeholder will use [PlaceholderDefaults.color].
* @param shape desired shape of the placeholder. If null is provided the placeholder
* will use the small shape set in [MaterialTheme.shapes].
* @param highlight optional highlight animation.
* @param placeholderFadeTransitionSpec The transition spec to use when fading the placeholder
* on/off screen. The boolean parameter defined for the transition is [visible].
* @param contentFadeTransitionSpec The transition spec to use when fading the content
* on/off screen. The boolean parameter defined for the transition is [visible].
*/
fun Modifier.placeholder(
visible: Boolean,
color: Color = Color.Unspecified,
shape: Shape? = null,
highlight: PlaceholderHighlight? = null,
placeholderFadeTransitionSpec: @Composable Transition.Segment<Boolean>.() -> FiniteAnimationSpec<Float> = { spring() },
contentFadeTransitionSpec: @Composable Transition.Segment<Boolean>.() -> FiniteAnimationSpec<Float> = { spring() },
): Modifier = composed {
Modifier.placeholder(
visible = visible,
color = if (color.isSpecified) color else PlaceholderDefaults.color(),
shape = shape ?: MaterialTheme.shapes.small,
highlight = highlight,
placeholderFadeTransitionSpec = placeholderFadeTransitionSpec,
contentFadeTransitionSpec = contentFadeTransitionSpec,
)
}
| apache-2.0 | 8fb420362fc69d42a3ac237d7e28cdf0 | 43.590551 | 123 | 0.771146 | 4.512351 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/observer/DelegatedCall.kt | 1 | 2275 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins.observer
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.util.*
import io.ktor.util.date.*
import io.ktor.utils.io.*
import kotlin.coroutines.*
/**
* Wrap existing [HttpClientCall] with new [content].
*/
@Deprecated(
"Parameter [shouldCloseOrigin] is deprecated",
ReplaceWith("wrapWithContent(content)"),
level = DeprecationLevel.ERROR
)
@Suppress("UNUSED_PARAMETER")
public fun HttpClientCall.wrapWithContent(
content: ByteReadChannel,
shouldCloseOrigin: Boolean
): HttpClientCall = wrapWithContent(content)
/**
* Wrap existing [HttpClientCall] with new [content].
*/
public fun HttpClientCall.wrapWithContent(content: ByteReadChannel): HttpClientCall {
return DelegatedCall(client, content, this)
}
/**
* Wrap existing [HttpResponse] with new [content].
*/
@OptIn(InternalAPI::class)
internal fun HttpResponse.wrapWithContent(content: ByteReadChannel): HttpResponse {
return DelegatedResponse(call, content, this)
}
@OptIn(InternalAPI::class)
internal class DelegatedCall(
client: HttpClient,
content: ByteReadChannel,
originCall: HttpClientCall
) : HttpClientCall(client) {
init {
request = DelegatedRequest(this, originCall.request)
response = DelegatedResponse(this, content, originCall.response)
}
}
internal class DelegatedRequest(
override val call: HttpClientCall,
origin: HttpRequest
) : HttpRequest by origin
@InternalAPI
internal class DelegatedResponse constructor(
override val call: HttpClientCall,
override val content: ByteReadChannel,
private val origin: HttpResponse
) : HttpResponse() {
override val coroutineContext: CoroutineContext = origin.coroutineContext
override val status: HttpStatusCode get() = origin.status
override val version: HttpProtocolVersion get() = origin.version
override val requestTime: GMTDate get() = origin.requestTime
override val responseTime: GMTDate get() = origin.responseTime
override val headers: Headers get() = origin.headers
}
| apache-2.0 | 5320a6a39e514b3517b7f974eba0bd1d | 27.08642 | 118 | 0.749451 | 4.341603 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/util/lang/Hash.kt | 2 | 1080 | package eu.kanade.tachiyomi.util.lang
import java.security.MessageDigest
object Hash {
private val chars = charArrayOf(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'
)
private val MD5 get() = MessageDigest.getInstance("MD5")
private val SHA256 get() = MessageDigest.getInstance("SHA-256")
fun sha256(bytes: ByteArray): String {
return encodeHex(SHA256.digest(bytes))
}
fun sha256(string: String): String {
return sha256(string.toByteArray())
}
fun md5(bytes: ByteArray): String {
return encodeHex(MD5.digest(bytes))
}
fun md5(string: String): String {
return md5(string.toByteArray())
}
private fun encodeHex(data: ByteArray): String {
val l = data.size
val out = CharArray(l shl 1)
var i = 0
var j = 0
while (i < l) {
out[j++] = chars[(240 and data[i].toInt()).ushr(4)]
out[j++] = chars[15 and data[i].toInt()]
i++
}
return String(out)
}
}
| apache-2.0 | c8e0aa905035f262b20ddec67ab23454 | 23.545455 | 67 | 0.542593 | 3.529412 | false | false | false | false |
stanfy/helium | codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/mapper/mantle/ObjCMantleMappingsGenerator.kt | 1 | 6127 | package com.stanfy.helium.handler.codegen.objectivec.entity.mapper.mantle
import com.stanfy.helium.handler.codegen.objectivec.entity.ObjCEntitiesOptions
import com.stanfy.helium.handler.codegen.objectivec.entity.ObjCProject
import com.stanfy.helium.handler.codegen.objectivec.entity.ObjCProjectStructureGenerator
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCClass
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCMethod
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCMethodImplementationSourcePart
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCPregeneratedClass
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCSourcePart
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCStringSourcePart
import com.stanfy.helium.model.Project
/**
* Created by ptaykalo on 9/2/14.
* Class that is responsible for generate files those are responsible for
* correct mapping performing from JSON Objects to Messages
* Generated classes will could be used with
* https://github.com/Mantle/Mantle
*/
class ObjCMantleMappingsGenerator : ObjCProjectStructureGenerator {
override fun generate(project: ObjCProject, projectDSL: Project, options: ObjCEntitiesOptions) {
val messages = projectDSL.messages
val objcClasses = messages.mapNotNull { m -> project.classesTree.getClassForType(m.name) }
objcClasses.forEach { objCClass ->
objCClass.definition.superClassName = "MTLModel"
objCClass.definition.implementedProtocols.add("MTLJSONSerializing")
objCClass.definition.importFrameworkWithName("Mantle/Mantle")
generateKeyPathsByPropertyKeyMethod(objCClass, options)
}
// Generate protocol for custom mapping
addCustomMantleValueTransformerProtocol(project, options)
}
private fun generateKeyPathsByPropertyKeyMethod(objCClass: ObjCClass, options: ObjCEntitiesOptions): ObjCSourcePart {
val contentsBuilder = StringBuilder()
val jsonMappingsMethod = ObjCMethod("JSONKeyPathsByPropertyKey", ObjCMethod.ObjCMethodType.CLASS, "NSDictionary *")
val jsonMappingsMethodImpl = ObjCMethodImplementationSourcePart(jsonMappingsMethod)
objCClass.implementation.addBodySourcePart(jsonMappingsMethodImpl)
val customValueTransformerProtocolName = options.prefix + "CustomValueTransformerProtocol"
// Get the implementation
contentsBuilder.append(" return @{\n")
// Simple values with no corresponding field
val propertyDefinitions = objCClass.definition.propertyDefinitions
propertyDefinitions
.forEach { prop ->
val heliumField = prop.correspondingField
// We don't have meta information, so we just
// setting that there' no mapping can be perfomed
if (heliumField == null) {
contentsBuilder.append(""" @"${prop.name}" : [NSNull null],
""")
return@forEach
}
// If it's a sequence, then we '' add propertyJSONTranfromer for it
if (heliumField.isSequence) {
val itemClass = prop.sequenceType!!.name
var valueTransformerMethod = ObjCMethod(prop.name + "JSONTransformer", ObjCMethod.ObjCMethodType.CLASS, "NSValueTransformer *")
var valueTransformerMethodImpl = ObjCMethodImplementationSourcePart(valueTransformerMethod)
valueTransformerMethodImpl.addSourcePart("""
return [MTLValueTransformer mtl_JSONArrayTransformerWithModelClass:[$itemClass class]];
""")
objCClass.implementation.addBodySourcePart(valueTransformerMethodImpl)
if (!prop.sequenceType!!.isFoundationType()) {
objCClass.implementation.importClassWithName(itemClass)
}
return@forEach
}
// If it's foundation type it's simple property name -> JSON parameter name
if (prop.type.isFoundationType()) {
contentsBuilder.append(""" @"${prop.name}" : @"${heliumField.name}",
""")
return@forEach
}
// Most general case
val propClass = prop.type.name
var valueTransformerMethod = ObjCMethod(prop.name + "JSONTransformer", ObjCMethod.ObjCMethodType.CLASS, "NSValueTransformer *")
var valueTransformerMethodImpl = ObjCMethodImplementationSourcePart(valueTransformerMethod)
val customValueTransformer = options.mantleCustomValueTransformers[propClass]
var propClassString = if (prop.type.isCustom) {
"NSClassFromString(@\"$propClass\")"
} else {
objCClass.implementation.importClassWithName(propClass)
"[$propClass class]"
}
if (customValueTransformer != null) {
objCClass.implementation.importClassWithName(customValueTransformerProtocolName)
valueTransformerMethodImpl.addSourcePart("""
return [(id<$customValueTransformerProtocolName>)NSClassFromString(@"$customValueTransformer") valueTransformerWithModelOfClass:$propClassString];
""")
} else {
valueTransformerMethodImpl.addSourcePart("""
return [MTLValueTransformer mtl_JSONDictionaryTransformerWithModelClass:$propClassString];
""")
}
objCClass.implementation.addBodySourcePart(valueTransformerMethodImpl)
contentsBuilder.append(""" @"${prop.name}" : @"${heliumField.name}",
""")
}
contentsBuilder.append(" };")
jsonMappingsMethodImpl.addSourcePart(ObjCStringSourcePart(contentsBuilder.toString()))
return jsonMappingsMethodImpl
}
private fun addCustomMantleValueTransformerProtocol(project: ObjCProject, options: ObjCEntitiesOptions) {
val protocolName = options.prefix + "CustomValueTransformerProtocol"
project.classesTree.addSourceCodeClass(ObjCPregeneratedClass(protocolName, header =
"""
@protocol $protocolName <NSObject>
+ (NSValueTransformer*)valueTransformerWithModelOfClass:(Class)modelClass;
@end
"""
, implementation = null));
}
}
| apache-2.0 | 8c65ffe84280c8885321d71103c51f4d | 45.770992 | 160 | 0.725314 | 4.790461 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/fileresource/internal/FileResourceDownloadCallHelper.kt | 1 | 5798 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.fileresource.internal
import dagger.Reusable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore
import org.hisp.dhis.android.core.dataelement.DataElement
import org.hisp.dhis.android.core.dataelement.DataElementTableInfo
import org.hisp.dhis.android.core.datavalue.DataValue
import org.hisp.dhis.android.core.datavalue.DataValueTableInfo
import org.hisp.dhis.android.core.datavalue.internal.DataValueStore
import org.hisp.dhis.android.core.fileresource.FileResourceValueType
import org.hisp.dhis.android.core.trackedentity.*
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeValueStore
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueStore
@Reusable
internal class FileResourceDownloadCallHelper @Inject constructor(
private val dataElementStore: IdentifiableObjectStore<DataElement>,
private val trackedEntityAttributeValueStore: TrackedEntityAttributeValueStore,
private val trackedEntityAttributeStore: IdentifiableObjectStore<TrackedEntityAttribute>,
private val trackedEntityDataValueStore: TrackedEntityDataValueStore,
private val dataValueStore: DataValueStore
) {
fun getMissingTrackerAttributeValues(
params: FileResourceDownloadParams,
existingFileResources: List<String>
): List<TrackedEntityAttributeValue> {
// TODO Download files for TrackedEntityAttributes
val valueTypes = params.valueTypes.filter { it == FileResourceValueType.IMAGE }
val attributeUidsWhereClause = WhereClauseBuilder()
.appendInKeyEnumValues(TrackedEntityAttributeTableInfo.Columns.VALUE_TYPE, valueTypes)
.build()
val trackedEntityAttributeUids = trackedEntityAttributeStore.selectUidsWhere(attributeUidsWhereClause)
val attributeValuesWhereClause = WhereClauseBuilder()
.appendInKeyStringValues(
TrackedEntityAttributeValueTableInfo.Columns.TRACKED_ENTITY_ATTRIBUTE,
trackedEntityAttributeUids
)
.appendNotInKeyStringValues(
TrackedEntityAttributeValueTableInfo.Columns.VALUE,
existingFileResources
)
.build()
return trackedEntityAttributeValueStore.selectWhere(attributeValuesWhereClause)
}
fun getMissingTrackerDataValues(
params: FileResourceDownloadParams,
existingFileResources: List<String>
): List<TrackedEntityDataValue> {
val dataElementUidsWhereClause = WhereClauseBuilder()
.appendInKeyEnumValues(DataElementTableInfo.Columns.VALUE_TYPE, params.valueTypes)
.appendKeyStringValue(DataElementTableInfo.Columns.DOMAIN_TYPE, "TRACKER")
.build()
val dataElementUids = dataElementStore.selectUidsWhere(dataElementUidsWhereClause)
val dataValuesWhereClause = WhereClauseBuilder()
.appendInKeyStringValues(TrackedEntityDataValueTableInfo.Columns.DATA_ELEMENT, dataElementUids)
.appendNotInKeyStringValues(TrackedEntityDataValueTableInfo.Columns.VALUE, existingFileResources)
.build()
return trackedEntityDataValueStore.selectWhere(dataValuesWhereClause)
}
fun getMissingAggregatedDataValues(
params: FileResourceDownloadParams,
existingFileResources: List<String>
): List<DataValue> {
val dataElementUidsWhereClause = WhereClauseBuilder()
.appendInKeyEnumValues(DataElementTableInfo.Columns.VALUE_TYPE, params.valueTypes)
.appendKeyStringValue(DataElementTableInfo.Columns.DOMAIN_TYPE, "AGGREGATE")
.build()
val dataElementUids = dataElementStore.selectUidsWhere(dataElementUidsWhereClause)
val dataValuesWhereClause = WhereClauseBuilder()
.appendInKeyStringValues(DataValueTableInfo.Columns.DATA_ELEMENT, dataElementUids)
.appendNotInKeyStringValues(DataValueTableInfo.Columns.VALUE, existingFileResources)
.build()
return dataValueStore.selectWhere(dataValuesWhereClause)
}
}
| bsd-3-clause | 5b34f7e20d34289ca9706527803a763c | 52.685185 | 110 | 0.768196 | 5.181412 | false | false | false | false |
kdwink/intellij-community | platform/script-debugger/backend/src/util.kt | 1 | 3610 | /*
* Copyright 2000-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.debugger
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.CharsetToolkit
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.io.CharSequenceBackedByChars
import org.jetbrains.io.addListener
import java.io.File
import java.io.FileOutputStream
import java.nio.CharBuffer
import java.text.SimpleDateFormat
import java.util.concurrent.ConcurrentLinkedQueue
internal class LogEntry(val message: Any, val marker: String) {
internal val time = System.currentTimeMillis()
}
class MessagingLogger internal constructor(private val queue: ConcurrentLinkedQueue<LogEntry>) {
internal @Volatile var closed = false
fun add(inMessage: CharSequence, marker: String = "IN") {
queue.add(LogEntry(inMessage, marker))
}
fun add(outMessage: ByteBuf, marker: String = "OUT") {
queue.add(LogEntry(outMessage.copy(), marker))
}
fun close() {
closed = true
}
fun closeOnChannelClose(channel: Channel) {
channel.closeFuture().addListener {
try {
add("\"Closed\"", "Channel")
}
finally {
close()
}
}
}
}
fun createDebugLogger(@PropertyKey(resourceBundle = Registry.REGISTRY_BUNDLE) key: String): MessagingLogger? {
val debugFile = Registry.stringValue(key)
if (debugFile.isNullOrEmpty()) {
return null
}
val queue = ConcurrentLinkedQueue<LogEntry>()
val logger = MessagingLogger(queue)
ApplicationManager.getApplication().executeOnPooledThread {
val file = File(FileUtil.expandUserHome(debugFile))
val out = FileOutputStream(file)
val writer = out.writer()
writer.write("[\n")
writer.flush()
val fileChannel = out.channel
val dateFormatter = SimpleDateFormat("HH.mm.ss,SSS")
while (true) {
val entry = queue.poll() ?: if (logger.closed) {
break
}
else {
continue
}
writer.write("""{"timestamp": "${dateFormatter.format(entry.time)}", """)
val message = entry.message
when (message) {
is CharSequence -> {
writer.write("\"${entry.marker}\": ")
writer.flush()
if (message is CharSequenceBackedByChars) {
fileChannel.write(message.byteBuffer)
}
else {
fileChannel.write(CharsetToolkit.UTF8_CHARSET.encode(CharBuffer.wrap(message)))
}
writer.write("},\n")
writer.flush()
}
is ByteBuf -> {
writer.write("\"${entry.marker}\": ")
writer.flush()
message.getBytes(message.readerIndex(), out, message.readableBytes())
message.release()
writer.write("},\n")
writer.flush()
}
else -> throw RuntimeException("Unknown message type")
}
}
writer.write("]")
out.close()
}
return logger
}
| apache-2.0 | a15995646d99a1497561c003c02acd19 | 28.112903 | 110 | 0.672853 | 4.333733 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/IrsOwner.kt | 6 | 1685 | // 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.tools.projectWizard.ir.buildsystem
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.plus
import kotlinx.collections.immutable.toPersistentList
interface IrsOwner {
val irs: PersistentList<BuildSystemIR>
fun withReplacedIrs(irs: PersistentList<BuildSystemIR>): IrsOwner
}
@Suppress("UNCHECKED_CAST")
fun <I : IrsOwner> I.withIrs(irs: List<BuildSystemIR>) = withReplacedIrs(irs = this.irs + irs.toPersistentList()) as I
@Suppress("UNCHECKED_CAST")
fun <I : IrsOwner> I.withIrs(vararg irs: BuildSystemIR) = withReplacedIrs(irs = this.irs + irs) as I
@Suppress("UNCHECKED_CAST")
inline fun <I : IrsOwner> I.withoutIrs(filterNot: (BuildSystemIR) -> Boolean): I =
withReplacedIrs(irs = this.irs.filterNot(filterNot).toPersistentList()) as I
inline fun <reified I : BuildSystemIR> IrsOwner.irsOfType(): List<I> =
irs.filterIsInstance<I>().let { irs ->
if (irs.all { it is BuildSystemIRWithPriority })
irs.sortedBy { (it as BuildSystemIRWithPriority).priority }
else irs
}
inline fun <reified I : BuildSystemIR> IrsOwner.irsOfTypeOrNull() =
irsOfType<I>().takeIf { it.isNotEmpty() }
inline fun <reified I : BuildSystemIR> List<BuildSystemIR>.irsOfTypeOrNull() =
filterIsInstance<I>().takeIf { it.isNotEmpty() }
inline fun <reified T : BuildSystemIR> IrsOwner.firstIrOfType() =
irs.firstOrNull { ir -> ir is T } as T?
fun IrsOwner.freeIrs(): List<FreeIR> =
irs.filterIsInstance<FreeIR>()
| apache-2.0 | a31a2650c98441b78c1742b5d311cd37 | 37.295455 | 158 | 0.734718 | 3.631466 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/metric/ShardedResultGroup.kt | 1 | 3253 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"): you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.metric
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.common.hash.Hashing
import com.spotify.heroic.common.Histogram
import com.spotify.heroic.common.Series
import java.util.*
data class ShardedResultGroup(
val shard: Map<String, String>,
// key-value pairs that act as a lookup key, identifying this result group
val key: Map<String, String>,
val series: Set<Series>,
val metrics: MetricCollection,
val cadence: Long
) {
@JsonIgnore
fun isEmpty() = metrics.isEmpty
fun hashGroup(): Int {
val hasher = HASH_FUNCTION.newHasher()
shard.forEach { (key, value) ->
hasher.putInt(RECORD_SEPARATOR)
hasher.putString(key, Charsets.UTF_8)
hasher.putInt(RECORD_SEPARATOR)
hasher.putString(value, Charsets.UTF_8)
}
hasher.putInt(RECORD_SEPARATOR)
key.forEach { (key, value) ->
hasher.putInt(RECORD_SEPARATOR)
hasher.putString(key, Charsets.UTF_8)
hasher.putInt(RECORD_SEPARATOR)
hasher.putString(value, Charsets.UTF_8)
}
return hasher.hash().asInt()
}
companion object {
// record separator is needed to avoid conflicts
private const val RECORD_SEPARATOR = 0
private val HASH_FUNCTION = Hashing.murmur3_32()
fun summarize(resultGroups: List<ShardedResultGroup>): MultiSummary {
val shardSummary = mutableSetOf<Map<String, String>>()
val keySize = Histogram.Builder()
val seriesSummarizer = SeriesSetsSummarizer()
val dataSize = Histogram.Builder()
var cadence = Optional.empty<Long>()
resultGroups.forEach {
shardSummary.add(it.shard)
keySize.add(it.key.size.toLong())
seriesSummarizer.add(it.series)
dataSize.add(it.metrics.size().toLong())
cadence = Optional.of(it.cadence)
}
return MultiSummary(shardSummary.toSet(), keySize.build(),
seriesSummarizer.end(), dataSize.build(), cadence)
}
}
data class MultiSummary(
val shards: Set<Map<String, String>>,
val keySize: Histogram,
val series: SeriesSetsSummarizer.Summary,
val dataSize: Histogram,
val cadence: Optional<Long>
)
}
| apache-2.0 | bf6d0030035e1e99cab6139812604e48 | 33.606383 | 78 | 0.653858 | 4.314324 | false | false | false | false |
cdietze/klay | klay-demo/src/main/kotlin/klay/tests/core/PointerMouseTouchTest.kt | 1 | 16742 | package klay.tests.core
import klay.core.*
import klay.scene.*
import klay.scene.Mouse
import klay.scene.Pointer
import klay.scene.Touch
import euklid.f.Point
import euklid.f.Vector
internal class PointerMouseTouchTest
// private TestsGame.NToggle<String> propagate;
(game: TestsGame) : Test(game, "PointerMouseTouch", "Tests the Pointer, Mouse, and Touch interfaces.") {
private val baseFormat = TextFormat(Font("Times New Roman", 20f))
private val logFormat = TextFormat(Font("Times New Roman", 12f))
private var logger: TextLogger? = null
private var motionLabel: TextMapper? = null
private var preventDefault: TestsGame.Toggle? = null
private var capture: TestsGame.Toggle? = null
override fun init() {
var y = 20f
var x = 20f
preventDefault = TestsGame.Toggle("Prevent Default")
game.rootLayer.addAt(preventDefault!!.layer, x, y)
x += preventDefault!!.layer.width() + 5
capture = TestsGame.Toggle("Capture")
game.rootLayer.addAt(capture!!.layer, x, y)
x += capture!!.layer.width() + 5
// propagate = new TestsGame.NToggle<String>("Propagation", "Off", "On", "On (stop)") {
// @Override public void set(int value) {
// super.set(value);
// platform().setPropagateEvents(value != 0);
// }
// };
// graphics().rootLayer().addAt(propagate.layer, x, y);
y += preventDefault!!.layer.height() + 5
x = 20f
val boxWidth = 300f
val boxHeight = 110f
val mouse = Box("Mouse", 0xffff8080.toInt(), boxWidth, boxHeight)
game.rootLayer.addAt(mouse.layer, x, y)
y += mouse.layer.height() + 5
val pointer = Box("Pointer", 0xff80ff80.toInt(), boxWidth, boxHeight)
game.rootLayer.addAt(pointer.layer, x, y)
y += pointer.layer.height() + 5
val touch = Box("Touch", 0xff8080ff.toInt(), boxWidth, boxHeight)
game.rootLayer.addAt(touch.layer, x, y)
y = mouse.layer.ty()
x += touch.layer.width() + 5
// setup the logger and its layer
y += createLabel("Event Log", 0, x, y).height()
logger = TextLogger(375f, 15, logFormat)
logger!!.layer.setTranslation(x, y)
game.rootLayer.add(logger!!.layer)
y += logger!!.layer.height() + 5
// setup the motion logger and its layer
y += createLabel("Motion Log", 0, x, y).height()
motionLabel = TextMapper(375f, 6, logFormat)
motionLabel!!.layer.setTranslation(x, y)
game.rootLayer.add(motionLabel!!.layer)
// add mouse layer listener
mouse.label.events().connect(object : Mouse.Listener {
internal var label = mouse.label
override fun onButton(event: klay.core.Mouse.ButtonEvent, iact: Mouse.Interaction) {
if (event.down) {
_lstart = label.transform().translation
_pstart = Vector(event.x, event.y)
label.setAlpha(0.5f)
modify(event)
logger!!.log(describe(event, "mouse down"))
} else {
label.setAlpha(1.0f)
modify(event)
logger!!.log(describe(event, "mouse up"))
}
}
override fun onDrag(event: klay.core.Mouse.MotionEvent, iact: Mouse.Interaction) {
val delta = Vector(event.x, event.y).subtractLocal(_pstart!!)
label.setTranslation(_lstart!!.x + delta.x, _lstart!!.y + delta.y)
modify(event)
motionLabel!!["mouse drag"] = describe(event, "")
}
override fun onMotion(event: klay.core.Mouse.MotionEvent, iact: Mouse.Interaction) {
modify(event)
motionLabel!!["mouse move"] = describe(event, "")
}
override fun onHover(event: Mouse.HoverEvent, iact: Mouse.Interaction) {
modify(event)
logger!!.log(describe(event, if (event.inside) "mouse over" else "mouse out"))
}
override fun onWheel(event: klay.core.Mouse.WheelEvent, iact: Mouse.Interaction) {
modify(event)
logger!!.log(describe(event, "mouse wheel"))
}
private var _lstart: Vector? = null
private var _pstart: Vector? = null
})
// add mouse layer listener to parent
mouse.layer.events().connect(object : Mouse.Listener {
internal var start: Double = 0.toDouble()
override fun onButton(event: klay.core.Mouse.ButtonEvent, iact: Mouse.Interaction) {
if (event.down) {
start = event.time
logger!!.log(describe(event, "parent mouse down " + capture!!.value()))
} else
logger!!.log(describe(event, "parent mouse up"))
}
override fun onDrag(event: klay.core.Mouse.MotionEvent, iact: Mouse.Interaction) {
motionLabel!!["parent mouse drag"] = describe(event, "")
if (capture!!.value() && event.time - start > 1000 && !iact.captured()) iact.capture()
}
override fun onMotion(event: klay.core.Mouse.MotionEvent, iact: Mouse.Interaction) {
motionLabel!!["parent mouse move"] = describe(event, "")
}
override fun onHover(event: Mouse.HoverEvent, iact: Mouse.Interaction) {
logger!!.log(describe(event, "parent mouse " + if (event.inside) "over" else "out"))
}
override fun onWheel(event: klay.core.Mouse.WheelEvent, iact: Mouse.Interaction) {
logger!!.log(describe(event, "parent mouse wheel"))
}
})
// add pointer layer listener
pointer.label.events().connect(object : Pointer.Listener {
internal var label = pointer.label
override fun onStart(iact: Pointer.Interaction) {
val event = iact.event!!
_lstart = label.transform().translation
_pstart = Vector(event.x, event.y)
label.setAlpha(0.5f)
modify(event)
logger!!.log(describe(event, "pointer start"))
}
override fun onDrag(iact: Pointer.Interaction) {
val event = iact.event!!
val delta = Vector(event.x, event.y).subtractLocal(_pstart!!)
label.setTranslation(_lstart!!.x + delta.x, _lstart!!.y + delta.y)
modify(event)
motionLabel!!["pointer drag"] = describe(event, "")
}
override fun onEnd(iact: Pointer.Interaction) {
val event = iact.event!!
label.setAlpha(1.0f)
modify(event)
logger!!.log(describe(event, "pointer end"))
}
override fun onCancel(iact: Pointer.Interaction?) {
val event = iact!!.event!!
label.setAlpha(1.0f)
modify(event)
logger!!.log(describe(event, "pointer cancel"))
}
private var _lstart: Vector? = null
private var _pstart: Vector? = null
})
// add pointer listener for parent layer
pointer.layer.events().connect(object : Pointer.Listener {
internal var start: Double = 0.toDouble()
override fun onStart(iact: Pointer.Interaction) {
val event = iact.event!!
logger!!.log(describe(event, "parent pointer start"))
start = event.time
}
override fun onDrag(iact: Pointer.Interaction) {
val event = iact.event!!
motionLabel!!["parent pointer drag"] = describe(event, "")
if (capture!!.value() && event.time - start > 1000 && !iact.captured()) iact.capture()
}
override fun onEnd(iact: Pointer.Interaction) {
val event = iact.event!!
logger!!.log(describe(event, "parent pointer end"))
}
override fun onCancel(iact: Pointer.Interaction?) {
val event = iact!!.event!!
logger!!.log(describe(event, "parent pointer cancel"))
}
})
// add touch layer listener
touch.label.events().connect(object : Touch.Listener {
internal var label = touch.label
override fun onStart(iact: Touch.Interaction) {
val event = iact.event!!
_lstart = label.transform().translation
_pstart = Vector(event.x, event.y)
label.setAlpha(0.5f)
modify(event)
logger!!.log(describe(event, "touch start"))
}
override fun onMove(iact: Touch.Interaction) {
val event = iact.event!!
val delta = Vector(event.x, event.y).subtractLocal(_pstart!!)
label.setTranslation(_lstart!!.x + delta.x, _lstart!!.y + delta.y)
modify(event)
motionLabel!!["touch move"] = describe(event, "")
}
override fun onEnd(iact: Touch.Interaction) {
val event = iact.event!!
label.setAlpha(1.0f)
modify(event)
logger!!.log(describe(event, "touch end"))
}
override fun onCancel(iact: Touch.Interaction) {
val event = iact.event!!
label.setAlpha(1.0f)
modify(event)
logger!!.log(describe(event, "touch cancel"))
}
private var _lstart: Vector? = null
private var _pstart: Vector? = null
})
// add touch parent layer listener
touch.layer.events().connect(object : Touch.Listener {
override fun onStart(iact: Touch.Interaction) {
val event = iact.event!!
logger!!.log(describe(event, "parent touch start"))
}
override fun onMove(iact: Touch.Interaction) {
val event = iact.event!!
motionLabel!!["parent touch move"] = describe(event, "")
}
override fun onEnd(iact: Touch.Interaction) {
val event = iact.event!!
logger!!.log(describe(event, "parent touch end"))
}
override fun onCancel(iact: Touch.Interaction) {
val event = iact.event!!
logger!!.log(describe(event, "parent touch cancel"))
}
})
conns.add(game.plat.frame.connect { _ ->
logger!!.paint()
motionLabel!!.paint()
})
}
override fun usesPositionalInputs(): Boolean {
return true
}
private fun createLabel(text: String, bg: Int, x: Float, y: Float): ImageLayer {
return createLabel(text, game.rootLayer, 0xFF202020.toInt(), bg, x, y, 0f)
}
private fun createLabel(text: String, parent: GroupLayer,
fg: Int, bg: Int, x: Float, y: Float, padding: Float): ImageLayer {
val layout = game.graphics.layoutText(text, baseFormat)
val twidth = layout.size.width + padding * 2
val theight = layout.size.height + padding * 2
val canvas = game.graphics.createCanvas(twidth, theight)
if (bg != 0) canvas.setFillColor(bg).fillRect(0f, 0f, twidth, theight)
canvas.setFillColor(fg).fillText(layout, padding, padding)
val imageLayer = ImageLayer(canvas.toTexture())
parent.addAt(imageLayer, x, y)
return imageLayer
}
private fun modify(event: Event.XY) {
event.updateFlag(Event.F_PREVENT_DEFAULT, preventDefault!!.value())
// TODO
// event.flags().setPropagationStopped(propagate.valueIdx() == 2);
}
private fun describe(event: Event.XY, handler: String): String {
val sb = StringBuilder()
sb.append("@").append(event.time.toLong() % 10000).append(" ")
sb.append(if (event.isSet(Event.F_PREVENT_DEFAULT)) "pd " else "")
sb.append(handler).append(" (").append(event.x).append(",").append(event.y).append(")")
sb.append(" m[")
if (event.isAltDown) sb.append("A")
if (event.isCtrlDown) sb.append("C")
if (event.isMetaDown) sb.append("M")
if (event.isShiftDown) sb.append("S")
sb.append("]")
if (event is klay.core.Pointer.Event) {
sb.append(" isTouch(").append(event.isTouch).append(")")
}
if (event is klay.core.Mouse.ButtonEvent) {
sb.append(" button(").append(event.button).append(")")
}
if (event is klay.core.Mouse.MotionEvent) {
sb.append(" d(").append(event.dx).append(",").append(event.dy).append(")")
}
return sb.toString()
}
private open inner class Label(wid: Float, hei: Float, private val format: TextFormat) {
val layer: CanvasLayer = CanvasLayer(game.graphics, wid, hei)
private var layout: Array<out TextLayout>? = null
private var text: String? = null
private var dirty: Boolean = false
fun set(text: String) {
this.text = text
dirty = true
}
fun paint() {
if (!dirty) {
return
}
val canvas = layer.begin()
canvas.clear()
canvas.setFillColor(0xFF202020.toInt())
layout = game.graphics.layoutText(text!!, format, TextWrap.MANUAL)
var yy = 0f
for (line in layout!!.indices) {
canvas.fillText(layout!![line], 0f, yy)
yy += layout!![line].size.height
}
// if (yy > layer.height()) {
// game.log.error("Clipped");
// }
layer.end()
dirty = false
}
}
private inner class TextMapper(wid: Float, lines: Int, format: TextFormat) : Label(wid, game.graphics.layoutText(".", format).size.height * lines, format) {
var values: MutableMap<String, String> = mutableMapOf()
operator fun set(name: String, value: String) {
values.put(name, value)
update()
}
fun update() {
val sb = StringBuilder()
val iter = values.entries.iterator()
if (iter.hasNext()) append(sb, iter.next())
while (iter.hasNext()) append(sb.append('\n'), iter.next())
set(sb.toString())
}
internal fun append(sb: StringBuilder, entry: MutableMap.MutableEntry<String, String>) {
sb.append(entry.key).append(": ").append(entry.value)
}
}
private inner class TextLogger(wid: Float, private val lineCount: Int, format: TextFormat) : Label(wid, game.graphics.layoutText(".", format).size.height * lineCount, format) {
private val entries = ArrayList<String>()
fun log(text: String) {
entries.add(text)
if (entries.size > lineCount) {
entries.removeAt(0)
}
val sb = StringBuilder()
for (i in entries.indices.reversed()) {
sb.append(entries[i])
sb.append('\n')
}
set(sb.toString())
}
}
private inner class Box internal constructor(text: String, color: Int, wid: Float, hei: Float) : Layer.HitTester {
internal val layer: GroupLayer = GroupLayer(wid, hei)
internal val label: ImageLayer
init {
layer.add(object : Layer() {
override fun paintImpl(surface: Surface) {
surface.setFillColor(0xff000000.toInt())
val t = 0.5f
val l = 0.5f
val b = layer.height() - 0.5f
val r = layer.width() - 0.5f
surface.drawLine(l, t, l, b, 1f)
surface.drawLine(r, t, r, b, 1f)
surface.drawLine(l, b, r, b, 1f)
surface.drawLine(l, t, r, t, 1f)
}
})
label = createLabel(text, layer, 0xff000000.toInt(), color, 0f, 0f, 40f)
layer.addAt(label, (wid - label.width()) / 2, (hei - label.height()) / 2)
layer.setHitTester(this)
}
override fun hitTest(layer: Layer, p: Point): Layer? {
if (p.x >= 0 && p.y >= 0 && p.x < this.layer.width() && p.y < this.layer.height()) {
return layer.hitTestDefault(p)
}
return null
}
}
}
| apache-2.0 | cb0d2bfcea44d53793d60aa0dc9ddfcb | 37.576037 | 180 | 0.53972 | 4.298331 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/StaticMembers.kt | 6 | 6266 | // 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.completion.smart
import com.intellij.codeInsight.lookup.LookupElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.completion.LookupElementFactory
import org.jetbrains.kotlin.idea.completion.decorateAsStaticMember
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import org.jetbrains.kotlin.idea.core.PropertyDelegateAdditionalData
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.core.multipleFuzzyTypes
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.fuzzyReturnType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.types.TypeSubstitutor
import java.util.*
// adds java static members, enum members and members from companion object
class StaticMembers(
private val bindingContext: BindingContext,
private val lookupElementFactory: LookupElementFactory,
private val resolutionFacade: ResolutionFacade,
private val moduleDescriptor: ModuleDescriptor
) {
fun addToCollection(
collection: MutableCollection<LookupElement>,
expectedInfos: Collection<ExpectedInfo>,
context: KtSimpleNameExpression,
enumEntriesToSkip: Set<DeclarationDescriptor>
) {
val expectedInfosByClass = HashMap<ClassDescriptor, MutableList<ExpectedInfo>>()
for (expectedInfo in expectedInfos) {
for (fuzzyType in expectedInfo.multipleFuzzyTypes) {
val classDescriptor = fuzzyType.type.constructor.declarationDescriptor as? ClassDescriptor ?: continue
expectedInfosByClass.getOrPut(classDescriptor) { ArrayList() }.add(expectedInfo)
}
if (expectedInfo.additionalData is PropertyDelegateAdditionalData) {
val delegatesClass =
resolutionFacade.resolveImportReference(moduleDescriptor, FqName("kotlin.properties.Delegates")).singleOrNull()
if (delegatesClass is ClassDescriptor) {
addToCollection(
collection,
delegatesClass,
listOf(expectedInfo),
context,
enumEntriesToSkip,
SmartCompletionItemPriority.DELEGATES_STATIC_MEMBER
)
}
}
}
for ((classDescriptor, expectedInfosForClass) in expectedInfosByClass) {
if (!classDescriptor.name.isSpecial) {
addToCollection(
collection,
classDescriptor,
expectedInfosForClass,
context,
enumEntriesToSkip,
SmartCompletionItemPriority.STATIC_MEMBER
)
}
}
}
private fun addToCollection(
collection: MutableCollection<LookupElement>,
classDescriptor: ClassDescriptor,
expectedInfos: Collection<ExpectedInfo>,
context: KtSimpleNameExpression,
enumEntriesToSkip: Set<DeclarationDescriptor>,
defaultPriority: SmartCompletionItemPriority
) {
fun processMember(descriptor: DeclarationDescriptor) {
if (descriptor is DeclarationDescriptorWithVisibility && !descriptor.isVisible(
context,
null,
bindingContext,
resolutionFacade
)
) return
val matcher: (ExpectedInfo) -> ExpectedInfoMatch = when {
descriptor is CallableDescriptor -> {
val returnType = descriptor.fuzzyReturnType() ?: return
{ expectedInfo -> returnType.matchExpectedInfo(expectedInfo) }
}
DescriptorUtils.isEnumEntry(descriptor) && !enumEntriesToSkip.contains(descriptor) -> {
/* we do not need to check type of enum entry because it's taken from proper enum */
{ ExpectedInfoMatch.match(TypeSubstitutor.EMPTY) }
}
else -> return
}
val priority = when {
DescriptorUtils.isEnumEntry(descriptor) -> SmartCompletionItemPriority.ENUM_ENTRIES
else -> defaultPriority
}
collection.addLookupElements(descriptor, expectedInfos, matcher) { createLookupElements(it, priority) }
}
classDescriptor.staticScope.getContributedDescriptors().forEach(::processMember)
val companionObject = classDescriptor.companionObjectDescriptor
if (companionObject != null) {
companionObject.defaultType.memberScope.getContributedDescriptors()
.filter { !it.isExtension }
.forEach(::processMember)
}
val members = classDescriptor.defaultType.memberScope.getContributedDescriptors().filter { member ->
when (classDescriptor.kind) {
ClassKind.ENUM_CLASS -> member is ClassDescriptor // enum member
ClassKind.OBJECT -> member is CallableMemberDescriptor || DescriptorUtils.isNonCompanionObject(member)
else -> DescriptorUtils.isNonCompanionObject(member)
}
}
members.forEach(::processMember)
}
private fun createLookupElements(
memberDescriptor: DeclarationDescriptor,
priority: SmartCompletionItemPriority
): Collection<LookupElement> {
return lookupElementFactory.createStandardLookupElementsForDescriptor(memberDescriptor, useReceiverTypes = false)
.map {
it.decorateAsStaticMember(memberDescriptor, classNameAsLookupString = true)!!
.assignSmartCompletionPriority(priority)
}
}
}
| apache-2.0 | 6397f733a173e688272882a7e88dfafb | 43.757143 | 158 | 0.659432 | 6.25974 | false | false | false | false |
subhalaxmin/Programming-Kotlin | Chapter07/src/main/kotlin/com/packt/chapter2/literals.kt | 4 | 192 | package com.packt.chapter2
fun main(args: Array<String>) {
val int = 123
val long = 123456L
val double = 12.34
val float = 12.34F
val hexadecimal = 0xAB
val binary = 0b01010101
}
| mit | 69f9bd6e68337a16ec00b98bd93f3f53 | 18.2 | 31 | 0.682292 | 3.047619 | false | false | false | false |
ssseasonnn/RxDownload | rxdownload4/src/main/java/zlc/season/rxdownload4/utils/HttpUtil.kt | 1 | 2676 | package zlc.season.rxdownload4.utils
import retrofit2.Response
import java.io.Closeable
import java.util.*
import java.util.regex.Pattern
/** Closes this, ignoring any checked exceptions. */
fun Closeable.closeQuietly() {
try {
close()
} catch (rethrown: RuntimeException) {
throw rethrown
} catch (_: Exception) {
}
}
fun Response<*>.url(): String {
return raw().request().url().toString()
}
fun Response<*>.contentLength(): Long {
return header("Content-Length").toLongOrDefault(-1)
}
fun Response<*>.isChunked(): Boolean {
return header("Transfer-Encoding") == "chunked"
}
fun Response<*>.isSupportRange(): Boolean {
if (code() == 206
|| header("Content-Range").isNotEmpty()
|| header("Accept-Ranges") == "bytes") {
return true
}
return false
}
fun Response<*>.fileName(): String {
val url = url()
var fileName = contentDisposition()
if (fileName.isEmpty()) {
fileName = getFileNameFromUrl(url)
}
return fileName
}
fun Response<*>.sliceCount(rangeSize: Long): Long {
val totalSize = contentLength()
val remainder = totalSize % rangeSize
val result = totalSize / rangeSize
return if (remainder == 0L) {
result
} else {
result + 1
}
}
private fun Response<*>.contentDisposition(): String {
val contentDisposition = header("Content-Disposition").toLowerCase(Locale.getDefault())
if (contentDisposition.isEmpty()) {
return ""
}
val matcher = Pattern.compile(".*filename=(.*)").matcher(contentDisposition)
if (!matcher.find()) {
return ""
}
var result = matcher.group(1)
if (result.startsWith("\"")) {
result = result.substring(1)
}
if (result.endsWith("\"")) {
result = result.substring(0, result.length - 1)
}
result = result.replace("/", "_", false)
return result
}
fun getFileNameFromUrl(url: String): String {
var temp = url
if (temp.isNotEmpty()) {
val fragment = temp.lastIndexOf('#')
if (fragment > 0) {
temp = temp.substring(0, fragment)
}
val query = temp.lastIndexOf('?')
if (query > 0) {
temp = temp.substring(0, query)
}
val filenamePos = temp.lastIndexOf('/')
val filename = if (0 <= filenamePos) temp.substring(filenamePos + 1) else temp
if (filename.isNotEmpty() && Pattern.matches("[a-zA-Z_0-9.\\-()%]+", filename)) {
return filename
}
}
return ""
}
private fun Response<*>.header(key: String): String {
val header = headers().get(key)
return header ?: ""
} | apache-2.0 | addcd520222a96e3b749c5bee0e81ec1 | 22.278261 | 91 | 0.594544 | 4.187793 | false | false | false | false |
jaredsburrows/android-gif-example | app/src/main/java/com/burrowsapps/gif/search/data/source/network/NetworkResult.kt | 1 | 1179 | package com.burrowsapps.gif.search.data.source.network
import retrofit2.Response
import timber.log.Timber
internal sealed class NetworkResult<T>(
val data: T? = null,
val message: String? = null,
) {
class Loading<T> : NetworkResult<T>()
class Success<T>(data: T) : NetworkResult<T>(data = data)
class Empty<T> : NetworkResult<T>()
class Error<T>(data: T? = null, message: String? = null) : NetworkResult<T>(
data = data,
message = message,
)
companion object {
suspend fun <T> safeApiCall(apiCall: suspend () -> Response<T>): NetworkResult<T> {
return try {
val response = apiCall()
val body = response.body()
if (response.isSuccessful && body != null) {
return Success(data = body)
}
Timber.e(message = "request failed")
error(errorMessage = "${response.code()} ${response.message()}")
} catch (e: Exception) {
Timber.e(t = e, message = "request failed")
error(errorMessage = e.message ?: e.toString())
}
}
private fun <T> error(errorMessage: String): NetworkResult<T> =
Error(data = null, message = "Api call failed $errorMessage")
}
}
| apache-2.0 | 3133e8e86fc28aeeee051037f4df68ff | 30.864865 | 87 | 0.622561 | 3.790997 | false | false | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/ZoomIdeAction.kt | 1 | 1777 | // 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.ide.actions
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
abstract class ZoomIdeAction : AnAction(), DumbAware {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = !UISettings.getInstance().presentationMode
}
}
class ZoomInIdeAction : ZoomIdeAction() {
companion object {
private const val MAX_SCALE = 5
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabled = e.presentation.isEnabled &&
IdeScaleTransformer.currentScale < MAX_SCALE
}
override fun actionPerformed(e: AnActionEvent) {
IdeScaleTransformer.zoomIn()
}
}
class ZoomOutIdeAction : ZoomIdeAction() {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabled = e.presentation.isEnabled &&
IdeScaleTransformer.currentScale > IdeScaleTransformer.DEFAULT_SCALE
}
override fun actionPerformed(e: AnActionEvent) {
IdeScaleTransformer.zoomOut()
}
}
class ResetIdeScaleAction : ZoomIdeAction() {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabled = e.presentation.isEnabled &&
IdeScaleTransformer.currentScale != IdeScaleTransformer.DEFAULT_SCALE
}
override fun actionPerformed(e: AnActionEvent) {
IdeScaleTransformer.reset()
}
}
| apache-2.0 | be8e20a4237aa0393ecc0070eaee5839 | 31.309091 | 120 | 0.730445 | 4.453634 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.