content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.uncmorfi.map import android.os.Bundle import androidx.fragment.app.Fragment import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.uncmorfi.R import android.view.ViewGroup import android.view.LayoutInflater import android.view.View import com.google.android.gms.maps.MapsInitializer import kotlinx.android.synthetic.main.fragment_map.* /** * Muestra las ubicaciones de los comedores en un GoogleMap. */ class MapFragment : Fragment() { private lateinit var mMap: GoogleMap override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_map, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mapView.onCreate(savedInstanceState) mapView.onResume() try { MapsInitializer.initialize(activity!!.applicationContext) } catch (e: Exception) { e.printStackTrace() } mapView.getMapAsync { onMapReady(it) } } override fun onResume() { super.onResume() requireActivity().setTitle(R.string.navigation_map) mapView.onResume() } override fun onPause() { super.onPause() mapView.onPause() } override fun onLowMemory() { super.onLowMemory() mapView.onLowMemory() } private fun onMapReady(googleMap: GoogleMap) { mMap = googleMap mMap.addMarker(MarkerOptions() .position(CENTRAL) .title(getString(R.string.map_central))) mMap.addMarker(MarkerOptions() .position(BELGRANO) .title(getString(R.string.map_belgrano))) val cameraPosition = CameraPosition.builder() .target(CENTER) .zoom(14f) .build() mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } companion object { private val CENTRAL = LatLng(-31.439734, -64.189293) private val BELGRANO = LatLng(-31.416686, -64.189000) private val CENTER = LatLng(-31.428570, -64.184912) } }
app/src/main/java/com/uncmorfi/map/MapFragment.kt
374185587
package com.philsoft.metrotripper.app.state import com.google.android.gms.maps.model.LatLng import com.philsoft.metrotripper.model.Stop import com.philsoft.metrotripper.model.Trip sealed class AppAction sealed class MapAction : AppAction() { class MoveCameraToPosition(val latLng: LatLng) : MapAction() class ShowStopMarkers(val stops: List<Stop>) : MapAction() class SelectStopMarker(val stop: Stop) : MapAction() class EnableLocationButton(val enabled: Boolean) : MapAction() } sealed class StopHeadingAction : AppAction() { object LoadingTrips : StopHeadingAction() object LoadTripsComplete : StopHeadingAction() class ShowStop(val stop: Stop, val isSaved: Boolean) : StopHeadingAction() object LoadTripsError : StopHeadingAction() } sealed class TripListAction : AppAction() { class ShowTrips(val trips: List<Trip>) : TripListAction() } sealed class DrawerAction : AppAction() { object CloseDrawer : DrawerAction() } sealed class StopListAction : AppAction() { class ShowStops(val stops: List<Stop>) : StopListAction() class SetStopSelected(val stopId: Long) : StopListAction() } sealed class NexTripAction : AppAction() { class GetTrips(val stopId: Long) : NexTripAction() } sealed class SlidingPanelAction : AppAction() { object Expand : SlidingPanelAction() object Collapse : SlidingPanelAction() object Hide : SlidingPanelAction() } sealed class VehicleAction : AppAction() { class ShowVehicles(val trips: List<Trip>) : VehicleAction() }
app/src/main/java/com/philsoft/metrotripper/app/state/AppAction.kt
444856932
package arraysandstrings import java.lang.Math.abs /* pg. 91 Question 1.5 One Away */ fun oneAway(a: CharArray, b: CharArray): Boolean { val sizeDiff = a.size - b.size if (abs(sizeDiff) > 1) return false // by storing the bigger string in x we can treat the "remove" case as an insertion on x val (x, y) = if (sizeDiff >= 0) Pair(a, b) else Pair(b, a) var xIdx = 0 var yIdx = 0 var diff = 0 while (diff <= 1 && yIdx < y.size) { if (x[xIdx] != y[yIdx]) { // the case when the bigger string has one insertion if (xIdx + 1 < x.size && x[xIdx + 1] == y[yIdx]) xIdx++ diff++ } xIdx++ yIdx++ } return diff <= 1 } fun main() { println("Is oneAway? true == ${ oneAway("pale".toCharArray(), "ale".toCharArray()) }") println("Is oneAway? true == ${ oneAway("pales".toCharArray(), "pale".toCharArray()) }") println("Is oneAway? true == ${ oneAway("pales".toCharArray(), "bale".toCharArray()) }") println("Is oneAway? false == ${ oneAway("pales".toCharArray(), "bake".toCharArray()) }") println("Is oneAway? true == ${ oneAway("apple".toCharArray(), "aple".toCharArray()) }") }
cracking-the-code-interview/arraysandstrings/OneAway.kt
3076576338
package wu.seal.jsontokotlin.model.codeelements import wu.seal.jsontokotlin.utils.* /** * Default Value relative * Created by Seal.wu on 2017/9/25. */ fun getDefaultValue(propertyType: String): String { val rawType = getRawType(propertyType) return when { rawType == TYPE_INT -> 0.toString() rawType == TYPE_LONG -> 0L.toString() rawType == TYPE_STRING -> "\"\"" rawType == TYPE_DOUBLE -> 0.0.toString() rawType == TYPE_BOOLEAN -> false.toString() rawType.contains("List<") -> "listOf()" rawType.contains("Map<") -> "mapOf()" rawType == TYPE_ANY -> "Any()" rawType.contains("Array<") -> "emptyArray()" else -> "$rawType()" } } fun getDefaultValueAllowNull(propertyType: String) = if (propertyType.endsWith("?")) "null" else getDefaultValue(propertyType)
src/main/kotlin/wu/seal/jsontokotlin/model/codeelements/DefaultValue.kt
2016921695
package com.github.ramonrabello.kiphy.common.arch.viewmodel import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable open class BaseViewModel : ViewModel() { private val compositeDisposable = CompositeDisposable() fun Disposable.composeDisposable() = compositeDisposable.add(this) override fun onCleared() { super.onCleared() compositeDisposable.clear() } }
app/src/main/kotlin/com/github/ramonrabello/kiphy/common/arch/viewmodel/BaseViewModel.kt
3011924942
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.text.SemVer import org.rust.utils.GeneralCommandLine import org.rust.utils.seconds import java.io.File import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths private val LOG = Logger.getInstance(RustToolchain::class.java) data class RustToolchain(val location: String) { fun looksLikeValidToolchain(): Boolean = hasExecutable(CARGO) && hasExecutable(RUSTC) fun queryVersions(): VersionInfo { check(!ApplicationManager.getApplication().isDispatchThread) return VersionInfo( rustc = scrapeRustcVersion(pathToExecutable(RUSTC)) ) } fun cargo(cargoProjectDirectory: Path): Cargo = Cargo(pathToExecutable(CARGO), pathToExecutable(RUSTC), cargoProjectDirectory, rustup(cargoProjectDirectory)) fun rustup(cargoProjectDirectory: Path): Rustup? = if (isRustupAvailable) Rustup(pathToExecutable(RUSTUP), pathToExecutable(RUSTC), cargoProjectDirectory) else null val isRustupAvailable: Boolean get() = hasExecutable(RUSTUP) fun nonProjectCargo(): Cargo = Cargo(pathToExecutable(CARGO), pathToExecutable(RUSTC), null, null) val presentableLocation: String = pathToExecutable(CARGO).toString() private fun pathToExecutable(toolName: String): Path { val exeName = if (SystemInfo.isWindows) "$toolName.exe" else toolName return Paths.get(location, exeName).toAbsolutePath() } private fun hasExecutable(exec: String): Boolean = Files.isExecutable(pathToExecutable(exec)) data class VersionInfo( val rustc: RustcVersion ) companion object { private val RUSTC = "rustc" private val CARGO = "cargo" private val RUSTUP = "rustup" val CARGO_TOML = "Cargo.toml" val CARGO_LOCK = "Cargo.lock" fun suggest(): RustToolchain? = Suggestions.all().mapNotNull { val candidate = RustToolchain(it.absolutePath) if (candidate.looksLikeValidToolchain()) candidate else null }.firstOrNull() } } data class RustcVersion( val semver: SemVer?, val nightlyCommitHash: String? ) { companion object { val UNKNOWN = RustcVersion(null, null) } } private fun scrapeRustcVersion(rustc: Path): RustcVersion { val lines = GeneralCommandLine(rustc) .withParameters("--version", "--verbose") .runExecutable() ?: return RustcVersion.UNKNOWN // We want to parse following // // ``` // rustc 1.8.0-beta.1 (facbfdd71 2016-03-02) // binary: rustc // commit-hash: facbfdd71cb6ed0aeaeb06b6b8428f333de4072b // commit-date: 2016-03-02 // host: x86_64-unknown-linux-gnu // release: 1.8.0-beta.1 // ``` val commitHashRe = "commit-hash: (.*)".toRegex() val releaseRe = """release: (\d+\.\d+\.\d+)(.*)""".toRegex() val find = { re: Regex -> lines.mapNotNull { re.matchEntire(it) }.firstOrNull() } val commitHash = find(commitHashRe)?.let { it.groups[1]!!.value } val releaseMatch = find(releaseRe) ?: return RustcVersion.UNKNOWN val versionText = releaseMatch.groups[1]?.value ?: return RustcVersion.UNKNOWN val semVer = SemVer.parseFromText(versionText) ?: return RustcVersion.UNKNOWN val isStable = releaseMatch.groups[2]?.value.isNullOrEmpty() return RustcVersion(semVer, if (isStable) null else commitHash) } private object Suggestions { fun all() = sequenceOf( fromRustup(), fromPath(), forMac(), forUnix(), forWindows() ).flatten() private fun fromRustup(): Sequence<File> { val file = File(FileUtil.expandUserHome("~/.cargo/bin")) return if (file.isDirectory) { sequenceOf(file) } else { emptySequence() } } private fun fromPath(): Sequence<File> = System.getenv("PATH").orEmpty() .split(File.pathSeparator) .asSequence() .filter { !it.isEmpty() } .map(::File) .filter { it.isDirectory } private fun forUnix(): Sequence<File> { if (!SystemInfo.isUnix) return emptySequence() return sequenceOf(File("/usr/local/bin")) } private fun forMac(): Sequence<File> { if (!SystemInfo.isMac) return emptySequence() return sequenceOf(File("/usr/local/Cellar/rust/bin")) } private fun forWindows(): Sequence<File> { if (!SystemInfo.isWindows) return emptySequence() val fromHome = File(System.getProperty("user.home") ?: "", ".cargo/bin") val programFiles = File(System.getenv("ProgramFiles") ?: "") val fromProgramFiles = if (!programFiles.exists() || !programFiles.isDirectory) emptySequence() else programFiles.listFiles { file -> file.isDirectory }.asSequence() .filter { it.nameWithoutExtension.toLowerCase().startsWith("rust") } .map { File(it, "bin") } return sequenceOf(fromHome) + fromProgramFiles } } private fun GeneralCommandLine.runExecutable(): List<String>? { val procOut = try { CapturingProcessHandler(this).runProcess(1.seconds) } catch (e: ExecutionException) { LOG.warn("Failed to run executable!", e) return null } if (procOut.exitCode != 0 || procOut.isCancelled || procOut.isTimeout) return null return procOut.stdoutLines }
src/main/kotlin/org/rust/cargo/toolchain/RustToolchain.kt
2549416352
package wu.seal.jsontokotlin.feedback import java.text.SimpleDateFormat import java.util.* /** * * Created by Seal.Wu on 2017/9/25. */ const val ACTION_START = "action_start" const val ACTION_SUCCESS_COMPLETE = "action_success_complete" const val ACTION_FORMAT_JSON = "action_format_json" const val ACTION_CLICK_PROJECT_URL = "action_click_project_url" data class StartAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_START, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) ) data class SuccessCompleteAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_SUCCESS_COMPLETE, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) ) data class FormatJSONAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_FORMAT_JSON, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) ) data class ClickProjectURLAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_CLICK_PROJECT_URL, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) )
src/main/kotlin/wu/seal/jsontokotlin/feedback/Actions.kt
1938229935
package com.garpr.android.misc import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.DecelerateInterpolator import android.view.animation.Interpolator object AnimationUtils { val ACCELERATE_DECELERATE_INTERPOLATOR: Interpolator by lazy { AccelerateDecelerateInterpolator() } val DECELERATE_INTERPOLATOR: Interpolator by lazy { DecelerateInterpolator() } }
smash-ranks-android/app/src/main/java/com/garpr/android/misc/AnimationUtils.kt
1684145918
package com.booboot.vndbandroid.ui.preferences import android.content.Context import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatDelegate import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreference import com.booboot.vndbandroid.R import com.booboot.vndbandroid.extensions.setupStatusBar import com.booboot.vndbandroid.extensions.setupToolbar import com.booboot.vndbandroid.extensions.toBooleanOrFalse import com.booboot.vndbandroid.model.vndbandroid.NO import com.booboot.vndbandroid.model.vndbandroid.Preferences import com.booboot.vndbandroid.model.vndbandroid.YES class PreferencesFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupStatusBar() setupToolbar() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { preferenceManager.sharedPreferencesName = Preferences.kotprefName preferenceManager.sharedPreferencesMode = Context.MODE_PRIVATE addPreferencesFromResource(R.xml.app_preferences) /* Replicating indirect preferences from Preferences to the UI */ val prefGdprCrashlytics = preferenceScreen.findPreference(getString(R.string.pref_key_gdpr_crashlytics)) as? SwitchPreference prefGdprCrashlytics?.isChecked = Preferences.gdprCrashlytics == YES for (i in 0 until preferenceScreen.preferenceCount) { preferenceScreen.getPreference(i).onPreferenceChangeListener = this } } override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean { when (preference.key) { getString(R.string.pref_key_night_mode) -> { val value = newValue.toString().toInt() if (Preferences.nightMode != value) { AppCompatDelegate.setDefaultNightMode(value) Preferences.nightMode = value activity?.recreate() } } getString(R.string.pref_key_gdpr_crashlytics) -> { val value = newValue.toString().toBooleanOrFalse() Preferences.gdprCrashlytics = if (value) YES else NO } } return true } }
app/src/main/java/com/booboot/vndbandroid/ui/preferences/PreferencesFragment.kt
3772083793
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve.ref import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.resolve.* import org.rust.lang.core.types.BoundElement class RsPatBindingReferenceImpl( element: RsPatBinding ) : RsReferenceBase<RsPatBinding>(element), RsReference { override val RsPatBinding.referenceAnchor: PsiElement get() = referenceNameElement override fun resolveInner(): List<BoundElement<RsCompositeElement>> = collectResolveVariants(element.referenceName) { processPatBindingResolveVariants(element, false, it) } override fun getVariants(): Array<out Any> = collectCompletionVariants { processPatBindingResolveVariants(element, true, it) } override fun isReferenceTo(element: PsiElement): Boolean { val target = resolve() return element.manager.areElementsEquivalent(target, element) } }
src/main/kotlin/org/rust/lang/core/resolve/ref/RsPatBindingReferenceImpl.kt
2053526221
/* -*-mode:java; c-basic-offset:2; -*- */ /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. 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 names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) * and contributors of zlib. */ package com.jtransc.compression.jzlib import com.jtransc.annotation.JTranscInvisible @JTranscInvisible internal class InfCodes(private val z: ZStream, s: InfBlocks) { var mode // current inflate_codes mode = 0 // mode dependent information var len = 0 var tree // pointer into tree : IntArray? var tree_index = 0 var need // bits needed = 0 var lit = 0 // if EXT or COPY, where and how much var get // bits to get for extra = 0 var dist // distance back to copy from = 0 var lbits // ltree bits decoded per branch : Byte = 0 var dbits // dtree bits decoder per branch : Byte = 0 var ltree // literal/length/eob tree : IntArray var ltree_index // literal/length/eob tree = 0 var dtree // distance tree : IntArray var dtree_index // distance tree = 0 private val s: InfBlocks fun init( bl: Int, bd: Int, tl: IntArray, tl_index: Int, td: IntArray, td_index: Int ) { mode = START lbits = bl.toByte() dbits = bd.toByte() ltree = tl ltree_index = tl_index dtree = td dtree_index = td_index tree = null } fun proc(r: Int): Int { var r = r var j: Int // temporary storage var t: IntArray // temporary pointer val tindex: Int // temporary pointer val e: Int // extra bits or operation var b = 0 // bit buffer var k = 0 // bits in bit buffer var p = 0 // input data pointer var n: Int // bytes available there var q: Int // output window write pointer var m: Int // bytes to end of window or read pointer var f: Int // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z.next_in_index n = z.avail_in b = s.bitb k = s.bitk q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q // process input and output based on current state while (true) { when (mode) { START -> { if (m >= 258 && n >= 10) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q r = inflate_fast( lbits.toInt(), dbits.toInt(), ltree, ltree_index, dtree, dtree_index, s, z ) p = z.next_in_index n = z.avail_in b = s.bitb k = s.bitk q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (r != Z_OK) { mode = if (r == Z_STREAM_END) WASH else BADCODE break } } need = lbits.toInt() tree = ltree tree_index = ltree_index mode = LEN j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b ushr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e == 0) { // literal lit = tree!![tindex + 2] mode = LIT break } if (e and 16 != 0) { // length get = e and 15 len = tree!![tindex + 2] mode = LENEXT break } if (e and 64 == 0) { // next table need = e tree_index = tindex / 3 + tree!![tindex + 2] break } if (e and 32 != 0) { // end of block mode = WASH break } mode = BADCODE // invalid code z.msg = "invalid literal/length code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } LEN -> { j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b ushr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e == 0) { lit = tree!![tindex + 2] mode = LIT break } if (e and 16 != 0) { get = e and 15 len = tree!![tindex + 2] mode = LENEXT break } if (e and 64 == 0) { need = e tree_index = tindex / 3 + tree!![tindex + 2] break } if (e and 32 != 0) { mode = WASH break } mode = BADCODE z.msg = "invalid literal/length code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } LENEXT -> { j = get while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } len += b and inflate_mask[j] b = b shr j k -= j need = dbits.toInt() tree = dtree tree_index = dtree_index mode = DIST j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b shr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e and 16 != 0) { // distance get = e and 15 dist = tree!![tindex + 2] mode = DISTEXT break } if (e and 64 == 0) { // next table need = e tree_index = tindex / 3 + tree!![tindex + 2] break } mode = BADCODE // invalid code z.msg = "invalid distance code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } DIST -> { j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b shr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e and 16 != 0) { get = e and 15 dist = tree!![tindex + 2] mode = DISTEXT break } if (e and 64 == 0) { need = e tree_index = tindex / 3 + tree!![tindex + 2] break } mode = BADCODE z.msg = "invalid distance code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } DISTEXT -> { j = get while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } dist += b and inflate_mask[j] b = b shr j k -= j mode = COPY f = q - dist while (f < 0) { // modulo window size-"while" instead f += s.end // of "if" handles invalid distances } while (len != 0) { if (m == 0) { if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } s.window.get(q++) = s.window.get(f++) m-- if (f == s.end) f = 0 len-- } mode = START } COPY -> { f = q - dist while (f < 0) { f += s.end } while (len != 0) { if (m == 0) { if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } s.window.get(q++) = s.window.get(f++) m-- if (f == s.end) f = 0 len-- } mode = START } LIT -> { if (m == 0) { if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } r = Z_OK s.window.get(q++) = lit.toByte() m-- mode = START } WASH -> { if (k > 7) { // return unused byte, if any k -= 8 n++ p-- // can always return one } s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (s.read !== s.write) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } mode = END r = Z_STREAM_END s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } END -> { r = Z_STREAM_END s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } BADCODE -> { r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } else -> { r = Z_STREAM_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } } fun free(z: ZStream?) { // ZFREE(z, c); } // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. fun inflate_fast( bl: Int, bd: Int, tl: IntArray, tl_index: Int, td: IntArray, td_index: Int, s: InfBlocks, z: ZStream ): Int { var t: Int // temporary pointer var tp: IntArray // temporary pointer var tp_index: Int // temporary pointer var e: Int // extra bits or operation var b: Int // bit buffer var k: Int // bits in bit buffer var p: Int // input data pointer var n: Int // bytes available there var q: Int // output window write pointer var m: Int // bytes to end of window or read pointer val ml: Int // mask for literal/length tree val md: Int // mask for distance tree var c: Int // bytes to copy var d: Int // distance back to copy from var r: Int // copy source pointer var tp_index_t_3: Int // (tp_index+t)*3 // load input, output, bit values p = z.next_in_index n = z.avail_in b = s.bitb k = s.bitk q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q // initialize masks ml = inflate_mask[bl] md = inflate_mask[bd] // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while (k < 20) { // max bits for literal/length code n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } t = b and ml tp = tl tp_index = tl_index tp_index_t_3 = (tp_index + t) * 3 if (tp[tp_index_t_3].also { e = it } == 0) { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] s.window.get(q++) = tp[tp_index_t_3 + 2].toByte() m-- continue } do { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] if (e and 16 != 0) { e = e and 15 c = tp[tp_index_t_3 + 2] + (b and inflate_mask[e]) b = b shr e k -= e // decode distance base of block to copy while (k < 15) { // max bits for distance code n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } t = b and md tp = td tp_index = td_index tp_index_t_3 = (tp_index + t) * 3 e = tp[tp_index_t_3] do { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] if (e and 16 != 0) { // get extra bits to add to distance base e = e and 15 while (k < e) { // get extra bits (up to 13) n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } d = tp[tp_index_t_3 + 2] + (b and inflate_mask[e]) b = b shr e k -= e // do the copy m -= c if (q >= d) { // offset before dest // just copy r = q - d if (q - r > 0 && 2 > q - r) { s.window.get(q++) = s.window.get(r++) // minimum count is three, s.window.get(q++) = s.window.get(r++) // so unroll loop a little c -= 2 } else { java.lang.System.arraycopy(s.window, r, s.window, q, 2) q += 2 r += 2 c -= 2 } } else { // else offset after destination r = q - d do { r += s.end // force pointer in window } while (r < 0) // covers invalid distances e = s.end - r if (c > e) { // if source crosses, c -= e // wrapped copy if (q - r > 0 && e > q - r) { do { s.window.get(q++) = s.window.get(r++) } while (--e != 0) } else { java.lang.System.arraycopy(s.window, r, s.window, q, e) q += e r += e e = 0 } r = 0 // copy rest from start of window } } // copy all or what's left if (q - r > 0 && c > q - r) { do { s.window.get(q++) = s.window.get(r++) } while (--c != 0) } else { java.lang.System.arraycopy(s.window, r, s.window, q, c) q += c r += c c = 0 } break } else if (e and 64 == 0) { t += tp[tp_index_t_3 + 2] t += b and inflate_mask[e] tp_index_t_3 = (tp_index + t) * 3 e = tp[tp_index_t_3] } else { z.msg = "invalid distance code" c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_DATA_ERROR } } while (true) break } if (e and 64 == 0) { t += tp[tp_index_t_3 + 2] t += b and inflate_mask[e] tp_index_t_3 = (tp_index + t) * 3 if (tp[tp_index_t_3].also { e = it } == 0) { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] s.window.get(q++) = tp[tp_index_t_3 + 2].toByte() m-- break } } else if (e and 32 != 0) { c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_STREAM_END } else { z.msg = "invalid literal/length code" c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_DATA_ERROR } } while (true) } while (m >= 258 && n >= 10) // not enough input or output--restore pointers and return c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_OK } companion object { private val inflate_mask = intArrayOf( 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff ) private const val Z_OK = 0 private const val Z_STREAM_END = 1 private const val Z_NEED_DICT = 2 private const val Z_ERRNO = -1 private const val Z_STREAM_ERROR = -2 private const val Z_DATA_ERROR = -3 private const val Z_MEM_ERROR = -4 private const val Z_BUF_ERROR = -5 private const val Z_VERSION_ERROR = -6 // waiting for "i:"=input, // "o:"=output, // "x:"=nothing private const val START = 0 // x: set up for LEN private const val LEN = 1 // i: get length/literal/eob next private const val LENEXT = 2 // i: getting length extra (have base) private const val DIST = 3 // i: get distance next private const val DISTEXT = 4 // i: getting distance extra private const val COPY = 5 // o: copying bytes in window, waiting for space private const val LIT = 6 // o: got literal, waiting for output space private const val WASH = 7 // o: got eob, possibly still output waiting private const val END = 8 // x: got eob and all data flushed private const val BADCODE = 9 // x: got error } init { this.s = s } }
benchmark_kotlin_mpp/wip/jzlib/InfCodes.kt
667105037
package com.avast.mff.lecture3.repository import com.avast.mff.lecture3.data.GithubRepository import com.avast.mff.lecture3.data.User /** * API for getting data about Github users and their repositories */ interface Repository { /** * Get user detail for given username. */ fun getUser(username: String): Result<User> /** * Get list of repositories for given username. */ fun getUserRepository(username: String): Result<List<GithubRepository>> }
Lecture 3/Demo-app/app/src/main/java/com/avast/mff/lecture3/repository/Repository.kt
815101160
package org.http4k.format import com.google.gson.GsonBuilder import com.google.gson.JsonElement import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.Body import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.with import org.http4k.format.Gson.asA import org.http4k.format.Gson.auto import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class GsonAutoTest : AutoMarshallingJsonContract(Gson) { @Test fun ` roundtrip arbitrary object to and from JSON element`() { val obj = ArbObject("hello", ArbObject("world", null, listOf(1), true), emptyList(), false) val out = Gson.asJsonObject(obj) assertThat(asA(out, ArbObject::class), equalTo(obj)) } @Test fun `roundtrip list of arbitrary objects to and from node`() { val obj = ArbObject("hello", ArbObject("world", null, listOf(1), true), emptyList(), false) assertThat(Gson.asJsonObject(listOf(obj)).asA(), equalTo(listOf(obj))) } @Test fun `roundtrip list of arbitrary objects to and from body`() { val body = Body.auto<List<ArbObject>>().toLens() val obj = ArbObject("hello", ArbObject("world", null, listOf(1), true), emptyList(), false) assertThat(body(Response(OK).with(body of listOf(obj))), equalTo(listOf(obj))) } @Test fun `roundtrip array of arbitrary objects to and from body`() { val body = Body.auto<Array<ArbObject>>().toLens() val obj = ArbObject("hello", ArbObject("world", null, listOf(1), true), emptyList(), false) assertThat(body(Response(OK).with(body of arrayOf(obj))).toList(), equalTo(listOf(obj))) } @Test @Disabled("GSON does not currently have Kotlin class support") override fun `fails decoding when a required value is null`() { } @Test @Disabled("GSON does not currently have this support") override fun `fails decoding when a extra key found`() { } override fun strictMarshaller() = throw UnsupportedOperationException() override fun customMarshaller() = object : ConfigurableGson(GsonBuilder().asConfigurable().customise()) {} override fun customMarshallerProhibitStrings() = object : ConfigurableGson(GsonBuilder().asConfigurable().prohibitStrings() .customise()) {} } class GsonTest : JsonContract<JsonElement>(Gson) { override val prettyString = """{ "hello": "world" }""" } class GsonAutoEventsTest : AutoMarshallingEventsContract(Gson)
http4k-format/gson/src/test/kotlin/org/http4k/format/GsonTest.kt
1880468448
package com.muhron.kotlinq fun <TSource> Sequence<TSource>.whereWithIndex(predicate: (TSource, Int) -> Boolean): Sequence<TSource> = filterIndexed { i, t -> predicate(t, i) } fun <TSource> Iterable<TSource>.whereWithIndex(predicate: (TSource, Int) -> Boolean): Sequence<TSource> = asSequence().whereWithIndex(predicate) fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.whereWithIndex(predicate: (Map.Entry<TSourceK, TSourceV>, Int) -> Boolean): Sequence<Map.Entry<TSourceK, TSourceV>> = asSequence().whereWithIndex(predicate) fun <TSource> Array<TSource>.whereWithIndex(predicate: (TSource, Int) -> Boolean): Sequence<TSource> = asSequence().whereWithIndex(predicate)
src/main/kotlin/com/muhron/kotlinq/whereWithIndex.kt
1428461284
package br.com.freestuffs.shared.application /** * Created by bruno on 24/08/2017. */ interface BaseView<T> { var presenter: T? }
FreeStuffs-Android/app/src/main/java/br/com/freestuffs/shared/application/BaseView.kt
4225974545
package com.st8vrt.mitsumame.interceptors import org.wasabi.interceptors.Interceptor import org.slf4j.LoggerFactory import org.wasabi.http.Request import org.wasabi.http.Response /** * Created by swishy on 30/10/13. */ public class MitsumameDecryptionInterceptor(): Interceptor() { private var log = LoggerFactory.getLogger(MitsumameDecryptionInterceptor::class.java) override fun intercept(request: Request, response: Response): Boolean { log!!.info("Decryption Interceptor invoked.") // TODO implement decryption... // TODO call com.st8vrt.mitsumame.authentication handler once done here and force auth again as something in credentials is bad. return false } }
core/src/main/kotlin/com/st8vrt/mitsumame/interceptors/MitsumameDecryptionInterceptor.kt
1253271816
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.paging.pagingwithnetwork.reddit.ui import android.content.Intent import android.net.Uri import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.android.example.paging.pagingwithnetwork.R import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost import com.bumptech.glide.RequestManager import com.bumptech.glide.request.RequestOptions /** * A RecyclerView ViewHolder that displays a reddit post. */ class RedditPostViewHolder(view: View, private val glide: RequestManager) : RecyclerView.ViewHolder(view) { private val title: TextView = view.findViewById(R.id.title) private val subtitle: TextView = view.findViewById(R.id.subtitle) private val score: TextView = view.findViewById(R.id.score) private val thumbnail : ImageView = view.findViewById(R.id.thumbnail) private var post : RedditPost? = null init { view.setOnClickListener { post?.url?.let { url -> val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) view.context.startActivity(intent) } } } fun bind(post: RedditPost?) { this.post = post title.text = post?.title ?: "loading" subtitle.text = itemView.context.resources.getString(R.string.post_subtitle, post?.author ?: "unknown") score.text = "${post?.score ?: 0}" if (post?.thumbnail?.startsWith("http") == true) { thumbnail.visibility = View.VISIBLE glide.load(post.thumbnail).apply(RequestOptions.centerCropTransform() .placeholder(R.drawable.ic_insert_photo_black_48dp)) .into(thumbnail) } else { thumbnail.visibility = View.GONE glide.clear(thumbnail) } } companion object { fun create(parent: ViewGroup, glide: RequestManager): RedditPostViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.reddit_post_item, parent, false) return RedditPostViewHolder(view, glide) } } fun updateScore(item: RedditPost?) { post = item score.text = "${item?.score ?: 0}" } }
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/ui/RedditPostViewHolder.kt
3954473855
package cat.xojan.random1.data import cat.xojan.random1.domain.model.Program import cat.xojan.random1.domain.model.ProgramData import cat.xojan.random1.domain.model.Section import cat.xojan.random1.domain.repository.ProgramRepository import io.reactivex.Observable import io.reactivex.Single class RemoteProgramRepository(private val service: ApiService): ProgramRepository { private var programData: Single<ProgramData>? = null override fun getPrograms(refresh: Boolean): Single<List<Program>> { if (programData == null || refresh) { programData = service.getProgramData().cache() } return programData!!.map { pd: ProgramData -> pd.toPrograms() } } override fun getProgram(programId: String): Single<Program> = getPrograms(false).flatMap { programs -> Observable.fromIterable(programs) .filter { p: Program -> p.id == programId } .firstOrError() } override fun hasSections(programId: String): Single<Boolean> = getProgram(programId).map { p -> p.sections!!.size > 1 } override fun getSections(programId: String): Single<List<Section>> = getProgram(programId) .map { p -> p.sections } }
app/src/rac1/java/cat/xojan/random1/data/RemoteProgramRepository.kt
2664416565
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.tests /** Annotation to specify an Operating System to override the "os.name" System Property. */ @Retention(AnnotationRetention.RUNTIME) annotation class WithOs(val os: OS, val arch: String = "") enum class OS(val propertyName: String) { WIN("Windows"), MAC("MacOs"), LINUX("Linux") }
packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/WithOs.kt
153270542
import org.junit.Assert.assertEquals import org.junit.Test /** * @Author Vasyl Antoniuk (@toniukan) */ class BinaryHeapTest { @Test fun createHeap(): Unit { val heap = BinaryHeap<Int>() assertEquals(heap.size, 0) assertEquals(heap.isEmpty(), true) return } @Test fun addOneElement(): Unit { val heap = BinaryHeap<Int>() heap.add(10) assertEquals(heap.size, 1) assertEquals(heap.isEmpty(), false) } @Test fun clear(): Unit { val heap = BinaryHeap<Int>() heap.add(10) heap.clear() assertEquals(heap.size, 0) assertEquals(heap.isEmpty(), true) } @Test fun peek(): Unit { val heap = BinaryHeap<Int>() heap.add(10) heap.add(20) assertEquals(heap.peek(), 10) // to check if 'peek' is not changing the heap assertEquals(heap.peek(), 10) } @Test fun remove(): Unit { val heap = BinaryHeap<Int>() heap.add(10) heap.add(20) heap.add(30) assertEquals(heap.remove(), 10) assertEquals(heap.remove(), 20) assertEquals(heap.remove(), 30) assertEquals(heap.isEmpty(), true) } @Test fun normalScenario(): Unit { val heap = BinaryHeap<Int>() heap.add(30) assertEquals(heap.peek(), 30) heap.add(15) assertEquals(heap.peek(), 15) heap.add(10) assertEquals(heap.remove(), 10) assertEquals(heap.peek(), 15) heap.add(25) assertEquals(heap.remove(), 15) assertEquals(heap.remove(), 25) assertEquals(heap.remove(), 30) } @Test fun duplicates(): Unit { val heap = BinaryHeap<Int>() heap.add(10) heap.add(5) heap.add(15) heap.add(10) assertEquals(heap.remove(), 5) assertEquals(heap.remove(), 10) assertEquals(heap.remove(), 10) assertEquals(heap.remove(), 15) } }
src/core/heaps/test/BinaryHeapTest.kt
2781444866
/** * Competir | Competition - Competition application for Educational institutions * Copyright © 2014 Reijhanniel Jearl Campos ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package competir.competition data class Answer<T>(val value: T, val explanation: String?) { constructor(value: T) : this(value, "") }
competition/src/main/kotlin/competir/competition/Answer.kt
1388131896
package org.mailcall.script import javax.script.Bindings import javax.script.SimpleBindings /** * @author Odysseus Levy ([email protected]) */ class SimpleConfiguration(val properties: Bindings = SimpleBindings()) : Configuration { fun put(key: String, value: Any) { properties.put(key, value) } fun putAll(values: Map<String, Any>) { properties.putAll(values); } override fun addObjectsToScope(bindings: Bindings) { bindings.putAll(properties); } }
src/main/kotlin/org/mailcall/script/SimpleConfiguration.kt
3508165387
package pl.loziuu.ivms.ddd class DomainValidationException(message: String) : RuntimeException(message)
ivms/src/main/kotlin/pl/loziuu/ivms/ddd/DomainValidationException.kt
2933887517
package de.westnordost.streetcomplete.util import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import androidx.exifinterface.media.ExifInterface import java.io.IOException import kotlin.math.min /** Create a bitmap that is not larger than the given desired max width or height and that is * rotated according to its EXIF information */ fun decodeScaledBitmapAndNormalize(imagePath: String, desiredMaxWidth: Int, desiredMaxHeight: Int): Bitmap? { var (width, height) = getImageSize(imagePath) ?: return null val maxWidth = min(width, desiredMaxWidth) val maxHeight = min(height, desiredMaxHeight) // Calculate the correct inSampleSize/resize value. This helps reduce memory use. It should be a power of 2 // from: https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966 var inSampleSize = 1 while (width / 2 > maxWidth || height / 2 > maxHeight) { width /= 2 height /= 2 inSampleSize *= 2 } val desiredScale = maxWidth.toFloat() / width // Decode with inSampleSize val options = BitmapFactory.Options().also { it.inJustDecodeBounds = false it.inDither = false it.inSampleSize = inSampleSize it.inScaled = false it.inPreferredConfig = Bitmap.Config.ARGB_8888 } val sampledSrcBitmap = BitmapFactory.decodeFile(imagePath, options) // Resize & Rotate val matrix = getRotationMatrix(imagePath) matrix.postScale(desiredScale, desiredScale) val result = Bitmap.createBitmap( sampledSrcBitmap, 0, 0, sampledSrcBitmap.width, sampledSrcBitmap.height, matrix, true) if (result != sampledSrcBitmap) { sampledSrcBitmap.recycle() } return result } private fun getImageSize(imagePath: String): Size? { val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(imagePath, options) val width = options.outWidth val height = options.outHeight if (width <= 0 || height <= 0) return null return Size(width, height) } private fun getRotationMatrix(imagePath: String): Matrix = try { ExifInterface(imagePath).rotationMatrix } catch (ignore: IOException) { Matrix() } private data class Size(val width: Int, val height: Int) val ExifInterface.rotationMatrix: Matrix get() { val orientation = getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED ) val matrix = Matrix() when (orientation) { ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f) ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f) ExifInterface.ORIENTATION_FLIP_VERTICAL -> { matrix.setRotate(180f) matrix.postScale(-1f, 1f) } ExifInterface.ORIENTATION_TRANSPOSE -> { matrix.setRotate(90f) matrix.postScale(-1f, 1f) } ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f) ExifInterface.ORIENTATION_TRANSVERSE -> { matrix.setRotate(-90f) matrix.postScale(-1f, 1f) } ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f) } return matrix }
app/src/main/java/de/westnordost/streetcomplete/util/BitmapFactoryUtils.kt
3066108587
package com.henorek.discharge @Retention(value = AnnotationRetention.BINARY) @Target(AnnotationTarget.CONSTRUCTOR, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) annotation class HandleException
library/src/main/java/com/henorek/discharge/HandleException.kt
1769976533
/* * Copyright (c) 2018. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.toshi.R import com.toshi.model.local.Conversation import com.toshi.model.local.User import com.toshi.util.keyboard.SOFAMessageFormatter import com.toshi.view.adapter.viewholder.ThreadViewHolder class ConversationAdapter( private val onItemClickListener: (Conversation) -> Unit, private val onItemLongClickListener: (Conversation) -> Unit, private val onItemDeleted: (Conversation) -> Unit ) : BaseCompoundableAdapter<ThreadViewHolder, Conversation>() { private var messageFormatter: SOFAMessageFormatter? = null fun setItemList(localUser: User?, items: List<Conversation>) { initMessageFormatter(localUser) val filteredItems = items.filter { !it.isRecipientInvalid } // Don't show conversations with invalid recipients. setItemList(filteredItems) } private fun initMessageFormatter(localUser: User?) { if (messageFormatter != null) return messageFormatter = SOFAMessageFormatter(localUser) } override fun compoundableBindViewHolder(viewHolder: RecyclerView.ViewHolder, adapterIndex: Int) { val typedHolder = viewHolder as? ThreadViewHolder ?: throw AssertionError("This is not the right type!") onBindViewHolder(typedHolder, adapterIndex) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ThreadViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item__recent, parent, false) return ThreadViewHolder(itemView) } override fun onBindViewHolder(holder: ThreadViewHolder, position: Int) { val conversation = safelyAt(position) ?: throw AssertionError("No conversation at $position") holder.setThread(conversation) val formattedLatestMessage = formatLatestMessage(conversation) holder.setLatestMessage(formattedLatestMessage) holder.setOnItemClickListener(conversation, onItemClickListener) holder.setOnItemLongClickListener(conversation, onItemLongClickListener) } private fun formatLatestMessage(conversation: Conversation): String { return if (conversation.latestMessage != null) { messageFormatter?.formatMessage(conversation.latestMessage) ?: "" } else "" } override fun deleteItem(item: Conversation) = onItemDeleted(item) }
app/src/main/java/com/toshi/view/adapter/ConversationAdapter.kt
737556141
package com.jtechme.jumpgo.search.engine import com.jtechme.jumpgo.R import com.jtechme.jumpgo.constant.Constants /** * The StartPage search engine. */ class StartPageSearch : BaseSearchEngine( "file:///android_asset/startpage.png", Constants.STARTPAGE_SEARCH, R.string.search_engine_startpage )
app/src/main/java/com/jtechme/jumpgo/search/engine/StartPageSearch.kt
1985870752
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Akvo Flow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.presentation.form.view.groups import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.widget.LinearLayout import android.widget.TextView import com.google.android.material.textfield.TextInputEditText import org.akvo.flow.presentation.form.view.groups.entity.ViewQuestionAnswer class CascadeQuestionLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { fun setUpViews(questionAnswer: ViewQuestionAnswer.CascadeViewQuestionAnswer) { for (cascadeLevel in questionAnswer.answers) { val textView = TextView(context) textView.text = cascadeLevel.level textView.setTypeface(null, Typeface.BOLD) textView.textSize = 18.0f addView(textView) val textInputEditText = TextInputEditText(context) textInputEditText.isEnabled = false textInputEditText.setText(cascadeLevel.answer) addView(textInputEditText) } } }
app/src/main/java/org/akvo/flow/presentation/form/view/groups/CascadeQuestionLayout.kt
1814509520
package org.mifos.mobile.utils import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload /* * Created by saksham on 29/July/2018 */ class RxEvent { data class AddGuarantorEvent(var payload: GuarantorApplicationPayload, var index: Int) data class DeleteGuarantorEvent(var index: Int) data class UpdateGuarantorEvent(var payload: GuarantorApplicationPayload, var index: Int) }
app/src/main/java/org/mifos/mobile/utils/RxEvent.kt
96945418
package runtimemodels.chazm.api.relation import runtimemodels.chazm.api.entity.Characteristic import runtimemodels.chazm.api.entity.CharacteristicId import runtimemodels.chazm.api.entity.Role import runtimemodels.chazm.api.entity.RoleId /** * The [ContainsManager] interface defines the APIs for managing a set of [Contains] relations. * * @author Christopher Zhong * @since 7.0.0 */ interface ContainsManager { /** * Adds a [Contains] relation between a [Role] and a [Characteristic] to this [ContainsManager]. * * @param contains the [Contains] relation to add. */ fun add(contains: Contains) /** * Returns the [Contains] relation between an [Role] and an [Characteristic] from this [HasManager]. * * @param roleId the [RoleId] that represents the [Role]. * @param characteristicId the [CharacteristicId] that represents the [Characteristic]. * @return the [Contains] relation if it exists, `null` otherwise. */ operator fun get(roleId: RoleId, characteristicId: CharacteristicId): Contains? /** * Returns a [Map] of [Characteristic]s that are contained by a [Role] from this [ContainsManager]. * * @param id the [RoleId] that represents the [Role]. * @return a [Map] of [Characteristic]s. */ operator fun get(id: RoleId): Map<CharacteristicId, Contains> /** * Returns a [Map] of [Role]s that contains a [Characteristic] from this [ContainsManager]. * * @param id the [CharacteristicId] that represents the [Characteristic]. * @return a [Map] of [Role]s. */ operator fun get(id: CharacteristicId): Map<RoleId, Contains> /** * Removes a [Contains] relation between a [Role] and a [Characteristic] from this [ContainsManager]. * * @param roleId the [RoleId] that represents the [Role]. * @param characteristicId the [CharacteristicId] that represents the [Characteristic]. * @return the [Characteristic] that was removed, `null` otherwise. */ fun remove(roleId: RoleId, characteristicId: CharacteristicId): Contains? /** * Removes all [Contains] relations associated to a [Role] from this [ContainsManager]. * * @param id the [RoleId] that represents the [Role]. */ fun remove(id: RoleId) /** * Removes all [Contains] relations associated to a [Characteristic] from this [ContainsManager]. * * @param id the [CharacteristicId] that represents the [Characteristic]. */ fun remove(id: CharacteristicId) }
chazm-api/src/main/kotlin/runtimemodels/chazm/api/relation/ContainsManager.kt
3729019041
package de.trbnb.databindingcommands.command /** * A [Command] implementation that can simply be set as en-/disabled with a boolean value. * * @param action The initial action that will be run when the Command is executed. * @param isEnabled Has to be `true` if this Command should be enabled, otherwise `false`. */ @Deprecated("This library is deprecated and migrated into MvvmBase (https://github.com/trbnb/mvvmbase)") open class SimpleCommand<out R>(isEnabled: Boolean = true, action: () -> R) : BaseCommandImpl<R>(action) { override var isEnabled: Boolean = isEnabled set(value) { field = value triggerEnabledChangedListener() } }
library/src/main/java/de/trbnb/databindingcommands/command/SimpleCommand.kt
674158577
// This file was automatically generated from polymorphism.md by Knit tool. Do not edit. package example.examplePoly14 import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* val module = SerializersModule { polymorphic(Any::class) { subclass(OwnedProject::class) } } val format = Json { serializersModule = module } @Serializable abstract class Project { abstract val name: String } @Serializable @SerialName("owned") class OwnedProject(override val name: String, val owner: String) : Project() fun main() { val data: Any = OwnedProject("kotlinx.coroutines", "kotlin") println(format.encodeToString(PolymorphicSerializer(Any::class), data)) }
guide/example/example-poly-14.kt
1311063466
package ca.six.daily.biz.aboutme import ca.six.daily.core.network.HttpEngine import ca.six.daily.data.CheckUpdateResponse import io.reactivex.Observable class AboutMePresenter(val view: IAboutMeView) { fun checkForUpdate() { HttpEngine.request("version/android/2.5.0") .flatMap { jsonString -> println("szw : resp = ${jsonString}") val resp: CheckUpdateResponse = CheckUpdateResponse(jsonString) if (resp.isNoUpdate) { Observable.error(NoUpdateException("No new app version.")) } else { Observable.just(resp) } } .subscribe( /* onNext */ { resp -> view.showUpdateMessage(resp) }, /* onError */ { view.showNoUpdate() } ) } } // latest : {"status":0,"latest":"2.6.0"} /* // old { "status": 1, "msg": "【更新】\r\n\r\n- 极大提升性能及稳定性\r\n- 部分用户无法使用新浪微博登录\r\n- 部分用户无图模式无法分享至微信及朋友圈", "url": "http://zhstatic.zhihu.com/pkg/store/daily/zhihu-daily-zhihu-2.6.0(744)-release.apk", "latest": "2.6.0" } */
app/src/main/java/ca/six/daily/biz/aboutme/AboutMePresenter.kt
1672986125
package flavor.pie.pieconomy import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.LoadingCache import com.google.common.collect.ImmutableList import flavor.pie.kludge.* import org.spongepowered.api.service.context.ContextCalculator import org.spongepowered.api.service.economy.Currency import org.spongepowered.api.service.economy.EconomyService import org.spongepowered.api.service.economy.account.Account import org.spongepowered.api.service.economy.account.UniqueAccount import java.util.Optional import java.util.UUID import java.util.concurrent.TimeUnit class PieconomyService : EconomyService { val cache: LoadingCache<UUID, PieconomyPlayerAccount> = Caffeine.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES).build(::PieconomyPlayerAccount) val serverAccounts: MutableMap<String, PieconomyServerAccount> = HashMap() override fun getOrCreateAccount(uuid: UUID): Optional<UniqueAccount> = cache[uuid].optional override fun getOrCreateAccount(identifier: String): Optional<Account> = (serverAccounts.values.firstOrNull { it.name == identifier } ?: if (config.serverAccounts.dynamicAccounts.enable) { PieconomyServerAccount(identifier, currencies = ImmutableList.copyOf(currencies.filter( if (config.serverAccounts.dynamicAccounts.currencies.type == ServerAccountCurrencyType.BLACKLIST) { { c -> c !in config.serverAccounts.dynamicAccounts.currencies.values } } else { { c -> c in config.serverAccounts.dynamicAccounts.currencies.values } } )), negativeValues = ImmutableList.copyOf(currencies.filter( if (config.serverAccounts.dynamicAccounts.negativeValues.type == ServerAccountCurrencyType.BLACKLIST) { { c -> c !in config.serverAccounts.dynamicAccounts.negativeValues.values } } else { { c -> c in config.serverAccounts.dynamicAccounts.negativeValues.values } } ))) } else { null }).optional override fun registerContextCalculator(calculator: ContextCalculator<Account>?) {} override fun getDefaultCurrency(): Currency = config.defaultCurrency override fun getCurrencies(): Set<Currency> = GameRegistry.getAllOf(Currency::class.java).toSet() override fun hasAccount(uuid: UUID): Boolean = uuid.user() != null override fun hasAccount(identifier: String): Boolean = serverAccounts.values.any { it.name == identifier } }
src/main/kotlin/flavor/pie/pieconomy/PieconomyService.kt
3872405246
package com.google.androidstudiopoet.generators.bazel import com.google.androidstudiopoet.testutils.assertEquals import org.junit.Test class BazelLangTest { @Test fun `assignment statement is converted to string correctly`() { val stmt = AssignmentStatement("foo", "\"bar\"") stmt.toString().assertEquals("foo = \"bar\"") } @Test fun `load statement is converted to string correctly`() { val stmt = LoadStatement("@foo//bar:baz.bzl", listOf("foo", "bar")) stmt.toString().assertEquals("""load("@foo//bar:baz.bzl", "foo", "bar")""") } @Test fun `comment is converted to string correctly`() { val comment = Comment("Foo bar baz") comment.toString().assertEquals("# Foo bar baz") } @Test fun `raw attribute is converted to string correctly`() { val attr = RawAttribute("foo", "[1, 2, 3]") attr.toString().assertEquals("foo = [1, 2, 3]") } @Test fun `string attribute is converted to string correctly`() { val attr = StringAttribute("foo", "bar") attr.toString().assertEquals("foo = \"bar\"") } @Test fun `target without attributes is converted to string correctly`() { val target = Target("foo_bar", listOf()) target.toString().assertEquals("foo_bar()") } @Test fun `target with one attribute is converted to string correctly`() { val target = Target("foo_bar", listOf(RawAttribute("baz", "42"))) target.toString().assertEquals("""foo_bar( baz = 42, )""") } @Test fun `target with two attributes is converted to string correctly`() { val target = Target( "foo_bar", listOf( RawAttribute("baz", "42"), StringAttribute("qux", "foo") )) target.toString().assertEquals("""foo_bar( baz = 42, qux = "foo", )""") } }
aspoet/src/test/kotlin/com/google/androidstudiopoet/generators/bazel/BazelLangTest.kt
1765759921
package fr.geobert.radis.ui import android.content.SharedPreferences import android.database.Cursor import android.os.Bundle import android.preference.CheckBoxPreference import android.preference.EditTextPreference import android.preference.ListPreference import android.preference.PreferenceManager import android.support.v4.app.LoaderManager import android.support.v4.content.Loader import android.support.v4.preference.PreferenceFragment import android.util.Log import android.view.View import fr.geobert.radis.R import fr.geobert.radis.data.AccountConfig import fr.geobert.radis.db.AccountTable import fr.geobert.radis.db.DbContentProvider import fr.geobert.radis.db.PreferenceTable import fr.geobert.radis.tools.DBPrefsManager import fr.geobert.radis.tools.map import fr.geobert.radis.ui.editor.AccountEditor import kotlin.properties.Delegates public class ConfigFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener, LoaderManager.LoaderCallbacks<Cursor> { // only in global prefs, it is lazy so no crash in AccountEditor private val mAccountsChoice by lazy(LazyThreadSafetyMode.NONE) { findPreference(KEY_DEFAULT_ACCOUNT) as ListPreference } //TODO lazy access to prefs in AccountEditor mode private val mOverInsertDate by lazy(LazyThreadSafetyMode.NONE) { findPreference(KEY_OVERRIDE_INSERT_DATE) as CheckBoxPreference } private val isAccountEditor by lazy(LazyThreadSafetyMode.NONE) { activity is AccountEditor } private var mOnRestore: Boolean = false var mConfig: AccountConfig by Delegates.notNull() private set override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(if (isAccountEditor) R.xml.account_prefs else R.xml.preferences) if (!isAccountEditor) // do not call account spinner init, it does not exist initAccountChoices() } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isAccountEditor) { // change only in account editor, because de listView is not match_parent listView.setBackgroundColor(resources.getColor(R.color.normal_bg)) val act = activity as AccountEditor if (act.isNewAccount()) { mConfig = AccountConfig() } } if (savedInstanceState != null) onRestoreInstanceState(savedInstanceState) } private fun getPrefs(): DBPrefsManager { return DBPrefsManager.getInstance(activity) } private fun notEmpty(s: String?): String? { if (s != null && s.trim().length == 0) { return null } return s } private fun initAccountChoices() { val accounts = activity.contentResolver.query(DbContentProvider.ACCOUNT_URI, AccountTable.ACCOUNT_ID_AND_NAME_COLS, null, null, null) if (accounts.moveToFirst()) { val entries = accounts.map { it.getString(it.getColumnIndex(AccountTable.KEY_ACCOUNT_NAME)) }.toTypedArray() val values = accounts.map { it.getString(it.getColumnIndex(AccountTable.KEY_ACCOUNT_ROWID)) }.toTypedArray() mAccountsChoice.entries = entries mAccountsChoice.entryValues = values } accounts.close() } fun updateLabel(key: String, account: AccountConfig? = null) { val summary = when (key) { getKey(KEY_INSERTION_DATE) -> { val value = if (account != null) account.insertDate.toString() else getPrefs().getString(key, DEFAULT_INSERTION_DATE) val s = getString(R.string.prefs_insertion_date_text) s.format(value) } getKey(KEY_NB_MONTH_AHEAD) -> { val value = if (account != null) account.nbMonthsAhead else getPrefs().getInt(key, DEFAULT_NB_MONTH_AHEAD) getString(R.string.prefs_nb_month_ahead_text).format(value) } getKey(KEY_QUICKADD_ACTION) -> { val valueIdx = if (account != null) account.quickAddAction else getPrefs().getInt(key, DEFAULT_QUICKADD_LONG_PRESS_ACTION) val value = activity.resources.getStringArray(R.array.quickadd_actions)[valueIdx] getString(R.string.quick_add_long_press_action_text).format(value) } KEY_DEFAULT_ACCOUNT -> { // !isAccountEditor only val l = findPreference(key) as ListPreference val s = l.entry if (null != s) { val value = s.toString() getString(R.string.default_account_desc, value) } else { null } } else -> null } if (summary != null) { val ps = preferenceScreen if (ps != null) { ps.findPreference(key)?.summary = summary } } } fun getKey(k: String) = if (isAccountEditor) "${k}_for_account" else k override fun onResume() { super.onResume() val act = activity PreferenceManager.getDefaultSharedPreferences(act).registerOnSharedPreferenceChangeListener(this) if (!isAccountEditor) { var value: String? = getPrefs().getString(KEY_INSERTION_DATE, DEFAULT_INSERTION_DATE) val ep = findPreference(KEY_INSERTION_DATE) as EditTextPreference ep.editText.setText(value) value = getPrefs().getString(KEY_DEFAULT_ACCOUNT) if (value != null) { for (s in mAccountsChoice.entryValues) { if (value == s) { mAccountsChoice.value = s.toString() } } } updateLabel(KEY_DEFAULT_ACCOUNT) updateLabel(KEY_INSERTION_DATE) updateLabel(KEY_NB_MONTH_AHEAD) updateLabel(KEY_QUICKADD_ACTION) } else if (act is AccountEditor) { if (!mOnRestore && !act.isNewAccount()) { act.supportLoaderManager.initLoader<Cursor>(AccountEditor.GET_ACCOUNT_CONFIG, Bundle(), this) } else { mOnRestore = false } if (act.isNewAccount()) { updateLabel(KEY_INSERTION_DATE) updateLabel(KEY_NB_MONTH_AHEAD) updateLabel(KEY_QUICKADD_ACTION) } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (isAccountEditor) outState.putParcelable("mConfig", mConfig) mOnRestore = true } private fun onRestoreInstanceState(state: Bundle) { mOnRestore = true if (isAccountEditor) mConfig = state.getParcelable<AccountConfig>("mConfig") } private fun setCheckBoxPrefState(key: String, value: Boolean) { val checkbox = findPreference(key) as CheckBoxPreference checkbox.isChecked = value PreferenceManager.getDefaultSharedPreferences(activity).edit().putBoolean(key, value) } private fun setEditTextPrefValue(key: String, value: String) { val edt = findPreference(key) as EditTextPreference edt.editText.setText(value) PreferenceManager.getDefaultSharedPreferences(activity).edit().putString(key, value) } private fun setListPrefValue(key: String, value: Int) { val l = findPreference(key) as ListPreference l.setValueIndex(value) PreferenceManager.getDefaultSharedPreferences(activity).edit().putInt(key, value) } public fun populateFields(account: AccountConfig) { setCheckBoxPrefState(KEY_OVERRIDE_INSERT_DATE, account.overrideInsertDate) setCheckBoxPrefState(KEY_OVERRIDE_HIDE_QUICK_ADD, account.overrideHideQuickAdd) setCheckBoxPrefState(KEY_OVERRIDE_USE_WEIGHTED_INFO, account.overrideUseWeighedInfo) setCheckBoxPrefState(KEY_OVERRIDE_INVERT_QUICKADD_COMPLETION, account.overrideInvertQuickAddComp) setCheckBoxPrefState(KEY_OVERRIDE_NB_MONTH_AHEAD, account.overrideNbMonthsAhead) setEditTextPrefValue(getKey(KEY_INSERTION_DATE), account.insertDate.toString()) setEditTextPrefValue(getKey(KEY_NB_MONTH_AHEAD), account.nbMonthsAhead.toString()) setListPrefValue(getKey(KEY_QUICKADD_ACTION), account.quickAddAction) updateLabel(getKey(KEY_INSERTION_DATE), account) updateLabel(getKey(KEY_NB_MONTH_AHEAD), account) updateLabel(getKey(KEY_QUICKADD_ACTION), account) setCheckBoxPrefState(getKey(KEY_HIDE_OPS_QUICK_ADD), account.hideQuickAdd) setCheckBoxPrefState(getKey(KEY_USE_WEIGHTED_INFOS), account.useWeighedInfo) setCheckBoxPrefState(getKey(KEY_INVERT_COMPLETION_IN_QUICK_ADD), account.invertQuickAddComp) PreferenceManager.getDefaultSharedPreferences(activity).edit().commit() } private fun getCheckBoxPrefValue(key: String): Boolean { val chk = findPreference(key) as CheckBoxPreference val r = chk.isChecked return r } private fun getEdtPrefValue(key: String): String { val edt = findPreference(key) as EditTextPreference val r = edt.editText.text.toString() return r } private fun getListPrefValue(key: String): Int { val l = findPreference(key) as ListPreference return l.value.toInt() } // called by AccountEditFragment.saveState fun fillConfig(): AccountConfig { mConfig.overrideInsertDate = getCheckBoxPrefValue(KEY_OVERRIDE_INSERT_DATE) val d = getEdtPrefValue(getKey(KEY_INSERTION_DATE)) mConfig.insertDate = if (d.trim().length > 0) d.toInt() else DEFAULT_INSERTION_DATE.toInt() mConfig.overrideHideQuickAdd = getCheckBoxPrefValue(KEY_OVERRIDE_HIDE_QUICK_ADD) mConfig.hideQuickAdd = getCheckBoxPrefValue(getKey(KEY_HIDE_OPS_QUICK_ADD)) mConfig.overrideUseWeighedInfo = getCheckBoxPrefValue(KEY_OVERRIDE_USE_WEIGHTED_INFO) mConfig.useWeighedInfo = getCheckBoxPrefValue(getKey(KEY_USE_WEIGHTED_INFOS)) mConfig.overrideInvertQuickAddComp = getCheckBoxPrefValue(KEY_OVERRIDE_INVERT_QUICKADD_COMPLETION) mConfig.invertQuickAddComp = getCheckBoxPrefValue(getKey(KEY_INVERT_COMPLETION_IN_QUICK_ADD)) mConfig.overrideNbMonthsAhead = getCheckBoxPrefValue(KEY_OVERRIDE_NB_MONTH_AHEAD) val m = getEdtPrefValue(getKey(KEY_NB_MONTH_AHEAD)) mConfig.nbMonthsAhead = if (m.trim().length > 0) m.toInt() else DEFAULT_NB_MONTH_AHEAD mConfig.overrideQuickAddAction = getCheckBoxPrefValue(KEY_OVERRIDE_QUICKADD_ACTION) mConfig.quickAddAction = getListPrefValue(getKey(KEY_QUICKADD_ACTION)) return mConfig } override fun onPause() { super.onPause() val act = activity PreferenceManager.getDefaultSharedPreferences(act).unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { val p = findPreference(key) val value = if (p is EditTextPreference) { notEmpty(sharedPreferences.getString(key, null)) } else if (p is ListPreference) { p.value } else if (p is CheckBoxPreference) { java.lang.Boolean.toString(p.isChecked) } else { "" } getPrefs().put(key, value) // put "_for_account" keys in cache for updateLabel updateLabel(key) } override fun onCreateLoader(id: Int, args: Bundle): Loader<Cursor> { val act = activity as AccountEditor return PreferenceTable.getAccountConfigLoader(act, act.mRowId) } override fun onLoadFinished(arg0: Loader<Cursor>, data: Cursor) { if (data.moveToFirst()) { mConfig = AccountConfig(data) populateFields(mConfig) } else { mConfig = AccountConfig() } } override fun onLoaderReset(arg0: Loader<Cursor>) { } companion object { public val KEY_OVERRIDE_INSERT_DATE: String = "override_insertion_date" public val KEY_OVERRIDE_HIDE_QUICK_ADD: String = "override_hide_quickadd" public val KEY_OVERRIDE_USE_WEIGHTED_INFO: String = "override_use_weighted_info" public val KEY_OVERRIDE_INVERT_QUICKADD_COMPLETION: String = "override_invert_quickadd_completion" public val KEY_OVERRIDE_QUICKADD_ACTION: String = "override_quick_add_long_press_action" public val KEY_INSERTION_DATE: String = "insertion_date" public val KEY_LAST_INSERTION_DATE: String = "LAST_INSERT_DATE" public val KEY_DEFAULT_ACCOUNT: String = "quickadd_account" public val KEY_HIDE_OPS_QUICK_ADD: String = "hide_ops_quick_add" public val KEY_USE_WEIGHTED_INFOS: String = "use_weighted_infos" public val KEY_INVERT_COMPLETION_IN_QUICK_ADD: String = "invert_completion_in_quick_add" public val KEY_OVERRIDE_NB_MONTH_AHEAD: String = "override_nb_month_ahead" public val KEY_NB_MONTH_AHEAD: String = "nb_month_ahead" public val KEY_QUICKADD_ACTION: String = "quick_add_long_press_action" public val DEFAULT_INSERTION_DATE: String = "25" public val DEFAULT_NB_MONTH_AHEAD: Int = 1 public val DEFAULT_QUICKADD_LONG_PRESS_ACTION: Int = 0 } }
app/src/main/kotlin/fr/geobert/radis/ui/ConfigFragment.kt
1811974357
package net.ndrei.teslapoweredthingies.machines.compoundmaker import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.item.EnumDyeColor import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagString import net.minecraft.util.ResourceLocation import net.minecraftforge.common.util.Constants import net.minecraftforge.fluids.IFluidTank import net.minecraftforge.items.IItemHandlerModifiable import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.FluidTankType import net.ndrei.teslacorelib.inventory.SyncProviderLevel import net.ndrei.teslacorelib.netsync.SimpleNBTMessage import net.ndrei.teslapoweredthingies.TeslaThingiesMod import net.ndrei.teslapoweredthingies.common.gui.IMultiTankMachine import net.ndrei.teslapoweredthingies.common.gui.TankInfo import net.ndrei.teslapoweredthingies.machines.BaseThingyMachine import net.ndrei.teslapoweredthingies.render.DualTankEntityRenderer import java.util.function.Consumer import java.util.function.Supplier class CompoundMakerEntity : BaseThingyMachine(CompoundMakerEntity::class.java.name.hashCode()), IMultiTankMachine { private lateinit var leftFluid: IFluidTank private lateinit var rightFluid: IFluidTank private lateinit var topInventory: IItemHandlerModifiable private lateinit var bottomInventory: IItemHandlerModifiable private lateinit var outputInventory: IItemHandlerModifiable //#region inventory & gui override fun initializeInventories() { this.leftFluid = this.addSimpleFluidTank(5000, "Left Tank", EnumDyeColor.BLUE, 52, 25, FluidTankType.INPUT, { fluid -> CompoundMakerRegistry.acceptsLeft(fluid) }) this.topInventory = this.addSimpleInventory(3, "input_top", EnumDyeColor.GREEN, "Top Inputs", BoundingRectangle.slots(70, 22, 3, 1), { stack, _ -> CompoundMakerRegistry.acceptsTop(stack)}, { _, _ -> false }, true) this.bottomInventory = this.addSimpleInventory(3, "input_bottom", EnumDyeColor.BROWN, "Bottom Inputs", BoundingRectangle.slots(70, 64, 3, 1), { stack, _ -> CompoundMakerRegistry.acceptsBottom(stack) }, { _, _ -> false }, true) this.rightFluid = this.addSimpleFluidTank(5000, "Right Tank", EnumDyeColor.PURPLE, 124, 25, FluidTankType.INPUT, { fluid -> CompoundMakerRegistry.acceptsRight(fluid) }) this.outputInventory = this.addSimpleInventory(1, "output", EnumDyeColor.ORANGE, "Output", BoundingRectangle.slots(88, 43, 1, 1), { _, _ -> false }, { _, _ -> true }, false) super.registerSyncStringPart(SYNC_CURRENT_RECIPE, Consumer { this.currentRecipe = if (it.string.isNotEmpty()) CompoundMakerRegistry.getRecipe(ResourceLocation(it.string)) else null }, Supplier { NBTTagString(if (this.currentRecipe != null) this.currentRecipe!!.registryName.toString() else "") }, SyncProviderLevel.GUI) super.registerSyncStringPart(SYNC_LOCKED_RECIPE, Consumer { this.lockedRecipe = if (it.string.isNotEmpty()) CompoundMakerRegistry.getRecipe(ResourceLocation(it.string)) else null }, Supplier { NBTTagString(if (this.lockedRecipe != null) this.lockedRecipe!!.registryName.toString() else "") }, SyncProviderLevel.GUI) super.registerSyncStringPart(SYNC_RECIPE_MODE, Consumer { this.recipeMode = RecipeRunType.valueOf(it.string) }, Supplier { NBTTagString(this.recipeMode.name) }, SyncProviderLevel.GUI) super.initializeInventories() } override fun shouldAddFluidItemsInventory() = false override fun getRenderers() = super.getRenderers().also { it.add(DualTankEntityRenderer) } override fun getTanks() = listOf( TankInfo(4.0, 8.0, this.leftFluid.fluid, this.leftFluid.capacity), TankInfo(22.0, 8.0, this.rightFluid.fluid, this.rightFluid.capacity) ) override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>) = super.getGuiContainerPieces(container).also { // it.add(BasicRenderedGuiPiece(70, 40, 54, 24, // ThingiesTexture.MACHINES_TEXTURES.resource, 5, 105)) CompoundMakerIcon.CENTER_BACKGROUND.addStaticPiece(it, 70,40) it.add(CompoundRecipeSelectorPiece(this)) it.add(CompoundRecipeButtonPiece(this, CompoundRecipeButtonPiece.Direction.UP, top = 25)) it.add(CompoundRecipeButtonPiece(this, CompoundRecipeButtonPiece.Direction.DOWN, top = 52)) it.add(CompoundRecipeTriggerPiece(this)) } //#endregion //#region selected recipe methods private var _availableRecipes: List<CompoundMakerRecipe>? = null private var recipeMode = RecipeRunType.PAUSED private var recipeIndex = 0 private var currentRecipe: CompoundMakerRecipe? = null private var lockedRecipe: CompoundMakerRecipe? = null override fun onSyncPartUpdated(key: String) { if (key in arrayOf("input_top", "input_bottom", "fluids")) { this._availableRecipes = null } // TeslaThingiesMod.logger.info("UPDATED: ${key}") } val availableRecipes: List<CompoundMakerRecipe> get() { if (this._availableRecipes == null) this._availableRecipes = CompoundMakerRegistry.findRecipes(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory) return this._availableRecipes ?: listOf() } val hasCurrentRecipe get() = (this.currentRecipe != null) || (this.lockedRecipe != null) val selectedRecipe: CompoundMakerRecipe? get() = this.currentRecipe ?: this.lockedRecipe ?: this.availableRecipes.let { if (it.isEmpty()) null else it[this.recipeIndex % it.size] } var selectedRecipeIndex: Int get() = this.availableRecipes.let { if (it.isEmpty()) 0 else (this.recipeIndex % it.size) } set(value) { if (value in this.availableRecipes.indices) { this.recipeIndex = value if (this.world?.isRemote == true) { this.sendToServer(this.setupSpecialNBTMessage("SET_RECIPE_INDEX").also { it.setInteger("recipe_index", this.recipeIndex) }) } } } var selectedRecipeMode: RecipeRunType get() = this.recipeMode set(value) { if (this.recipeMode != value) { this.recipeMode = value if (this.recipeMode != RecipeRunType.PAUSED) { this.setLockedRecipe(this.selectedRecipe) } else { this.setLockedRecipe(null) } if (this.world?.isRemote == true) { this.sendToServer(this.setupSpecialNBTMessage("SET_RECIPE_MODE").also { it.setInteger("recipe_mode", this.recipeMode.ordinal) }) } else { this.partialSync(CompoundMakerEntity.SYNC_RECIPE_MODE) } } } private fun setLockedRecipe(recipe: CompoundMakerRecipe?) { if (this.lockedRecipe?.registryName != recipe?.registryName) { this.lockedRecipe = recipe if (this.world?.isRemote == false) { this.partialSync(CompoundMakerEntity.SYNC_LOCKED_RECIPE) } } } override fun processClientMessage(messageType: String?, player: EntityPlayerMP?, compound: NBTTagCompound): SimpleNBTMessage? { when(messageType) { "SET_RECIPE_INDEX" -> { if (compound.hasKey("recipe_index", Constants.NBT.TAG_INT)) { this.selectedRecipeIndex = compound.getInteger("recipe_index") } return null } "SET_RECIPE_MODE" -> { if (compound.hasKey("recipe_mode", Constants.NBT.TAG_INT)) { this.selectedRecipeMode = RecipeRunType.byOrdinal(compound.getInteger("recipe_mode")) } return null } } return super.processClientMessage(messageType, player, compound) } enum class RecipeRunType(val langKey: String) { PAUSED("Machine Paused"), SINGLE("Make Single Item"), ALL("Make Maximum Items"), LOCK("Lock Recipe"); val next get() = RecipeRunType.values()[(this.ordinal + 1) % RecipeRunType.values().size] companion object { fun byOrdinal(ordinal: Int) = RecipeRunType.values()[ordinal % RecipeRunType.values().size] } } //#endregion override fun getEnergyRequiredForWork(): Long { if (this.recipeMode != RecipeRunType.PAUSED) { if (this.lockedRecipe?.matches(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory) == true) { this.currentRecipe = this.lockedRecipe TeslaThingiesMod.logger.info("Current Recipe: ${this.currentRecipe!!.registryName}") this.currentRecipe!!.processInventories(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory) return super.getEnergyRequiredForWork() } } return 0L } override fun performWork(): Float { if (this.currentRecipe != null) { val stack = this.currentRecipe!!.output.copy() if (this.outputInventory.insertItem(0, stack, true).isEmpty) { this.outputInventory.insertItem(0, stack, false) when (this.recipeMode) { RecipeRunType.SINGLE -> { this.selectedRecipeMode = RecipeRunType.PAUSED } RecipeRunType.ALL -> { if (!this.currentRecipe!!.matches(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory)) { this.selectedRecipeMode = RecipeRunType.PAUSED } } else -> { } } TeslaThingiesMod.logger.info("Current Recipe: [null]; Locked Recipe: ${this.lockedRecipe?.registryName}") this.currentRecipe = null this.partialSync(SYNC_CURRENT_RECIPE) return 1.0f } } return 0.0f } companion object { const val SYNC_CURRENT_RECIPE = "current_recipe" const val SYNC_LOCKED_RECIPE = "locked_recipe" const val SYNC_RECIPE_MODE = "recipe_mode" } }
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/compoundmaker/CompoundMakerEntity.kt
1718791011
package com.pr0gramm.app.util import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.database.sqlite.SQLiteFullException import android.graphics.Point import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.os.Build import android.os.Looper import android.text.SpannableStringBuilder import android.text.style.BulletSpan import android.text.style.LeadingMarginSpan import android.util.LruCache import android.view.View import android.view.WindowInsets import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources import androidx.core.app.TaskStackBuilder import androidx.core.content.getSystemService import androidx.core.content.res.ResourcesCompat import androidx.core.content.res.use import androidx.core.graphics.drawable.DrawableCompat import androidx.core.net.ConnectivityManagerCompat import androidx.core.text.inSpans import androidx.core.view.postDelayed import com.google.firebase.crashlytics.FirebaseCrashlytics import com.pr0gramm.app.BuildConfig import com.pr0gramm.app.Logger import com.pr0gramm.app.R import com.pr0gramm.app.debugConfig import com.pr0gramm.app.ui.PermissionHelperDelegate import com.pr0gramm.app.ui.base.AsyncScope import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.launch import retrofit2.HttpException import java.io.IOException import java.io.PrintWriter import java.io.StringWriter /** * Place to put everything that belongs nowhere. Thanks Obama. */ object AndroidUtility { private val logger = Logger("AndroidUtility") private val EXCEPTION_BLACKLIST = listOf("MediaCodec", "dequeueInputBuffer", "dequeueOutputBuffer", "releaseOutputBuffer", "native_") private val cache = LruCache<Int, Unit>(6) /** * Gets the height of the action bar as definied in the style attribute * [R.attr.actionBarSize] plus the height of the status bar on android * Kitkat and above. * @param context A context to resolve the styled attribute value for */ fun getActionBarContentOffset(context: Context): Int { return getStatusBarHeight(context) + getActionBarHeight(context) } /** * Gets the height of the actionbar. */ private fun getActionBarHeight(context: Context): Int { context.obtainStyledAttributes(intArrayOf(R.attr.actionBarSize)).use { ta -> return ta.getDimensionPixelSize(ta.getIndex(0), -1) } } /** * Gets the height of the statusbar. */ fun getStatusBarHeight(context: Context): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val window = activityFromContext(context)?.window val rootWindowInsets = window?.decorView?.rootWindowInsets if (rootWindowInsets != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // this seems to be always correct on android 11 and better. return rootWindowInsets .getInsetsIgnoringVisibility(WindowInsets.Type.statusBars()) .top } // this works for android 6 and above return rootWindowInsets.stableInsetTop } } // use the old code as fallback in case we have a really old android // or if we don't have a window or decorView var result = 0 val resources = context.resources val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId) } return result } fun logToCrashlytics(error: Throwable?, force: Boolean = false) { val causalChain = error?.causalChain ?: return if (causalChain.containsType<CancellationException>()) { return } if (!force) { if (causalChain.containsType<PermissionHelperDelegate.PermissionNotGranted>()) { return } if (causalChain.containsType<IOException>() || causalChain.containsType<HttpException>()) { logger.warn(error) { "Ignoring network exception" } return } if (causalChain.containsType<SQLiteFullException>()) { logger.warn { "Database is full: $error" } return } } try { val trace = StringWriter().also { w -> error.printStackTrace(PrintWriter(w)) }.toString() if (EXCEPTION_BLACKLIST.any { word -> word in trace }) { logger.warn("Ignoring exception", error) return } val errorStr = error.toString() if ("connect timed out" in errorStr) { return } // try to rate limit exceptions. val key = System.identityHashCode(error) if (cache.get(key) != null) { return } else { cache.put(key, Unit) } ignoreAllExceptions { FirebaseCrashlytics.getInstance().recordException(error) } } catch (err: Throwable) { logger.warn(err) { "Could not send error $error to crash tool" } } } fun isOnMobile(context: Context?): Boolean { context ?: return false val cm = context.getSystemService( Context.CONNECTIVITY_SERVICE ) as ConnectivityManager return ConnectivityManagerCompat.isActiveNetworkMetered(cm) } /** * Gets the color tinted hq-icon */ fun getTintedDrawable(context: Context, @DrawableRes drawableId: Int, @ColorRes colorId: Int): Drawable { val resources = context.resources val icon = DrawableCompat.wrap(AppCompatResources.getDrawable(context, drawableId)!!) DrawableCompat.setTint(icon, ResourcesCompat.getColor(resources, colorId, null)) return icon } /** * Returns a CharSequence containing a bulleted and properly indented list. * @param leadingMargin In pixels, the space between the left edge of the bullet and the left edge of the text. * * * @param lines An array of CharSequences. Each CharSequences will be a separate line/bullet-point. */ fun makeBulletList(leadingMargin: Int, lines: List<CharSequence>): CharSequence { return SpannableStringBuilder().apply { for (idx in lines.indices) { inSpans(BulletSpan(leadingMargin / 3)) { inSpans(LeadingMarginSpan.Standard(leadingMargin)) { append(lines[idx]) } } val last = idx == lines.lastIndex append(if (last) "" else "\n") } } } fun buildVersionCode(): Int { return if (BuildConfig.DEBUG) { debugConfig.versionOverride ?: BuildConfig.VERSION_CODE } else { BuildConfig.VERSION_CODE } } fun showSoftKeyboard(view: EditText?) { view?.postDelayed(100) { try { view.requestFocus() val imm = view.context.getSystemService<InputMethodManager>() imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) } catch (err: Exception) { logger.warn(err) { "Failed to show soft keyboard" } } } } fun hideSoftKeyboard(view: View?) { if (view != null) { try { val imm = view.context.getSystemService<InputMethodManager>() imm?.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } catch (err: Exception) { logger.warn(err) { "Failed to hide soft keyboard" } } } } fun recreateActivity(activity: Activity) { val intent = Intent(activity.intent) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK TaskStackBuilder.create(activity) .addNextIntentWithParentStack(intent) .startActivities() } fun applyWindowFullscreen(activity: Activity, fullscreen: Boolean) { var flags = 0 if (fullscreen) { flags = flags or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION flags = flags or (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_FULLSCREEN) flags = flags or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY } val decorView = activity.window.decorView decorView.systemUiVisibility = flags } fun screenSize(activity: Activity): Point { val screenSize = Point() val display = activity.windowManager.defaultDisplay display.getRealSize(screenSize) return screenSize } fun screenIsLandscape(activity: Activity?): Boolean { if (activity == null) { return false } val size = screenSize(activity) return size.x > size.y } /** * Tries to get a basic activity from the given context. Returns an empty observable, * if no activity could be found. */ fun activityFromContext(context: Context): Activity? { if (context is Activity) return context if (context is ContextWrapper) return activityFromContext(context.baseContext) return null } @ColorInt fun resolveColorAttribute(context: Context, attr: Int): Int { val arr = context.obtainStyledAttributes(intArrayOf(attr)) try { return arr.getColor(arr.getIndex(0), 0) } finally { arr.recycle() } } } @Suppress("NOTHING_TO_INLINE") inline fun checkMainThread() = debugOnly { if (Looper.getMainLooper().thread !== Thread.currentThread()) { Logger("AndroidUtility").error { "Expected to be in main thread but was: ${Thread.currentThread().name}" } throw IllegalStateException("Must be called from the main thread.") } } @Suppress("NOTHING_TO_INLINE") inline fun checkNotMainThread(msg: String? = null) = debugOnly { if (Looper.getMainLooper().thread === Thread.currentThread()) { Logger("AndroidUtility").error { "Expected not to be on main thread: $msg" } throw IllegalStateException("Must not be called from the main thread: $msg") } } inline fun <T> doInBackground(crossinline action: suspend () -> T): Job { return AsyncScope.launch { try { action() } catch (thr: Throwable) { // log it AndroidUtility.logToCrashlytics(BackgroundThreadException(thr)) } } } class BackgroundThreadException(cause: Throwable) : RuntimeException(cause) fun Throwable.getMessageWithCauses(): String { val error = this val type = javaClass.name .replaceFirst(".+\\.".toRegex(), "") .replace('$', '.') val cause = error.cause val hasCause = cause != null && error !== cause val message = error.message ?: "" val hasMessage = message.isNotBlank() && ( !hasCause || (cause != null && cause.javaClass.directName !in message)) return if (hasMessage) { if (hasCause && cause != null) { "$type(${error.message}), caused by ${cause.getMessageWithCauses()}" } else { "$type(${error.message})" } } else { if (hasCause && cause != null) { "$type, caused by ${cause.getMessageWithCauses()}" } else { type } } }
app/src/main/java/com/pr0gramm/app/util/AndroidUtility.kt
2642203087
package rxreddit.model import com.google.gson.annotations.SerializedName data class Link( @SerializedName("data") internal val data: Data, ) : Listing(), Votable, Savable, Hideable { override val id: String get() = data.id val domain: String? get() = data.domain val mediaEmbed: MediaEmbed? get() = data.mediaEmbed val subreddit: String? get() = data.subreddit val selftextHtml: String? get() = data.selftextHtml val selftext: String? get() = data.selftext val edited: Boolean get() = when (data.edited) { "true" -> true "0", "false", null, -> false else -> false } override var liked: Boolean? by data::liked val userReports: List<UserReport>? get() = data.userReports val linkFlairText: Any? get() = data.linkFlairText val gilded: Int? get() = data.gilded override val archived: Boolean get() = data.isArchived ?: false val clicked: Boolean get() = data.clicked ?: false val author: String? get() = data.author val numComments: Int? get() = data.numComments var score: Int? by data::score override fun applyVote(direction: Int) { val scoreDiff = direction - likedScore data.liked = when (direction) { 0 -> null 1 -> true -1 -> false else -> null } if (data.score == null) return data.score = data.score?.plus(scoreDiff) ?: 0 } private val likedScore: Int get() = if (liked == null) 0 else if (liked == true) 1 else -1 val approvedBy: Any? get() = data.approvedBy val over18: Boolean get() = data.over18 ?: false override var hidden: Boolean get() = data.hidden ?: false set(value) { data.hidden = value } val thumbnail: String? get() = data.thumbnail val subredditId: String? get() = data.subredditId val isScoreHidden: Boolean get() = data.hideScore ?: false val linkFlairCssClass: Any? get() = data.linkFlairCssClass val authorFlairCssClass: Any? get() = data.authorFlairCssClass val downs: Int? get() = data.downs override var isSaved: Boolean get() = if (data.saved == null) false else data.saved!! set(value) { data.saved = value } val stickied: Boolean get() = data.stickied ?: false val isSelf: Boolean get() = data.isSelf ?: false val permalink: String? get() = data.permalink val created: Double? get() = data.created val url: String? get() = data.url val authorFlairText: Any? get() = data.authorFlairText val title: String? get() = data.title val createdUtc: Double? get() = data.createdUtc val distinguished: String? get() = data.distinguished val media: Media? get() = data.media val modReports: List<ModReport>? get() = data.modReports val visited: Boolean get() = data.visited ?: false val numReports: Any? get() = data.numReports val ups: Int? get() = data.ups val previewImages: List<Image>? get() = if (data.preview == null) null else data.preview.images val isGallery: Boolean get() = data.isGallery ?: false val galleryItems: List<GalleryItem> get() = if (data.isGallery == true) { data.galleryItems.items.mapNotNull { galleryItemJson -> return@mapNotNull data.mediaMetadata[galleryItemJson.mediaId]?.let { media -> GalleryItem( url = media.s.u, ) } } } else emptyList() data class Data( @SerializedName("preview") val preview: Preview? = null, @SerializedName("domain") val domain: String? = null, @SerializedName("banned_by") val bannedBy: String? = null, @SerializedName("media_embed") val mediaEmbed: MediaEmbed? = null, @SerializedName("subreddit") val subreddit: String? = null, @SerializedName("selftext_html") val selftextHtml: String? = null, @SerializedName("selftext") val selftext: String? = null, @SerializedName("edited") val edited: String?, // TODO: Remove mutability here @SerializedName("likes") var liked: Boolean? = null, @SerializedName("user_reports") val userReports: List<UserReport>? = null, @SerializedName("link_flair_text") val linkFlairText: String? = null, @SerializedName("gilded") val gilded: Int? = null, @SerializedName("archived") val isArchived: Boolean? = null, @SerializedName("clicked") val clicked: Boolean? = null, @SerializedName("author") val author: String? = null, @SerializedName("num_comments") val numComments: Int? = null, // TODO: Remove mutability here @SerializedName("score") var score: Int? = null, @SerializedName("approved_by") val approvedBy: String? = null, @SerializedName("over_18") val over18: Boolean? = null, // TODO: Remove mutability here @SerializedName("hidden") var hidden: Boolean? = null, @SerializedName("thumbnail") val thumbnail: String? = null, @SerializedName("subreddit_id") val subredditId: String? = null, @SerializedName("hide_score") val hideScore: Boolean? = null, @SerializedName("link_flair_css_class") val linkFlairCssClass: String? = null, @SerializedName("author_flair_css_class") val authorFlairCssClass: String? = null, @SerializedName("downs") val downs: Int? = null, // TODO: Remove mutability here @SerializedName("saved") var saved: Boolean? = null, @SerializedName("stickied") val stickied: Boolean? = null, @SerializedName("is_self") val isSelf: Boolean? = null, @SerializedName("permalink") val permalink: String? = null, @SerializedName("created") val created: Double? = null, @SerializedName("url") val url: String? = null, @SerializedName("author_flair_text") val authorFlairText: String? = null, @SerializedName("title") val title: String? = null, @SerializedName("created_utc") val createdUtc: Double? = null, @SerializedName("distinguished") val distinguished: String? = null, @SerializedName("media") val media: Media? = null, @SerializedName("mod_reports") val modReports: List<ModReport>? = null, @SerializedName("visited") val visited: Boolean? = null, @SerializedName("num_reports") val numReports: Int? = null, @SerializedName("ups") val ups: Int? = null, @SerializedName("is_gallery") val isGallery: Boolean? = null, @SerializedName("gallery_data") internal val galleryItems: GalleryItems, @SerializedName("media_metadata") internal val mediaMetadata: Map<String, MediaMetadata>, ) : ListingData() data class Preview( @SerializedName("images") val images: List<Image>? = emptyList(), ) }
library/src/main/java/rxreddit/model/Link.kt
3431398872
package com.codegy.aerlink.service.media.model sealed class MediaEntity(val value: Byte) { object Player: MediaEntity(0) { enum class Attribute(val value: Byte) { Name(0), PlaybackInfo(1), Volume(2), Reserved(3); companion object { fun fromRaw(attributeId: Byte): Attribute { return values().getOrNull(attributeId.toInt()) ?: Reserved } } } } object Queue: MediaEntity(1) { enum class Attribute(val value: Byte) { Index(0), Count(1), ShuffleMode(2), RepeatMode(3), Reserved(4); companion object { fun fromRaw(attributeId: Byte): Attribute { return values().getOrNull(attributeId.toInt()) ?: Reserved } } } } object Track: MediaEntity(2) { enum class Attribute(val value: Byte) { Artist(0), Album(1), Title(2), Duration(3), Reserved(4); companion object { fun fromRaw(attributeId: Byte): Attribute { return values().getOrNull(attributeId.toInt()) ?: Reserved } } } } object Reserved: MediaEntity(4) companion object { fun fromRaw(entityId: Byte): MediaEntity { if (entityId >= Reserved.value) { return Reserved } return listOf(Player, Queue, Track, Reserved)[entityId.toInt()] } } }
wear/src/main/java/com/codegy/aerlink/service/media/model/MediaEntity.kt
3379481526
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.options.ConfigurableBase import com.intellij.openapi.options.ConfigurableUi import com.intellij.ui.layout.* import java.nio.file.Paths import javax.swing.JCheckBox internal class IcsConfigurable : ConfigurableBase<IcsConfigurableUi, IcsSettings>("ics", icsMessage("ics.settings"), "reference.settings.ics") { override fun getSettings() = if (ApplicationManager.getApplication().isUnitTestMode) IcsSettings() else icsManager.settings override fun createUi() = IcsConfigurableUi() } internal class IcsConfigurableUi : ConfigurableUi<IcsSettings>, Disposable { private val icsManager = if (ApplicationManager.getApplication().isUnitTestMode) IcsManager(Paths.get(PathManager.getConfigPath()).resolve("settingsRepository")) else org.jetbrains.settingsRepository.icsManager private val editors = listOf(createRepositoryListEditor(icsManager), createReadOnlySourcesEditor()) private val autoSync = JCheckBox("Auto Sync") override fun dispose() { icsManager.autoSyncManager.enabled = true } override fun reset(settings: IcsSettings) { // do not set in constructor to avoid icsManager.autoSyncManager.enabled = false autoSync.isSelected = settings.autoSync editors.forEach { it.reset(settings) } } override fun isModified(settings: IcsSettings) = autoSync.isSelected != settings.autoSync || editors.any { it.isModified(settings) } override fun apply(settings: IcsSettings) { settings.autoSync = autoSync.isSelected editors.forEach { if (it.isModified(settings)) { it.apply(settings) } } saveSettings(settings, icsManager.settingsFile) } override fun getComponent() = verticalPanel { editors.get(0).component() autoSync() hint("Use VCS -> Sync Settings to sync when you want") panel("Read-only Sources", editors.get(1).component) } }
plugins/settings-repository/src/IcsConfigurable.kt
2156807218
// see https://handstandsam.com/2018/02/11/kotlin-buildsrc-for-better-gradle-dependency-management/ // for an explanation of the idea object Ver { const val kotlin = "1.4.31" const val apache_http_core = "4.4.9" const val apache_http_client = "4.5.5" const val junit = "5.7.+" const val mockito_kotlin = "1.6.+" const val hamkrest = "1.8.+" const val hamcrest = "1.3" const val mockito = "2.28.2" } object Deps { const val kt_stdlib_jdk8 = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Ver.kotlin}" val apache_http_core = "org.apache.httpcomponents:httpcore:${Ver.apache_http_core}" val apache_http_client = "org.apache.httpcomponents:httpclient:${Ver.apache_http_client}" const val kotlin_reflect = "org.jetbrains.kotlin:kotlin-reflect:${Ver.kotlin}" const val junit = "org.junit.jupiter:junit-jupiter-api:${Ver.junit}" const val junit_engine = "org.junit.jupiter:junit-jupiter-engine:${Ver.junit}" const val mockito_kotlin = "com.nhaarman:mockito-kotlin:${Ver.mockito_kotlin}" const val hamkrest = "com.natpryce:hamkrest:${Ver.hamkrest}" const val hamcrest_integration = "org.hamcrest:hamcrest-integration:${Ver.hamcrest}" const val mockito_core = "org.mockito:mockito-core:${Ver.mockito}" const val mockito_junit_jupiter = "org.mockito:mockito-junit-jupiter:${Ver.mockito}" }
buildSrc/src/main/kotlin/Dependencies.kt
2352170487
/***************************************************************************** * NetworkProvider.kt ***************************************************************************** * Copyright © 2018 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.providers import android.content.Context import android.net.Uri import androidx.lifecycle.Observer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.withContext import org.videolan.libvlc.util.MediaBrowser import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.DummyItem import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.tools.NetworkMonitor import org.videolan.tools.livedata.LiveDataset import org.videolan.vlc.R @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class NetworkProvider(context: Context, dataset: LiveDataset<MediaLibraryItem>, url: String? = null, showHiddenFiles: Boolean): BrowserProvider(context, dataset, url, showHiddenFiles), Observer<List<MediaWrapper>> { override suspend fun browseRootImpl() { dataset.clear() dataset.value = mutableListOf() if (NetworkMonitor.getInstance(context).lanAllowed) browse() } override fun fetch() {} override suspend fun requestBrowsing(url: String?, eventListener: MediaBrowser.EventListener, interact : Boolean) = withContext(Dispatchers.IO) { initBrowser() mediabrowser?.let { it.changeEventListener(eventListener) if (url != null) it.browse(Uri.parse(url), getFlags(interact)) else it.discoverNetworkShares() } } override fun refresh() { val list by lazy(LazyThreadSafetyMode.NONE) { getList(url!!) } when { url == null -> { browseRoot() } list !== null -> { dataset.value = list as MutableList<MediaLibraryItem> removeList(url) parseSubDirectories() computeHeaders(list as MutableList<MediaLibraryItem>) } else -> super.refresh() } } override fun parseSubDirectories(list : List<MediaLibraryItem>?) { if (url != null) super.parseSubDirectories(list) } override fun stop() { if (url == null) clearListener() return super.stop() } override fun onChanged(favs: List<MediaWrapper>?) { val data = dataset.value.toMutableList() data.listIterator().run { while (hasNext()) { val item = next() if (item.hasStateFlags(MediaLibraryItem.FLAG_FAVORITE) || item is DummyItem) remove() } } dataset.value = data.apply { getFavoritesList(favs)?.let { addAll(0, it) } } } private fun getFavoritesList(favs: List<MediaWrapper>?): MutableList<MediaLibraryItem>? { if (favs?.isNotEmpty() == true) { val list = mutableListOf<MediaLibraryItem>() list.add(0, DummyItem(context.getString(R.string.network_favorites))) for ((index, fav) in favs.withIndex()) list.add(index + 1, fav) list.add(DummyItem(context.getString(R.string.network_shared_folders))) return list } return null } }
application/vlc-android/src/org/videolan/vlc/providers/NetworkProvider.kt
959657947
package fr.free.nrw.commons.explore.media import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import fr.free.nrw.commons.media.MediaClient import io.reactivex.Single import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations class PageableMediaDataSourceTest { @Mock lateinit var mediaConverter: MediaConverter @Mock lateinit var mediaClient: MediaClient @Before fun setUp() { MockitoAnnotations.initMocks(this) } @Test fun `loadFunction invokes mediaClient and has Label`() { whenever(mediaClient.getMediaListFromSearch("test", 0, 1)) .thenReturn(Single.just(emptyList())) val pageableMediaDataSource = PageableMediaDataSource(mock(), mediaClient) pageableMediaDataSource.onQueryUpdated("test") assertThat(pageableMediaDataSource.loadFunction(0,1), `is`(emptyList())) } }
app/src/test/kotlin/fr/free/nrw/commons/explore/media/PageableMediaDataSourceTest.kt
926148875
package de.thm.arsnova.service.authservice import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ArsnovaAuthServiceApplicationTests { @Test fun contextLoads() { } }
authz/src/test/kotlin/de/thm/arsnova/service/authservice/ArsnovaAuthServiceApplicationTests.kt
1382607637
/* * Copyright 2018 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronolens.java import org.chronolens.core.model.SourceFile import org.chronolens.core.parsing.Parser import org.chronolens.core.parsing.Result import org.chronolens.test.core.model.SourceFileBuilder import org.chronolens.test.core.model.sourceFile import kotlin.test.fail abstract class JavaParserTest { private val defaultPath = "Test.java" protected fun sourceFile(init: SourceFileBuilder.() -> Unit): SourceFile = sourceFile(defaultPath).build(init) protected fun parse( source: String, path: String = defaultPath ): SourceFile { val result = Parser.parse(path, source) return when (result) { is Result.Success -> result.source else -> fail() } } protected fun parseResult( source: String, path: String = defaultPath ): Result = Parser.parse(path, source) ?: fail() }
services/chronolens-java/src/test/kotlin/org/chronolens/java/JavaParserTest.kt
1442409285
package com.ternaryop.util.okhttp3 import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor /** * OkHttp util class */ object OkHttpUtil { fun debugHttpClient(): OkHttpClient { val debugInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { this.level = HttpLoggingInterceptor.Level.BODY } return OkHttpClient.Builder().apply { interceptors().add(debugInterceptor) }.build() } }
core/src/main/java/com/ternaryop/util/okhttp3/OkHttpUtil.kt
3792757860
package com.didichuxing.doraemonkit.kit.mc.oldui import com.didichuxing.doraemonkit.kit.core.DoKitManager import com.didichuxing.doraemonkit.kit.test.TestMode import com.didichuxing.doraemonkit.kit.test.mock.data.HostInfo import com.didichuxing.doraemonkit.util.SPUtils /** * didi Create on 2022/4/22 . * * Copyright (c) 2022/4/22 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/4/22 12:25 下午 * @Description 用一句话说明文件功能 */ object DoKitMcManager { const val MC_CASE_ID_KEY = "MC_CASE_ID" const val MC_CASE_RECODING_KEY = "MC_CASE_RECODING" const val DOKIT_MC_CONNECT_URL = "dokit_mc_connect_url" const val NAME_DOKIIT_MC_CONFIGALL = "dokiit-mc-config-all" /** * 是否处于录制状态 */ var IS_MC_RECODING = false /** * 主机信息 */ var HOST_INFO: HostInfo? = null var MC_CASE_ID: String = "" var WS_MODE: TestMode = TestMode.UNKNOWN var CONNECT_MODE: TestMode = TestMode.UNKNOWN var sp: SPUtils = SPUtils.getInstance(NAME_DOKIIT_MC_CONFIGALL) private var mode: TestMode = TestMode.UNKNOWN fun getMode(): TestMode { return mode } fun init() { loadConfig() } fun loadConfig() { DoKitManager.MC_CONNECT_URL = sp.getString(DOKIT_MC_CONNECT_URL) } fun saveMcConnectUrl(url: String) { DoKitManager.MC_CONNECT_URL = url sp.put(DOKIT_MC_CONNECT_URL, url) } }
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/DoKitMcManager.kt
2555778503
package cc.aoeiuv020.panovel.refresher import com.google.gson.annotations.SerializedName /** * 分享书单时供gson解析的bean类, * 兼容旧版, * * Created by AoEiuV020 on 2018.05.28-13:50:33. */ class BookListBean( @SerializedName("name") val name: String, @SerializedName("list") val list: List<NovelMinimal>, @SerializedName("version") val version: Int, @SerializedName("uuid") val uuid: String ) class BookListBean2( @SerializedName("name") val name: String, @SerializedName("list") val list: List<NovelMinimal>, @SerializedName("version") val version: Int ) class BookListBean1( @SerializedName("name") val name: String, @SerializedName("list") val list: List<OldNovel> ) class OldNovel( @SerializedName("name") val name: String, @SerializedName("author") val author: String, @SerializedName("site") val site: String, @SerializedName("requester") val requester: OldRequester ) class OldRequester( @SerializedName("type") val type: String, @SerializedName("extra") val extra: String ) data class NovelMinimal( var site: String, var author: String, var name: String, var detail: String )
refresher/src/main/java/cc/aoeiuv020/panovel/refresher/data.kt
157478168
package org.tasks.caldav.property import at.bitfire.dav4jvm.PropertyRegistry import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.tasks.caldav.property.TestPropertyUtils.toProperty import org.tasks.caldav.property.ShareAccess.Companion.SHARED_OWNER class ShareAccessTest { @Before fun setUp() { PropertyRegistry.register(ShareAccess.Factory()) } @Test fun parseShareAccess() { val access: ShareAccess = """ <d:share-access> <d:shared-owner /> </d:share-access> """.toProperty() assertEquals(ShareAccess(SHARED_OWNER), access) } }
app/src/test/java/org/tasks/caldav/property/ShareAccessTest.kt
4122889387
package cc.aoeiuv020.panovel.api.site import org.junit.Test import java.net.URLEncoder /** * Created by AoEiuV020 on 2018.09.04-03:47:10. */ class QinxiaoshuoTest : BaseNovelContextText(Qinxiaoshuo::class) { @Test fun search() { search("异世界") search("都市") search("OVERLORD", "丸山くがね", "OVERLORD") // 全名太长,搜索失败, search("为美好的世界献上祝福!(给予这个绝美的世界以祝福!)", "晓なつめ", URLEncoder.encode("为美好的世界献上祝福!(给予这个绝美的世界以祝福!)", "utf-8").toLowerCase()) } @Test fun detail() { detail(URLEncoder.encode("为美好的世界献上祝福!(给予这个绝美的世界以祝福!)", "utf-8").toLowerCase(), URLEncoder.encode("为美好的世界献上祝福!(给予这个绝美的世界以祝福!)", "utf-8").toLowerCase(), "为美好的世界献上祝福!(给予这个绝美的世界以祝福!)", "晓なつめ", "http://static.qinxiaoshuo.com:4000/bookimg/1609.jpg", "喜爱游戏的家里蹲少年佐藤和真的人生突然闭幕……但是他的眼前出现自称女神的美少女。转生到异世界的和真就此为了满足食衣住而努力工作!原本只想安稳度日的和真,却因为带去的女神接二连三引发问题,甚至被魔王军盯上了!?", "2019-08-19 23:00:00") detail("OVERLORD", "OVERLORD", "OVERLORD", "丸山くがね", "http://static.qinxiaoshuo.com:4000/bookimg/1545.jpg", "一款席卷游戏界的网络游戏「YGGDRASIL」,有一天突然毫无预警地停止一切服务——原本应该是如此。但是不知为何它却成了一款即使过了结束时间,玩家角色依然不会登出的游戏。NPC开始拥有自己的思想。\n" + "现实世界当中一名喜欢电玩的普通青年,似乎和整个公会一起穿越到异世界,变成拥有骷髅外表的最强魔法师「飞鼠」。他率领的公会「安兹.乌尔.恭」将展开前所未有的奇幻传说!", "2019-12-23 10:27:42") } @Test fun chapters() { chapters(URLEncoder.encode("为美好的世界献上祝福!(给予这个绝美的世界以祝福!)", "utf-8").toLowerCase(), "转载信息", "0/1609/5d77d1cb56fec85e5b100448", null, "后记", "0/1609/5d77d1da56fec85e5b100552", "2019-08-19 23:00:00", 267) chapters("OVERLORD", "prologue", "0/1545/5d77d0d856fec85e5b0ffccc", null, "作者杂感", "0/1545/5ea3edf4e5337d4bcf7e81b5", "2020-04-25 15:59:00", 142) } @Test fun content() { content("0/1545/5d77d0d856fec85e5b0ffccc", "第一卷 不死者之王 prologue", "于是────", 56) content("0/1609/5d77d1cb56fec85e5b100452", "第一卷 啊啊,没用的女神大人 插画", "![img](http://static.qinxiaoshuo.com:4000/novel_img/1609/5d77d1cb56fec85e5b100452/23.jpg)", 24) } }
api/src/test/java/cc/aoeiuv020/panovel/api/site/QinxiaoshuoTest.kt
4064167630
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.ds3autogen.go.generators.response import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableSet import com.spectralogic.ds3autogen.api.models.apispec.Ds3ResponseCode import com.spectralogic.ds3autogen.api.models.apispec.Ds3Type import com.spectralogic.ds3autogen.go.models.response.ResponseCode /** * Generates the Go Amazon Get Object response handler */ class GetObjectResponseGenerator : BaseResponseGenerator() { /** * Retrieves the response payload struct content, which is an io.ReadCloser */ override fun toResponsePayloadStruct(expectedResponseCodes: ImmutableList<Ds3ResponseCode>?): String { return "Content io.ReadCloser" } /** * Converts a Ds3ResponseCode into a ResponseCode model which contains the Go * code for parsing the specified response. */ override fun toResponseCode(ds3ResponseCode: Ds3ResponseCode, responseName: String): ResponseCode { if (ds3ResponseCode.code == 200 || ds3ResponseCode.code == 206) { return ResponseCode(ds3ResponseCode.code, "return &$responseName{ Content: webResponse.Body(), Headers: webResponse.Header() }, nil") } return toStandardResponseCode(ds3ResponseCode, responseName) } }
ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/response/GetObjectResponseGenerator.kt
943330693
package org.apollo.game.plugin.entity.actions import io.mockk.verify import org.apollo.game.message.impl.SetPlayerActionMessage import org.apollo.game.model.entity.Player import org.apollo.game.plugin.testing.junit.ApolloTestingExtension import org.apollo.game.plugin.testing.junit.api.annotations.TestMock import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource @ExtendWith(ApolloTestingExtension::class) class PlayerActionTests { @TestMock lateinit var player: Player @ParameterizedTest @EnumSource(PlayerActionType::class) fun `enabling and disabling PlayerActions sends SetPlayerActionMessages`(type: PlayerActionType) { player.enableAction(type) verify { player.send(eq(SetPlayerActionMessage(type.displayName, type.slot, type.primary))) } assertTrue(player.actionEnabled(type)) { "Action $type should have been enabled, but was not." } player.disableAction(type) verify { player.send(eq(SetPlayerActionMessage("null", type.slot, type.primary))) } assertFalse(player.actionEnabled(type)) { "Action $type should not have been enabled, but was." } } }
game/plugin/entity/actions/test/PlayerActionTests.kt
1456508211
package io.multimoon.colorful import android.annotation.TargetApi import android.app.Activity import android.os.Bundle import android.support.annotation.RequiresApi @RequiresApi(21) open class CActivity : Activity(), CThemeInterface { override var themeString: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) handleOnCreate(this, savedInstanceState, BaseTheme.THEME_MATERIAL) } override fun onResume() { super.onResume() handleOnResume(this) } }
library/src/main/java/io/multimoon/colorful/CActivity.kt
4192839173
package com.andela.checksmarter.Extensions import com.andela.checksmarter.model.CheckSmarterJava import io.realm.Realm /** * Created by CodeKenn on 19/04/16. */ fun Realm.createCheckSmarter(checkSmarterJava: CheckSmarterJava) { beginTransaction() copyToRealmOrUpdate(checkSmarterJava) commitTransaction() }
app/src/main/kotlin/com/andela/checksmarter/Extensions/RealmExt.kt
3413243116
package io.github.detekt.tooling.api import java.util.ServiceLoader interface VersionProvider { fun current(): String companion object { fun load( classLoader: ClassLoader = VersionProvider::class.java.classLoader ): VersionProvider = ServiceLoader.load(VersionProvider::class.java, classLoader).first() } }
detekt-tooling/src/main/kotlin/io/github/detekt/tooling/api/VersionProvider.kt
1996615835
package gsonpath.unit.adapter.standard.model import com.nhaarman.mockitokotlin2.mock import com.squareup.javapoet.TypeName import gsonpath.ProcessingException import gsonpath.adapter.standard.model.GsonObjectValidator import gsonpath.model.FieldType import gsonpath.unit.model.FieldInfoTestFactory.mockFieldInfo import org.junit.Assert import org.junit.Rule import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.rules.ExpectedException import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.Mockito.`when` as whenever @RunWith(Enclosed::class) class GsonObjectValidatorTest { class ExceptionTests { @JvmField @Rule val exception: ExpectedException = ExpectedException.none() @Test @Throws(ProcessingException::class) fun givenBothNonNullAndNullableAnnotations_whenValidate_throwIncorrectAnnotationsException() { // given val fieldInfo = mockFieldInfo(BaseGsonObjectFactoryTest.DEFAULT_VARIABLE_NAME) whenever(fieldInfo.fieldType).thenReturn(FieldType.Other(TypeName.INT.box(), mock())) whenever(fieldInfo.annotationNames).thenReturn(listOf("NonNull", "Nullable")) // when / then exception.expect(ProcessingException::class.java) exception.expectMessage("Field cannot have both Mandatory and Optional annotations") GsonObjectValidator().validate(fieldInfo) } @Test @Throws(ProcessingException::class) fun givenObjectType_whenValidate_throwInvalidFieldTypeException() { // given val fieldInfo = mockFieldInfo(BaseGsonObjectFactoryTest.DEFAULT_VARIABLE_NAME) whenever(fieldInfo.fieldType).thenReturn(FieldType.Other(TypeName.OBJECT, mock())) // when / then exception.expect(ProcessingException::class.java) exception.expectMessage("Invalid field type: java.lang.Object") GsonObjectValidator().validate(fieldInfo) } } @RunWith(Parameterized::class) class MandatoryAnnotationsTest(private val mandatoryAnnotation: String) { @JvmField @Rule val exception: ExpectedException = ExpectedException.none() @Test @Throws(ProcessingException::class) fun givenPrimitiveField_whenAddGsonType_throwProcessingException() { // when val fieldInfo = mockFieldInfo(BaseGsonObjectFactoryTest.DEFAULT_VARIABLE_NAME) whenever(fieldInfo.annotationNames).thenReturn(listOf(mandatoryAnnotation)) // when / then exception.expect(ProcessingException::class.java) exception.expectMessage("Primitives should not use NonNull or Nullable annotations") GsonObjectValidator().validate(fieldInfo) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<Any>> = listOf( arrayOf<Any>("NonNull"), arrayOf<Any>("Nonnull"), arrayOf<Any>("NotNull"), arrayOf<Any>("Notnull") ) } } @RunWith(Parameterized::class) class ValidResultTests( private val requiredTypeAnnotation: String?, private val expectedResult: GsonObjectValidator.Result) { @Test @Throws(ProcessingException::class) fun test() { // when val fieldInfo = mockFieldInfo(BaseGsonObjectFactoryTest.DEFAULT_VARIABLE_NAME) whenever(fieldInfo.fieldType).thenReturn(FieldType.Other(TypeName.INT.box(), mock())) if (requiredTypeAnnotation != null) { whenever(fieldInfo.annotationNames).thenReturn(listOf(requiredTypeAnnotation)) } // when val result = GsonObjectValidator().validate(fieldInfo) // then Assert.assertEquals(expectedResult, result) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<out Any?>> = listOf( arrayOf("NonNull", GsonObjectValidator.Result.Mandatory), arrayOf("Nonnull", GsonObjectValidator.Result.Mandatory), arrayOf("NotNull", GsonObjectValidator.Result.Mandatory), arrayOf("Notnull", GsonObjectValidator.Result.Mandatory), arrayOf("Nullable", GsonObjectValidator.Result.Optional), arrayOf("Unknown", GsonObjectValidator.Result.Standard), arrayOf(null, GsonObjectValidator.Result.Standard) ) } } }
compiler/standard/src/test/java/gsonpath/unit/adapter/standard/model/GsonObjectValidatorTest.kt
3243411740
package net.nemerosa.ontrack.extension.av.processing import net.nemerosa.ontrack.common.BaseException /** * Processing exception thrown if no version can be identified in target file using the * PR creation configuration. */ class AutoVersioningVersionNotFoundException( path: String, ) : BaseException( """Cannot find version in "$path"""" )
ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/processing/AutoVersioningVersionNotFoundException.kt
2644754054
package it.liceoarzignano.bold.marks import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import it.liceoarzignano.bold.R import it.liceoarzignano.bold.utils.HelpToast import it.liceoarzignano.bold.utils.Time import java.util.* internal class SubjectAdapter(private var mMarks: List<Mark>, private val mContext: Context) : androidx.recyclerview.widget.RecyclerView.Adapter<SubjectAdapter.SubjectHolder>() { override fun onCreateViewHolder(parent: ViewGroup, type: Int): SubjectHolder = SubjectHolder(LayoutInflater.from(parent.context) .inflate(R.layout.item_mark, parent, false)) override fun onBindViewHolder(holder: SubjectHolder, position: Int) = holder.setData(mMarks[position]) override fun getItemCount(): Int = mMarks.size fun updateList(marks: List<Mark>) { mMarks = marks notifyDataSetChanged() } internal inner class SubjectHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { private val mView: View = view.findViewById(R.id.row_mark_root) private val mValue: TextView = view.findViewById(R.id.row_mark_value) private val mDate: TextView = view.findViewById(R.id.row_mark_date) private val mSummary: TextView = view.findViewById(R.id.row_mark_summary) fun setData(mark: Mark) { mDate.text = Time(mark.date).asString(mContext) val value = mark.value.toDouble() / 100 if (value < 6) { mValue.setTextColor(Color.RED) } mValue.text = String.format(Locale.ENGLISH, "%.2f", value) val summary = mark.description val hasSummary = !summary.isEmpty() if (hasSummary) { mSummary.text = summary } mView.setOnClickListener { if (hasSummary) { mSummary.visibility = if (mSummary.visibility == View.VISIBLE) View.GONE else View.VISIBLE } HelpToast(mContext, HelpToast.KEY_MARK_LONG_PRESS) } mView.setOnLongClickListener { (mContext as SubjectActivity).marksAction(mark) } } } }
app/src/main/kotlin/it/liceoarzignano/bold/marks/SubjectAdapter.kt
2230922113
package net.nemerosa.ontrack.model.security import com.fasterxml.jackson.annotation.JsonProperty import net.nemerosa.ontrack.model.structure.Entity import net.nemerosa.ontrack.model.structure.ID import java.io.Serializable data class Account( override val id: ID, val name: String, val fullName: String, val email: String, val authenticationSource: AuthenticationSource, val role: SecurityRole, val disabled: Boolean, val locked: Boolean, ) : Entity, Serializable { companion object { @JvmStatic fun of(name: String, fullName: String, email: String, role: SecurityRole, authenticationSource: AuthenticationSource, disabled: Boolean, locked: Boolean) = Account( ID.NONE, name, fullName, email, authenticationSource, role, disabled = disabled, locked = locked, ) } fun withId(id: ID): Account = Account( id, name, fullName, email, authenticationSource, role, disabled = disabled, locked = locked, ) fun update(input: AccountInput) = Account( id, input.name, input.fullName, input.email, authenticationSource, role, disabled = input.disabled, locked = input.locked, ) /** * Default built-in admin? */ @get:JsonProperty("defaultAdmin") val isDefaultAdmin get() = "admin" == name fun asPermissionTarget() = PermissionTarget( PermissionTargetType.ACCOUNT, id(), name, fullName ) }
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/Account.kt
3409941966
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2022 Tobias Kaminsky * Copyright (C) 2022 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.adapter import com.afollestad.sectionedrecyclerview.SectionedViewHolder import com.owncloud.android.databinding.GalleryHeaderBinding class GalleryHeaderViewHolder(val binding: GalleryHeaderBinding) : SectionedViewHolder(binding.root)
app/src/main/java/com/owncloud/android/ui/adapter/GalleryHeaderViewHolder.kt
4234092772
/* * 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 org.junit.jupiter.api.Assertions import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource import java.util.stream.Stream private class ProjectArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> { return Stream.of( Arguments.of(Project(masterURL = "Master URL")), Arguments.of(Project(masterURL = "Master URL", projectName = "Project")) ) } } class ProjectTest { @ParameterizedTest @ArgumentsSource(ProjectArgumentsProvider::class) fun `Test name property`(project: Project) { if (project.projectName.isEmpty()) Assertions.assertEquals(project.masterURL, project.name) else Assertions.assertEquals(project.projectName, project.name) } }
android/BOINC/app/src/test/java/edu/berkeley/boinc/rpc/ProjectTest.kt
815769232
package net.blakelee.coinprofits.di import android.app.Application import android.arch.persistence.room.Room import android.content.SharedPreferences import android.support.v7.preference.PreferenceManager import com.jakewharton.picasso.OkHttp3Downloader import com.squareup.picasso.Picasso import dagger.Module import dagger.Provides import net.blakelee.coinprofits.repository.* import net.blakelee.coinprofits.repository.db.AppDatabase import net.blakelee.coinprofits.repository.db.CoinDao import net.blakelee.coinprofits.repository.db.HoldingsDao import net.blakelee.coinprofits.repository.db.TransactionDao import net.blakelee.coinprofits.repository.rest.ChartApi import net.blakelee.coinprofits.repository.rest.CoinApi import net.blakelee.coinprofits.repository.rest.ERC20Api import okhttp3.Cache import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.io.File import javax.inject.Singleton @Module class AppModule{ companion object { private const val NAME = "app.db" private const val DISK_CACHE_SIZE: Long = 5 * 1024 * 1024 const val IMAGE_URL = "https://files.coinmarketcap.com/static/img/coins/64x64/" private fun createHttpClient(app: Application): OkHttpClient.Builder { val cacheDir = File(app.cacheDir, "http") val cache = Cache(cacheDir, DISK_CACHE_SIZE) return OkHttpClient.Builder() .cache(cache) } } /** DATABASE COMPONENTS */ @Singleton @Provides fun providePersistentDatabase(app: Application): AppDatabase = Room.databaseBuilder(app, AppDatabase::class.java, NAME) .build() @Provides @Singleton fun provideCoinDao(db: AppDatabase) = db.coinModel() @Provides @Singleton fun provideHoldingsDao(db: AppDatabase) = db.holdingsModel() @Provides @Singleton fun provideTransactionDao(db: AppDatabase) = db.transactionModel() /** IMAGE COMPONENTS*/ @Provides @Singleton fun provideOkHttpClient(app: Application):OkHttpClient = createHttpClient(app).build() @Provides @Singleton fun providePicasso(client: OkHttpClient, app: Application): Picasso = Picasso.Builder(app) .downloader(OkHttp3Downloader(client)) .build() /** NETWORK COMPONENTS */ @Provides @Singleton fun provideCoinMarketCapApi(): CoinApi = Retrofit.Builder() .baseUrl(CoinApi.HTTPS_API_COINMARKETCAP_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(CoinApi::class.java) @Provides @Singleton fun provideChartApi(): ChartApi = Retrofit.Builder() .baseUrl(ChartApi.HTTPS_API_CHART_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(ChartApi::class.java) @Provides @Singleton fun provideERC20Api(): ERC20Api = Retrofit.Builder() .baseUrl(ERC20Api.HTTPS_API_ETHPLORER_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(ERC20Api::class.java) /** SHARED PREFERENCES COMPONENTS */ @Provides @Singleton fun provideSharedPreferences(app: Application): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(app) /** REPOSITORIES */ @Provides @Singleton fun provideChartRepository(api: ChartApi) = ChartRepository(api) @Provides @Singleton fun provideCoinRepository(dao: CoinDao, api: CoinApi) = CoinRepository(dao, api) @Provides @Singleton fun provideHoldingsRepository(hdao: HoldingsDao, cdao: CoinDao, api: CoinApi) = HoldingsRepository(hdao, cdao, api) @Provides @Singleton fun providePreferencesRepository(prefs: SharedPreferences) = PreferencesRepository(prefs) @Provides @Singleton fun provideTransactionRepository(db: TransactionDao, api: ERC20Api) = TransactionRepository(db, api) }
app/src/main/java/net/blakelee/coinprofits/di/AppModule.kt
3348829592
package com.hewking.custom import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import android.view.animation.BounceInterpolator import com.hewking.custom.util.L import com.hewking.custom.util.dp2px /** * 项目名称:FlowChat * 类的描述: * 创建人员:hewking * 创建时间:2018/11/12 0012 * 修改人员:hewking * 修改时间:2018/11/12 0012 * 修改备注: * Version: 1.0.0 */ open class LoadingView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) { private val TAG = "LoadingView" var color = Color.BLACK var size = dp2px(10f) var stroke = dp2px(10f) var count = 3 // 一秒三次 var interval = 1 set(value) { field = value postInvalidateOnAnimation() } init { val typedArray = ctx.obtainStyledAttributes(attrs, R.styleable.LoadingView) color = typedArray.getColor(R.styleable.LoadingView_h_color,color) typedArray.recycle() } private val animator = ValueAnimator.ofFloat(0f, 1f).apply { duration = 2000 interpolator = BounceInterpolator() repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.RESTART addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { override fun onAnimationUpdate(animation: ValueAnimator?) { // 1-3 val value = makeValue(animation?.animatedValue as Float) L.d("LoadingView", "value -> ${animation?.animatedValue} value : $value") if (value != interval) { interval = value } } }) } private fun makeValue(value : Float) : Int { val a = 1f.div(3) return (value.div(a) + 1).toInt() } private val mPaint by lazy { Paint().apply { isAntiAlias = true style = Paint.Style.FILL } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { L.d(TAG,"onMeasure") val wMode = MeasureSpec.getMode(widthMeasureSpec) var width = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) if (wMode == MeasureSpec.AT_MOST) { width = paddingStart + paddingEnd + size * count + 2 * stroke } if (hMode == MeasureSpec.AT_MOST) { height = paddingTop + paddingBottom + size } setMeasuredDimension(width, height) } override fun onDraw(canvas: Canvas?) { L.d(TAG,"onDraw") if (canvas == null) return var radius = size / 2 var cy = height / 2 for (i in 1 until interval + 1) { var cx = paddingStart + radius + (size + stroke) * (i - 1) canvas.drawCircle(cx.toFloat(), cy.toFloat(), radius.toFloat(), mPaint) } } override fun onAttachedToWindow() { super.onAttachedToWindow() // start animator animator.start() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // end animator animator.end() } }
app/src/main/java/com/hewking/custom/LoadingView.kt
341917537
package com.soywiz.korge.service import com.soywiz.kds.linkedHashMapOf open class ServiceBaseId() { private val map: LinkedHashMap<String, String> = linkedHashMapOf() operator fun set(platform: String, id: String) { map[platform] = id } operator fun get(platform: String) = map[platform] ?: error("Id not set for platform '$platform'") override fun toString(): String = "${this::class.simpleName}($map)" } fun ServiceBaseId.platform(platform: String) = this[platform] fun ServiceBaseId.android() = platform("android") fun ServiceBaseId.ios() = platform("ios") fun <T : ServiceBaseId> T.platform(platform: String, id: String): T = this.apply { this[platform] = id } fun <T : ServiceBaseId> T.android(id: String): T = platform("android", id) fun <T : ServiceBaseId> T.ios(id: String): T = platform("ios", id)
korge/src/commonMain/kotlin/com/soywiz/korge/service/ServiceBaseId.kt
3968646094
package com.soywiz.korge.tiled import com.soywiz.kmem.* import com.soywiz.korge.tiled.TiledMap.* import com.soywiz.korim.color.* import com.soywiz.korio.file.* import com.soywiz.korio.lang.* import com.soywiz.korio.serialization.xml.* import com.soywiz.korio.util.* import com.soywiz.korma.geom.* suspend fun VfsFile.writeTiledMap(map: TiledMap) { writeString(map.toXml().toString()) } fun TiledMap.toXml(): Xml { val map = this val mapData = map.data return buildXml( "map", "version" to 1.2, "tiledversion" to "1.3.1", "orientation" to mapData.orientation.value, "renderorder" to mapData.renderOrder.value, "compressionlevel" to mapData.compressionLevel, "width" to mapData.width, "height" to mapData.height, "tilewidth" to mapData.tilewidth, "tileheight" to mapData.tileheight, "hexsidelength" to mapData.hexSideLength, "staggeraxis" to mapData.staggerAxis, "staggerindex" to mapData.staggerIndex, "backgroundcolor" to mapData.backgroundColor?.toStringARGB(), "infinite" to mapData.infinite.toInt(), "nextlayerid" to mapData.nextLayerId, "nextobjectid" to mapData.nextObjectId ) { propertiesToXml(mapData.properties) for (tileset in map.tilesets) { val tilesetData = tileset.data if (tilesetData.tilesetSource != null) { node("tileset", "firstgid" to tilesetData.firstgid, "source" to tilesetData.tilesetSource) } else { node(tilesetData.toXml()) } } for (layer in map.allLayers) { when (layer) { is Layer.Tiles -> tileLayerToXml( layer, mapData.infinite, mapData.editorSettings?.chunkWidth ?: 16, mapData.editorSettings?.chunkHeight ?: 16 ) is Layer.Objects -> objectLayerToXml(layer) is Layer.Image -> imageLayerToXml(layer) is Layer.Group -> groupLayerToXml( layer, mapData.infinite, mapData.editorSettings?.chunkWidth ?: 16, mapData.editorSettings?.chunkHeight ?: 16 ) } } val editorSettings = mapData.editorSettings if (editorSettings != null && (editorSettings.chunkWidth != 16 || editorSettings.chunkHeight != 16)) { node("editorsettings") { node( "chunksize", "width" to editorSettings.chunkWidth, "height" to editorSettings.chunkHeight ) } } } } private fun TileSetData.toXml(): Xml { return buildXml( "tileset", "firstgid" to firstgid, "name" to name, "tilewidth" to tileWidth, "tileheight" to tileHeight, "spacing" to spacing.takeIf { it > 0 }, "margin" to margin.takeIf { it > 0 }, "tilecount" to tileCount, "columns" to columns, "objectalignment" to objectAlignment.takeIf { it != ObjectAlignment.UNSPECIFIED }?.value ) { imageToXml(image) if (tileOffsetX != 0 || tileOffsetY != 0) { node("tileoffset", "x" to tileOffsetX, "y" to tileOffsetY) } grid?.let { grid -> node( "grid", "orientation" to grid.orientation.value, "width" to grid.cellWidth, "height" to grid.cellHeight ) } propertiesToXml(properties) if (terrains.isNotEmpty()) { node("terraintypes") { for (terrain in terrains) { node("terrain", "name" to terrain.name, "tile" to terrain.tile) { propertiesToXml(terrain.properties) } } } } if (tiles.isNotEmpty()) { for (tile in tiles) { node(tile.toXml()) } } if (wangsets.isNotEmpty()) { node("wangsets") { for (wangset in wangsets) node(wangset.toXml()) } } } } private fun WangSet.toXml(): Xml { return buildXml("wangset", "name" to name, "tile" to tileId) { propertiesToXml(properties) if (cornerColors.isNotEmpty()) { for (color in cornerColors) { node( "wangcornercolor", "name" to color.name, "color" to color.color, "tile" to color.tileId, "probability" to color.probability.takeIf { it != 0.0 }?.niceStr ) } } if (edgeColors.isNotEmpty()) { for (color in edgeColors) { node( "wangedgecolor", "name" to color.name, "color" to color.color.toStringARGB(), "tile" to color.tileId, "probability" to color.probability.takeIf { it != 0.0 }?.niceStr ) } } if (wangtiles.isNotEmpty()) { for (wangtile in wangtiles) { node( "wangtile", "tileid" to wangtile.tileId, "wangid" to wangtile.wangId.toUInt().toString(16).toUpperCase(), "hflip" to wangtile.hflip.takeIf { it }, "vflip" to wangtile.vflip.takeIf { it }, "dflip" to wangtile.dflip.takeIf { it } ) } } } } private fun TileData.toXml(): Xml { return buildXml("tile", "id" to id, "type" to type, "terrain" to terrain?.joinToString(",") { it?.toString() ?: "" }, "probability" to probability.takeIf { it != 0.0 }?.niceStr ) { propertiesToXml(properties) imageToXml(image) objectLayerToXml(objectGroup) if (frames != null && frames.isNotEmpty()) { node("animation") { for (frame in frames) { node("frame", "tileid" to frame.tileId, "duration" to frame.duration) } } } } } private class Chunk(val x: Int, val y: Int, val ids: IntArray) private fun XmlBuilder.tileLayerToXml( layer: Layer.Tiles, infinite: Boolean, chunkWidth: Int, chunkHeight: Int ) { node( "layer", "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "width" to layer.width, "height" to layer.height, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) node("data", "encoding" to layer.encoding.value, "compression" to layer.compression.value) { if (infinite) { val chunks = divideIntoChunks(layer.map.data.ints, chunkWidth, chunkHeight, layer.width) chunks.forEach { chunk -> node( "chunk", "x" to chunk.x, "y" to chunk.y, "width" to chunkWidth, "height" to chunkHeight ) { when (layer.encoding) { Encoding.XML -> { chunk.ids.forEach { gid -> node("tile", "gid" to gid.toUInt().takeIf { it != 0u }) } } Encoding.CSV -> { text(buildString(chunkWidth * chunkHeight * 4) { append("\n") for (y in 0 until chunkHeight) { for (x in 0 until chunkWidth) { append(chunk.ids[x + y * chunkWidth].toUInt()) if (y != chunkHeight - 1 || x != chunkWidth - 1) append(',') } append("\n") } }) } Encoding.BASE64 -> { //TODO: convert int array of gids into compressed string } } } } } else { when (layer.encoding) { Encoding.XML -> { layer.map.data.ints.forEach { gid -> node("tile", "gid" to gid.toUInt().takeIf { it != 0u }) } } Encoding.CSV -> { text(buildString(layer.area * 4) { append("\n") for (y in 0 until layer.height) { for (x in 0 until layer.width) { append(layer.map[x, y].value.toUInt()) if (y != layer.height - 1 || x != layer.width - 1) append(',') } append("\n") } }) } Encoding.BASE64 -> { //TODO: convert int array of gids into compressed string } } } } } } private fun divideIntoChunks(array: IntArray, width: Int, height: Int, totalWidth: Int): Array<Chunk> { val columns = totalWidth / width val rows = array.size / columns return Array(rows * columns) { i -> val cx = i % rows val cy = i / rows Chunk(cx * width, cy * height, IntArray(width * height) { j -> val tx = j % width val ty = j / width array[(cx * width + tx) + (cy * height + ty) * totalWidth] }) } } private fun XmlBuilder.objectLayerToXml(layer: Layer.Objects?) { if (layer == null) return node( "objectgroup", "draworder" to layer.drawOrder.value, "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "color" to layer.color.toStringARGB().takeIf { it != "#a0a0a4" }, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) layer.objects.forEach { obj -> node( "object", "id" to obj.id, "gid" to obj.gid, "name" to obj.name.takeIf { it.isNotEmpty() }, "type" to obj.type.takeIf { it.isNotEmpty() }, "x" to obj.bounds.x.takeIf { it != 0.0 }, "y" to obj.bounds.y.takeIf { it != 0.0 }, "width" to obj.bounds.width.takeIf { it != 0.0 }, "height" to obj.bounds.height.takeIf { it != 0.0 }, "rotation" to obj.rotation.takeIf { it != 0.0 }, "visible" to obj.visible.toInt().takeIf { it != 1 } //TODO: support object template //"template" to obj.template ) { propertiesToXml(obj.properties) fun List<Point>.toXml() = joinToString(" ") { p -> "${p.x.niceStr},${p.y.niceStr}" } when (val type = obj.objectShape) { is Object.Shape.Rectangle -> Unit is Object.Shape.Ellipse -> node("ellipse") is Object.Shape.PPoint -> node("point") is Object.Shape.Polygon -> node("polygon", "points" to type.points.toXml()) is Object.Shape.Polyline -> node("polyline", "points" to type.points.toXml()) is Object.Shape.Text -> node( "text", "fontfamily" to type.fontFamily, "pixelsize" to type.pixelSize.takeIf { it != 16 }, "wrap" to type.wordWrap.toInt().takeIf { it != 0 }, "color" to type.color.toStringARGB(), "bold" to type.bold.toInt().takeIf { it != 0 }, "italic" to type.italic.toInt().takeIf { it != 0 }, "underline" to type.underline.toInt().takeIf { it != 0 }, "strikeout" to type.strikeout.toInt().takeIf { it != 0 }, "kerning" to type.kerning.toInt().takeIf { it != 1 }, "halign" to type.hAlign.value, "valign" to type.vAlign.value ) } } } } } private fun XmlBuilder.imageLayerToXml(layer: Layer.Image) { node( "imagelayer", "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) imageToXml(layer.image) } } private fun XmlBuilder.groupLayerToXml(layer: Layer.Group, infinite: Boolean, chunkWidth: Int, chunkHeight: Int) { node( "group", "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) layer.layers.forEach { when (it) { is Layer.Tiles -> tileLayerToXml(it, infinite, chunkWidth, chunkHeight) is Layer.Objects -> objectLayerToXml(it) is Layer.Image -> imageLayerToXml(it) is Layer.Group -> groupLayerToXml(it, infinite, chunkWidth, chunkHeight) } } } } private fun XmlBuilder.imageToXml(image: Image?) { if (image == null) return node( "image", when (image) { is Image.Embedded -> "format" to image.format is Image.External -> "source" to image.source }, "width" to image.width, "height" to image.height, "transparent" to image.transparent ) { if (image is Image.Embedded) { node( "data", "encoding" to image.encoding.value, "compression" to image.compression.value ) { //TODO: encode and compress image text(image.toString()) } } } } private fun XmlBuilder.propertiesToXml(properties: Map<String, Property>) { if (properties.isEmpty()) return fun property(name: String, type: String, value: Any) = node("property", "name" to name, "type" to type, "value" to value) node("properties") { properties.forEach { (name, prop) -> when (prop) { is Property.StringT -> property(name, "string", prop.value) is Property.IntT -> property(name, "int", prop.value) is Property.FloatT -> property(name, "float", prop.value) is Property.BoolT -> property(name, "bool", prop.value.toString()) is Property.ColorT -> property(name, "color", prop.value.toStringARGB()) is Property.FileT -> property(name, "file", prop.path) is Property.ObjectT -> property(name, "object", prop.id) } } } } //TODO: move to korim private fun RGBA.toStringARGB(): String { if (a == 0xFF) { return "#%02x%02x%02x".format(r, g, b) } else { return "#%02x%02x%02x%02x".format(a, r, g, b) } }
korge/src/commonMain/kotlin/com/soywiz/korge/tiled/TiledMapWriter.kt
550566277
package com.google.firebase.example.fireeats.kotlin import android.content.Context import android.os.Bundle import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.google.android.gms.tasks.Task import com.google.android.material.snackbar.Snackbar import com.google.firebase.example.fireeats.R import com.google.firebase.example.fireeats.databinding.ActivityRestaurantDetailBinding import com.google.firebase.example.fireeats.kotlin.adapter.RatingAdapter import com.google.firebase.example.fireeats.kotlin.model.Rating import com.google.firebase.example.fireeats.kotlin.model.Restaurant import com.google.firebase.example.fireeats.kotlin.util.RestaurantUtil import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.ktx.toObject import com.google.firebase.ktx.Firebase class RestaurantDetailActivity : AppCompatActivity(), EventListener<DocumentSnapshot>, RatingDialogFragment.RatingListener { private var ratingDialog: RatingDialogFragment? = null private lateinit var binding: ActivityRestaurantDetailBinding private lateinit var firestore: FirebaseFirestore private lateinit var restaurantRef: DocumentReference private lateinit var ratingAdapter: RatingAdapter private var restaurantRegistration: ListenerRegistration? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRestaurantDetailBinding.inflate(layoutInflater) setContentView(binding.root) // Get restaurant ID from extras val restaurantId = intent.extras?.getString(KEY_RESTAURANT_ID) ?: throw IllegalArgumentException("Must pass extra $KEY_RESTAURANT_ID") // Initialize Firestore firestore = Firebase.firestore // Get reference to the restaurant restaurantRef = firestore.collection("restaurants").document(restaurantId) // Get ratings val ratingsQuery = restaurantRef .collection("ratings") .orderBy("timestamp", Query.Direction.DESCENDING) .limit(50) // RecyclerView ratingAdapter = object : RatingAdapter(ratingsQuery) { override fun onDataChanged() { if (itemCount == 0) { binding.recyclerRatings.visibility = View.GONE binding.viewEmptyRatings.visibility = View.VISIBLE } else { binding.recyclerRatings.visibility = View.VISIBLE binding.viewEmptyRatings.visibility = View.GONE } } } binding.recyclerRatings.layoutManager = LinearLayoutManager(this) binding.recyclerRatings.adapter = ratingAdapter ratingDialog = RatingDialogFragment() binding.restaurantButtonBack.setOnClickListener { onBackArrowClicked() } binding.fabShowRatingDialog.setOnClickListener { onAddRatingClicked() } } public override fun onStart() { super.onStart() ratingAdapter.startListening() restaurantRegistration = restaurantRef.addSnapshotListener(this) } public override fun onStop() { super.onStop() ratingAdapter.stopListening() restaurantRegistration?.remove() restaurantRegistration = null } override fun finish() { super.finish() overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right) } /** * Listener for the Restaurant document ([.restaurantRef]). */ override fun onEvent(snapshot: DocumentSnapshot?, e: FirebaseFirestoreException?) { if (e != null) { Log.w(TAG, "restaurant:onEvent", e) return } snapshot?.let { val restaurant = snapshot.toObject<Restaurant>() if (restaurant != null) { onRestaurantLoaded(restaurant) } } } private fun onRestaurantLoaded(restaurant: Restaurant) { binding.restaurantName.text = restaurant.name binding.restaurantRating.rating = restaurant.avgRating.toFloat() binding.restaurantNumRatings.text = getString(R.string.fmt_num_ratings, restaurant.numRatings) binding.restaurantCity.text = restaurant.city binding.restaurantCategory.text = restaurant.category binding.restaurantPrice.text = RestaurantUtil.getPriceString(restaurant) // Background image Glide.with(binding.restaurantImage.context) .load(restaurant.photo) .into(binding.restaurantImage) } private fun onBackArrowClicked() { onBackPressed() } private fun onAddRatingClicked() { ratingDialog?.show(supportFragmentManager, RatingDialogFragment.TAG) } override fun onRating(rating: Rating) { // In a transaction, add the new rating and update the aggregate totals addRating(restaurantRef, rating) .addOnSuccessListener(this) { Log.d(TAG, "Rating added") // Hide keyboard and scroll to top hideKeyboard() binding.recyclerRatings.smoothScrollToPosition(0) } .addOnFailureListener(this) { e -> Log.w(TAG, "Add rating failed", e) // Show failure message and hide keyboard hideKeyboard() Snackbar.make(findViewById(android.R.id.content), "Failed to add rating", Snackbar.LENGTH_SHORT).show() } } private fun addRating(restaurantRef: DocumentReference, rating: Rating): Task<Void> { // Create reference for new rating, for use inside the transaction val ratingRef = restaurantRef.collection("ratings").document() // In a transaction, add the new rating and update the aggregate totals return firestore.runTransaction { transaction -> val restaurant = transaction.get(restaurantRef).toObject<Restaurant>() if (restaurant == null) { throw Exception("Resraurant not found at ${restaurantRef.path}") } // Compute new number of ratings val newNumRatings = restaurant.numRatings + 1 // Compute new average rating val oldRatingTotal = restaurant.avgRating * restaurant.numRatings val newAvgRating = (oldRatingTotal + rating.rating) / newNumRatings // Set new restaurant info restaurant.numRatings = newNumRatings restaurant.avgRating = newAvgRating // Commit to Firestore transaction.set(restaurantRef, restaurant) transaction.set(ratingRef, rating) null } } private fun hideKeyboard() { val view = currentFocus if (view != null) { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(view.windowToken, 0) } } companion object { private const val TAG = "RestaurantDetail" const val KEY_RESTAURANT_ID = "key_restaurant_id" } }
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RestaurantDetailActivity.kt
166234873
package com.isupatches.wisefy import com.isupatches.wisefy.callbacks.SearchForSSIDsCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER import com.isupatches.wisefy.internal.base.BaseInstrumentationTest import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify /** * Used to test the functionality to search for SSIDs nearby. * * @author Patches * @since 3.0 */ internal class SearchForSSIDsTests : BaseInstrumentationTest() { @Test fun sync_failure_precheck() { mockWiseFyPrechecksUtil.searchForSSIDs_failure() assertEquals(null, wisefy.searchForSSIDs(TEST_SSID)) } @Test fun sync_failure() { mockWiseFyPrechecksUtil.searchForSSIDs_success() mockWiseFySearchUtil.findSSIDsMatchingRegex_null() assertEquals(null, wisefy.searchForSSIDs(TEST_SSID)) } @Test fun sync_success() { mockWiseFyPrechecksUtil.searchForSSIDs_success() val ssids = mockWiseFySearchUtil.findSSIDsMatchingRegex_success() assertEquals(ssids, wisefy.searchForSSIDs(TEST_SSID)) } @Test fun async_failure_prechecks() { mockWiseFyPrechecksUtil.searchForSSIDs_failure() val mockCallbacks = mock(SearchForSSIDsCallbacks::class.java) wisefy.searchForSSIDs(TEST_SSID, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER) } @Test fun async_failure_prechecks_nullCallback() { mockWiseFyPrechecksUtil.searchForSSIDs_failure() nullCallbackUtil.callSearchForSSIDs(TEST_SSID) } @Test fun async_failure() { mockWiseFyPrechecksUtil.searchForSSIDs_success() mockWiseFySearchUtil.findSSIDsMatchingRegex_null() val mockCallbacks = mock(SearchForSSIDsCallbacks::class.java) wisefy.searchForSSIDs(TEST_SSID, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noSSIDsFound() } @Test fun async_failure_nullCallback() { mockWiseFyPrechecksUtil.searchForSSIDs_success() mockWiseFySearchUtil.findSSIDsMatchingRegex_null() nullCallbackUtil.callSearchForSSIDs(TEST_SSID) } @Test fun async_success() { mockWiseFyPrechecksUtil.searchForSSIDs_success() val ssids = mockWiseFySearchUtil.findSSIDsMatchingRegex_success() val mockCallbacks = mock(SearchForSSIDsCallbacks::class.java) wisefy.searchForSSIDs(TEST_SSID, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedSSIDs(ssids) } @Test fun async_success_nullCallback() { mockWiseFyPrechecksUtil.searchForSSIDs_success() mockWiseFySearchUtil.findSSIDsMatchingRegex_success() nullCallbackUtil.callSearchForSSIDs(TEST_SSID) } }
wisefy/src/androidTest/java/com/isupatches/wisefy/SearchForSSIDsTests.kt
138175153
package com.pennapps.labs.pennmobile import android.content.Context import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.view.* import android.widget.Button import android.widget.RelativeLayout import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.google.firebase.analytics.FirebaseAnalytics import com.pennapps.labs.pennmobile.adapters.LaundrySettingsAdapter import com.pennapps.labs.pennmobile.api.StudentLife import com.pennapps.labs.pennmobile.classes.LaundryRoomSimple import kotlinx.android.synthetic.main.fragment_laundry_settings.* import kotlinx.android.synthetic.main.fragment_laundry_settings.view.* import kotlinx.android.synthetic.main.include_main.* import kotlinx.android.synthetic.main.loading_panel.* import kotlinx.android.synthetic.main.no_results.* import java.util.ArrayList import java.util.HashMap class LaundrySettingsFragment : Fragment() { private lateinit var mActivity: MainActivity private lateinit var mStudentLife: StudentLife private lateinit var mContext: Context internal var mHelpLayout: RelativeLayout? = null private var sp: SharedPreferences? = null private var mButton: Button? = null private var numRooms: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mStudentLife = MainActivity.studentLifeInstance mActivity = activity as MainActivity mContext = mActivity mActivity.closeKeyboard() setHasOptionsMenu(true) mActivity.toolbar.visibility = View.VISIBLE mActivity.expandable_bottom_bar.visibility = View.GONE val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "12") bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Laundry Settings") bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature") FirebaseAnalytics.getInstance(mContext).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_laundry_settings, container, false) // set up shared preferences sp = PreferenceManager.getDefaultSharedPreferences(mContext) // reset laundry rooms button mButton = view.laundry_room_reset mButton?.setOnClickListener { // remove shared preferences val editor = sp?.edit() editor?.putInt(getString(R.string.num_rooms_selected_pref), 0) editor?.apply() for (i in 0 until numRooms) { editor?.remove(Integer.toString(i))?.apply() } //view.laundry_building_expandable_list?.setAdapter(mAdapter) } // set up back button mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true) getHalls() return view } private fun getHalls() { mStudentLife.laundryRooms() .subscribe({ rooms -> mActivity.runOnUiThread { numRooms = rooms.size // save number of rooms val editor = sp?.edit() editor?.putInt(getString(R.string.num_rooms_pref), numRooms) editor?.apply() val hashMap = HashMap<String, List<LaundryRoomSimple>>() val hallList = ArrayList<String>() var i = 0 // go through all the rooms while (i < numRooms) { // new list for the rooms in the hall var roomList: MutableList<LaundryRoomSimple> = ArrayList() // if hall name already exists, get the list of rooms and add to that var hallName = rooms[i].location ?: "" if (hallList.contains(hallName)) { roomList = hashMap[hallName] as MutableList<LaundryRoomSimple> hashMap.remove(hallName) hallList.remove(hallName) } while (hallName == rooms[i].location) { roomList.add(rooms[i]) i += 1 if (i >= rooms.size) { break } } // name formatting for consistency if (hallName == "Lauder College House") { hallName = "Lauder" } // add the hall name to the list hallList.add(hallName) hashMap[hallName] = roomList } val mAdapter = LaundrySettingsAdapter(mContext, hashMap, hallList) laundry_building_expandable_list?.setAdapter(mAdapter) loadingPanel?.visibility = View.GONE no_results?.visibility = View.GONE } }, { mActivity.runOnUiThread { loadingPanel?.visibility = View.GONE no_results?.visibility = View.VISIBLE mHelpLayout?.visibility = View.GONE } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { mActivity.toolbar.visibility = View.GONE mActivity.onBackPressed() return true } override fun onResume() { super.onResume() mActivity.removeTabs() mActivity.setTitle(R.string.laundry) if (Build.VERSION.SDK_INT > 17){ mActivity.setSelectedTab(MainActivity.LAUNDRY) } } override fun onDestroyView() { mActivity.toolbar.visibility = View.GONE mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(false) super.onDestroyView() } }
PennMobile/src/main/java/com/pennapps/labs/pennmobile/LaundrySettingsFragment.kt
1604329937
package net.numa08.gochisou.presentation.widget import android.content.Context import android.support.design.widget.AppBarLayout import android.support.design.widget.CoordinatorLayout import android.support.design.widget.TabLayout import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.view.View @Suppress("unused") class BottomBarBehavior(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<TabLayout>(context, attrs) { var defaultDependencyTop = -1 override fun layoutDependsOn(parent: CoordinatorLayout?, child: TabLayout?, dependency: View?): Boolean = dependency is AppBarLayout override fun onDependentViewChanged(parent: CoordinatorLayout?, child: TabLayout?, dependency: View?): Boolean { if (defaultDependencyTop == -1) { defaultDependencyTop = dependency?.top ?: 0 } ViewCompat.setTranslationY(child, defaultDependencyTop.toFloat() - (dependency?.y ?: 0.0f)) return true } }
app/src/main/java/net/numa08/gochisou/presentation/widget/BottomBarBehavior.kt
1503493219
package io.vertx.workshop.trader.impl import io.vertx.core.CompositeFuture import io.vertx.core.Future import io.vertx.core.eventbus.MessageConsumer import io.vertx.core.json.JsonObject import io.vertx.servicediscovery.ServiceDiscovery import io.vertx.servicediscovery.types.EventBusService import io.vertx.servicediscovery.types.MessageSource import io.vertx.workshop.portfolio.PortfolioService class KotlinCompulsiveTraderVerticle : io.vertx.core.AbstractVerticle() { override fun start() { val company = TraderUtils.pickACompany() val numberOfShares = TraderUtils.pickANumber() System.out.println("Groovy compulsive trader configured for company $company and shares: $numberOfShares"); // We create the discovery service object. val discovery = ServiceDiscovery.create(vertx) val marketFuture: Future<MessageConsumer<JsonObject>> = Future.future() val portfolioFuture: Future<PortfolioService> = Future.future() MessageSource.getConsumer<JsonObject>(discovery, JsonObject().put("name", "market-data"), marketFuture) EventBusService.getProxy<PortfolioService>(discovery, PortfolioService::class.java, portfolioFuture) // When done (both services retrieved), execute the handler CompositeFuture.all(marketFuture, portfolioFuture).setHandler { ar -> if (ar.failed()) { System.err.println("One of the required service cannot be retrieved: ${ar.cause().message}"); } else { // Our services: val portfolio = portfolioFuture.result(); val marketConsumer = marketFuture.result(); // Listen the market... marketConsumer.handler { message -> val quote = message.body(); TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, quote) } } } } }
vertx-microservices-workshop/solution/compulsive-traders/src/main/kotlin/io/vertx/workshop/trader/impl/KotlinCompulsiveTraderVerticle.kt
2119311913
import rx.Subscriber import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.* import java.util.concurrent.Semaphore import kotlin.concurrent.thread /** * Created by Roman Belkov on 14.10.15. */ class ButtonEvent(val button: ButtonEventCode, val isPressed: Boolean) { constructor(code: Int, isPressed: Boolean) : this( when(code) { 0 -> ButtonEventCode.Sync 1 -> ButtonEventCode.Escape 28 -> ButtonEventCode.Enter 116 -> ButtonEventCode.Power 103 -> ButtonEventCode.Up 105 -> ButtonEventCode.Left 106 -> ButtonEventCode.Right 108 -> ButtonEventCode.Down else -> throw Exception("Received unknown code") }, isPressed) fun asPair() = Pair(button, isPressed) override fun toString() = "${button.toString()} ${isPressed.toString()}" } class Buttons(deviceFilePath: String) : BinaryFifoSensor<ButtonEvent>(deviceFilePath, 16, 1024) { constructor() : this("/dev/input/event0") var clicksOnly = true override fun parse(bytes: ByteArray, offset: Int): Optional<ButtonEvent> { if (bytes.size < 16) return Optional.empty() val evType = intFromTwoBytes(bytes[offset + 9], bytes[offset + 8]) //println("evType: $evType ") val evCode = intFromTwoBytes(bytes[offset + 11], bytes[offset + 10]) //println("evCode: $evCode ") val evValue = ByteBuffer.wrap(bytes, offset + 12, 4).order(ByteOrder.LITTLE_ENDIAN).int when { evType == 1 && (evValue == 1 || !clicksOnly) -> return Optional.of(ButtonEvent(evCode, evValue == 1)) else -> return Optional.empty() } } // fun checkPressing(button: ButtonEventCode): Boolean { // var isPressed = false // //val semaphore = Semaphore(0) //TODO to monitor // // thread { // this.toObservable().subscribe(object : Subscriber<ButtonEvent>() { // override fun onNext(p0: ButtonEvent) { // if (p0.button == button) { // this.unsubscribe() // //semaphore.release() // } // } // // override fun onCompleted() = Unit // // override fun onError(p0: Throwable) = throw p0 // // }) // } // // return isPressed // } }
src/Buttons.kt
3946727400
package com.eje_c.multilink.data import com.eje_c.multilink.json.JSON /** * JSON object which is sent between VR devices and controller. * @param type Must be one of Message.TYPE_** values. * @param data Optional data. */ class Message(val type: Int, val data: Any? = null) { init { check(type == TYPE_PING || type == TYPE_CONTROL_MESSAGE) { "Illegal value for type: $type" } } /** * Convert to byte array for sending on network. */ fun serialize(): ByteArray { return JSON.stringify(this).toByteArray() } companion object { const val TYPE_PING = 0 const val TYPE_CONTROL_MESSAGE = 1 } }
common-messaging/src/main/java/com/eje_c/multilink/data/Message.kt
562687952
package com.stripe.example.activity import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.Column import androidx.compose.material.MaterialTheme import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.text.PlaceholderVerticalAlign import com.stripe.android.ui.core.R import com.stripe.android.uicore.image.StripeImageLoader import com.stripe.android.uicore.text.EmbeddableImage import com.stripe.android.uicore.text.Html class StripeImageActivity : AppCompatActivity() { private val LocalStripeImageLoader = staticCompositionLocalOf<StripeImageLoader> { error("No ImageLoader provided") } private val imageLoader by lazy { StripeImageLoader( context = this, memoryCache = null, diskCache = null ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CompositionLocalProvider(LocalStripeImageLoader provides imageLoader) { Column { Html( imageLoader = mapOf( "affirm" to EmbeddableImage.Drawable( R.drawable.stripe_ic_affirm_logo, R.string.stripe_paymentsheet_payment_method_affirm ) ), html = """ HTML with single local image <br/> Local image <img src="affirm"/>. <br/> """.trimIndent(), color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.body1 ) Html( imageLoader = mapOf( "affirm" to EmbeddableImage.Drawable( R.drawable.stripe_ic_affirm_logo, R.string.stripe_paymentsheet_payment_method_affirm ) ), html = """ HTML with local and remote images <br/> Local image <img src="affirm"/>. <br/> Unknown remote image <img src="https://qa-b.stripecdn.com/unknown_image.png"/> <br/> Remote images <img src="https://qa-b.stripecdn.com/payment-method-messaging-statics-srv/assets/afterpay_logo_black.png"/> <img src="https://qa-b.stripecdn.com/payment-method-messaging-statics-srv/assets/klarna_logo_black.png"/> <br/> Paragraph text <b>bold text</b>. ⓘ """.trimIndent(), color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.body1, imageAlign = PlaceholderVerticalAlign.TextCenter ) } } } } }
example/src/main/java/com/stripe/example/activity/StripeImageActivity.kt
2126298082
package com.bl_lia.kirakiratter.presentation.presenter import com.bl_lia.kirakiratter.domain.interactor.CompletableUseCase import com.bl_lia.kirakiratter.domain.interactor.SingleUseCase import com.bl_lia.kirakiratter.presentation.internal.di.PerFragment import io.reactivex.Completable import io.reactivex.Single import javax.inject.Inject import javax.inject.Named @PerFragment class NavigationDrawerPresenter @Inject constructor( @Named("logout") private val logout: CompletableUseCase<Void>, @Named("registerToken") private val registerToken: SingleUseCase<String>, @Named("unregisterToken") private val unregisterToken: SingleUseCase<String>, @Named("isRegisteredToken") private val isRegisteredToken: SingleUseCase<Boolean>, @Named("setSimpleMode") private val setSimpleMode: SingleUseCase<Boolean>, @Named("getSimpleMode") private val getSimpleMode: SingleUseCase<Boolean> ): Presenter { override fun resume() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun pause() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun destroy() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun start() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } fun logout(): Completable { return logout.execute() } fun registerToken(pushApiUrl: String): Single<String> { return registerToken.execute(pushApiUrl) } fun unregisterToken(pushApiUrl: String): Single<String> = unregisterToken.execute(pushApiUrl) fun isRegisteredToken(pushApiUrl: String): Single<Boolean> = isRegisteredToken.execute(pushApiUrl) fun setSimpleMode(enabled: Boolean): Single<Boolean> = setSimpleMode.execute(enabled) fun getSimpleMode(): Single<Boolean> = getSimpleMode.execute() }
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/presenter/NavigationDrawerPresenter.kt
2622311084
package org.softeg.slartus.forpdaplus import android.content.SharedPreferences import android.graphics.Color import android.os.Environment import org.softeg.slartus.forpdaplus.classes.common.ArrayUtils import org.softeg.slartus.forpdaplus.core.AppPreferences import java.io.File object AppTheme { private const val THEME_LIGHT = 0 private const val THEME_DARK = 1 private const val THEME_BLACK = 6 private const val THEME_MATERIAL_LIGHT = 2 private const val THEME_MATERIAL_DARK = 3 private const val THEME_MATERIAL_BLACK = 5 private const val THEME_LIGHT_OLD_HD = 4 private const val THEME_CUSTOM_CSS = 99 const val THEME_TYPE_LIGHT = 0 const val THEME_TYPE_DARK = 2 private const val THEME_TYPE_BLACK = 3 private val LIGHT_THEMES = arrayOf(THEME_LIGHT, THEME_LIGHT_OLD_HD, THEME_MATERIAL_LIGHT) private val DARK_THEMES = arrayOf(THEME_MATERIAL_DARK, THEME_DARK) @JvmStatic val webViewFont: String? get() = preferences.getString("webViewFontName", "") @JvmStatic fun getColorAccent(type: String?): Int { var color = 0 when (type) { "Accent" -> color = preferences.getInt("accentColor", Color.rgb(2, 119, 189)) "Pressed" -> color = preferences.getInt("accentColorPressed", Color.rgb(0, 89, 159)) } return color } @JvmStatic val mainAccentColor: Int get() { var color = R.color.accentPink when (preferences.getString("mainAccentColor", "pink")) { AppPreferences.ACCENT_COLOR_PINK_NAME -> color = R.color.accentPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> color = R.color.accentBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> color = R.color.accentGray } return color } @JvmStatic val themeStyleResID: Int get() { var theme = R.style.ThemeLight val color = preferences.getString("mainAccentColor", "pink") when (themeType) { THEME_TYPE_LIGHT -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.MainPinkLight AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.MainBlueLight AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.MainGrayLight } } THEME_TYPE_DARK -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.MainPinkDark AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.MainBlueDark AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.MainGrayDark } } else -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.MainPinkBlack AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.MainBlueBlack AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.MainGrayBlack } } } return theme } @JvmStatic val prefsThemeStyleResID: Int get() { var theme = R.style.ThemePrefsLightPink val color = preferences.getString("mainAccentColor", "pink") when (themeType) { THEME_TYPE_LIGHT -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.ThemePrefsLightPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.ThemePrefsLightBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.ThemePrefsLightGray } } THEME_TYPE_DARK -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.ThemePrefsDarkPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.ThemePrefsDarkBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.ThemePrefsDarkGray } } else -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.ThemePrefsBlackPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.ThemePrefsBlackBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.ThemePrefsBlackGray } } } return theme } @JvmStatic val themeType: Int get() { var themeType = THEME_TYPE_LIGHT val themeStr = currentTheme if (themeStr.length < 3) { val theme = themeStr.toInt() themeType = if (ArrayUtils.indexOf(theme, LIGHT_THEMES) != -1) THEME_TYPE_LIGHT else if (ArrayUtils.indexOf(theme, DARK_THEMES) != -1) THEME_TYPE_DARK else THEME_TYPE_BLACK } else { if (themeStr.contains("/dark/")) themeType = THEME_TYPE_DARK else if (themeStr.contains("/black/")) themeType = THEME_TYPE_BLACK } return themeType } @JvmStatic val themeBackgroundColorRes: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.app_background_light else if (themeType == THEME_TYPE_DARK) R.color.app_background_dark else R.color.app_background_black } @JvmStatic val themeTextColorRes: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) android.R.color.black else if (themeType == THEME_TYPE_DARK) android.R.color.white else android.R.color.white } @JvmStatic val swipeRefreshBackground: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.swipe_background_light else if (themeType == THEME_TYPE_DARK) R.color.swipe_background_dark else R.color.swipe_background_black } @JvmStatic val navBarColor: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.navBar_light else if (themeType == THEME_TYPE_DARK) R.color.navBar_dark else R.color.navBar_black } @JvmStatic val drawerMenuText: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.drawer_menu_text_light else if (themeType == THEME_TYPE_DARK) R.color.drawer_menu_text_dark else R.color.drawer_menu_text_dark } @JvmStatic val themeStyleWebViewBackground: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) Color.parseColor("#eeeeee") else if (themeType == THEME_TYPE_DARK) Color.parseColor("#1a1a1a") else Color.parseColor("#000000") } @JvmStatic val currentBackgroundColorHtml: String get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) "#eeeeee" else if (themeType == THEME_TYPE_DARK) "#1a1a1a" else "#000000" } @JvmStatic val currentTheme: String get() = preferences.getString("appstyle", THEME_LIGHT.toString())?:THEME_LIGHT.toString() @JvmStatic val currentThemeName: String get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) "white" else if (themeType == THEME_TYPE_DARK) "dark" else "black" } private fun checkThemeFile(themePath: String): String { return try { if (!File(themePath).exists()) { // Toast.makeText(INSTANCE,"не найден файл темы: "+themePath,Toast.LENGTH_LONG).show(); defaultCssTheme() } else themePath } catch (ex: Throwable) { defaultCssTheme() } } private fun defaultCssTheme(): String { return "/android_asset/forum/css/4pda_light_blue.css" } @JvmStatic val themeCssFileName: String get() { val themeStr = currentTheme return getThemeCssFileName(themeStr) } @JvmStatic fun getThemeCssFileName(themeStr: String): String { if (themeStr.length > 3) return checkThemeFile(themeStr) val path = "/android_asset/forum/css/" var cssFile = "4pda_light_blue.css" val theme = themeStr.toInt() if (theme == -1) return themeStr val color = preferences.getString("mainAccentColor", "pink") when (theme) { THEME_LIGHT -> when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> cssFile = "4pda_light_blue.css" AppPreferences.ACCENT_COLOR_BLUE_NAME -> cssFile = "4pda_light_pink.css" AppPreferences.ACCENT_COLOR_GRAY_NAME -> cssFile = "4pda_light_gray.css" } THEME_DARK -> when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> cssFile = "4pda_dark_blue.css" AppPreferences.ACCENT_COLOR_BLUE_NAME -> cssFile = "4pda_dark_pink.css" AppPreferences.ACCENT_COLOR_GRAY_NAME -> cssFile = "4pda_dark_gray.css" } THEME_BLACK -> when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> cssFile = "4pda_black_blue.css" AppPreferences.ACCENT_COLOR_BLUE_NAME -> cssFile = "4pda_black_pink.css" AppPreferences.ACCENT_COLOR_GRAY_NAME -> cssFile = "4pda_black_gray.css" } THEME_MATERIAL_LIGHT -> cssFile = "material_light.css" THEME_MATERIAL_DARK -> cssFile = "material_dark.css" THEME_MATERIAL_BLACK -> cssFile = "material_black.css" THEME_LIGHT_OLD_HD -> cssFile = "standart_4PDA.css" THEME_CUSTOM_CSS -> return Environment.getExternalStorageDirectory().path + "/style.css" } return path + cssFile } private val preferences: SharedPreferences get() = App.getInstance().preferences }
app/src/main/java/org/softeg/slartus/forpdaplus/AppTheme.kt
1151527322
package com.stripe.android.payments.core.authentication.threeds2 import android.app.Activity import androidx.activity.result.ActivityResultLauncher import com.stripe.android.StripePaymentController import com.stripe.android.view.AuthActivityStarter import com.stripe.android.view.AuthActivityStarterHost /** * A [AuthActivityStarter] to start [Stripe3ds2TransactionActivity] * with legacy [Activity.startActivityForResult] or modern [ActivityResultLauncher.launch]. */ internal interface Stripe3ds2TransactionStarter : AuthActivityStarter<Stripe3ds2TransactionContract.Args> { class Legacy( private val host: AuthActivityStarterHost ) : Stripe3ds2TransactionStarter { override fun start(args: Stripe3ds2TransactionContract.Args) { host.startActivityForResult( Stripe3ds2TransactionActivity::class.java, args.toBundle(), StripePaymentController.getRequestCode(args.stripeIntent) ) } } class Modern( private val launcher: ActivityResultLauncher<Stripe3ds2TransactionContract.Args> ) : Stripe3ds2TransactionStarter { override fun start(args: Stripe3ds2TransactionContract.Args) { launcher.launch(args) } } }
payments-core/src/main/java/com/stripe/android/payments/core/authentication/threeds2/Stripe3ds2TransactionStarter.kt
4103635311
package com.xenoage.zong.core.music.util import com.xenoage.utils.math.Fraction.Companion.fr import kotlin.test.Test import kotlin.test.assertEquals /** * Tests for [Duration]. */ class DurationTest { @Test fun flagsCountTest() { //simple notes assertEquals(0, fr(1, 4).flagsCount) assertEquals(1, fr(1, 8).flagsCount) assertEquals(2, fr(1, 16).flagsCount) assertEquals(3, fr(1, 32).flagsCount) assertEquals(4, fr(1, 64).flagsCount) assertEquals(5, fr(1, 128).flagsCount) assertEquals(3, fr(2, 64).flagsCount) //single dotted quarter note assertEquals(0, fr(3, 8).flagsCount) //single dotted eighth note assertEquals(1, fr(3, 16).flagsCount) //double dotted quarter note assertEquals(0, fr(7, 16).flagsCount) //single dotted 32nd note assertEquals(3, fr(3, 64).flagsCount) //double dotted 32nd note assertEquals(3, fr(7, 128).flagsCount) //whole note assertEquals(0, fr(1, 1).flagsCount) } @Test fun prolongTest() { //no dots assertEquals(fr(1, 2), fr(1, 2).prolong(0)) assertEquals(fr(1, 4), fr(1, 4).prolong(0)) //one dot assertEquals(fr(3, 4), fr(1, 2).prolong(1)) assertEquals(fr(3, 8), fr(1, 4).prolong(1)) //two dots assertEquals(fr(7, 8), fr(1, 2).prolong(2)) assertEquals(fr(7, 16), fr(1, 4).prolong(2)) } @Test fun dotsTest() { //no dots assertEquals(0, fr(1, 1).dots) assertEquals(0, fr(1, 2).dots) assertEquals(0, fr(1, 4).dots) assertEquals(0, fr(1, 8).dots) assertEquals(0, fr(1, 16).dots) assertEquals(0, fr(1, 32).dots) //one dot assertEquals(1, (fr(1, 1) + fr(1, 2)).dots) assertEquals(1, (fr(1, 2) + fr(1, 4)).dots) assertEquals(1, (fr(1, 4) + fr(1, 8)).dots) assertEquals(1, (fr(1, 8) + fr(1, 16)).dots) assertEquals(1, (fr(1, 16) + fr(1, 32)).dots) assertEquals(1, (fr(1, 32) + fr(1, 64)).dots) //two dots assertEquals(2, (fr(1, 1) + fr(1, 2) + fr(1, 4)).dots) assertEquals(2, (fr(1, 2) + fr(1, 4) + fr(1, 8)).dots) assertEquals(2, (fr(1, 4) + fr(1, 8) + fr(1, 16)).dots) assertEquals(2, (fr(1, 8) + fr(1, 16) + fr(1, 32)).dots) assertEquals(2, (fr(1, 16) + fr(1, 32) + fr(1, 64)).dots) assertEquals(2, (fr(1, 32) + fr(1, 64) + fr(1, 128)).dots) } @Test fun getBaseDurationTest() { //no dots assertEquals(fr(1, 2), fr(1, 2).baseDuration) assertEquals(fr(1, 4), fr(1, 4).baseDuration) //one dot assertEquals(fr(1, 2), fr(3, 4).baseDuration) assertEquals(fr(1, 4), fr(3, 8).baseDuration) //two dots assertEquals(fr(1, 2), fr(7, 8).baseDuration) assertEquals(fr(1, 4), fr(7, 16).baseDuration) } }
core/core-jvm/test/com/xenoage/zong/core/music/util/DurationTest.kt
2339987806
package abi44_0_0.expo.modules.core.errors import kotlinx.coroutines.CancellationException private const val DEFAULT_MESSAGE = "Module destroyed. All coroutines are cancelled." /** * Can be passed as parameter to [kotlinx.coroutines.cancel] when module is destroyed * in order to cancel all coroutines in [kotlinx.coroutines.CoroutineScope] * * Example usage: * ``` * override fun onDestroy() { * try { * moduleCoroutineScope.cancel(ModuleDestroyedException()) * } catch (e: IllegalStateException) { * Log.w(TAG, "The scope does not have a job in it") * } * } * ``` */ class ModuleDestroyedException(message: String = DEFAULT_MESSAGE) : CancellationException(message)
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/core/errors/ModuleDestroyedException.kt
2455190010
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.actions.runAnything.wasmpack import org.rust.ide.actions.runAnything.RsRunAnythingItem import javax.swing.Icon class RunAnythingWasmPackItem(command: String, icon: Icon) : RsRunAnythingItem(command, icon) { override val helpCommand: String = "wasm-pack" override val commandDescriptions: Map<String, String> = hashMapOf( "new" to "Create a new RustWasm project", "build" to "Build and pack the project into pkg directory", "test" to "Run tests using the wasm-bindgen test runner", "pack" to "(npm) Create a tarball from pkg directory", "publish" to "(npm) Create a tarball and publish to the NPM registry" ) override fun getOptionsDescriptionsForCommand(commandName: String): Map<String, String>? = when (commandName) { "build" -> buildOptionsDescriptions "test" -> testOptionsDescriptions "publish" -> publishOptionsDescriptions else -> null } companion object { private val buildOptionsDescriptions: Map<String, String> = hashMapOf( "--target" to "Output target environment: bundler (default), nodejs, web, no-modules", "--dev" to "Development profile: debug info, no optimizations", "--profiling" to "Profiling profile: optimizations and debug info", "--release" to "Release profile: optimizations, no debug info", "--out-dir" to "Output directory", "--out-name" to "Generated file names", "--scope" to "The npm scope to use" ) private val testOptionsDescriptions: Map<String, String> = hashMapOf( "--release" to "Build with release profile", "--headless" to "Test in headless browser mode", "--node" to "Run the tests in Node.js", "--firefox" to "Run the tests in Firefox", "--chrome" to "Run the tests in Chrome", "--safari" to "Run the tests in Safari" ) private val publishOptionsDescriptions: Map<String, String> = hashMapOf( "--tag" to "NPM tag to publish with" ) } }
src/main/kotlin/org/rust/ide/actions/runAnything/wasmpack/RunAnythingWasmPackItem.kt
2193702340
package com.github.jk1.ytplugin.commands.model import com.google.gson.JsonElement import com.google.gson.JsonParser import java.io.InputStream import java.io.InputStreamReader /** * Main wrapper around youtrack command assist response response. It delegates further parsing * to CommandHighlightRange, CommandSuggestion and CommandPreview classes */ class CommandAssistResponse(element: JsonElement) { val highlightRanges: List<CommandHighlightRange> val suggestions: List<CommandSuggestion> val previews: List<CommandPreview> val timestamp = System.currentTimeMillis() init { val root = element.asJsonObject val ranges = root.asJsonObject.getAsJsonArray("styleRanges") val suggests = root.asJsonObject.getAsJsonArray("suggestions") val commands = root.asJsonObject.getAsJsonArray("commands") highlightRanges = ranges.map { CommandHighlightRange(it) } suggestions = suggests.map { CommandSuggestion(it) } previews = commands.map { CommandPreview(it) } } }
src/main/kotlin/com/github/jk1/ytplugin/commands/model/CommandAssistResponse.kt
1899832272
package com.teamwizardry.librarianlib.foundation.block import net.minecraft.block.Block import net.minecraft.block.SoundType import net.minecraft.block.material.Material import net.minecraft.block.material.MaterialColor import net.minecraftforge.client.model.generators.BlockStateProvider /** * A base class for simple Foundation blocks. * * Required textures: * - `<modid>:block/<block_id>.png` */ public open class BaseBlock(override val properties: FoundationBlockProperties): Block(properties.vanillaProperties), IFoundationBlock { override fun generateBlockState(gen: BlockStateProvider) { gen.simpleBlock(this) } public companion object { @JvmStatic public val defaultStoneProperties: FoundationBlockProperties get() = FoundationBlockProperties() .material(Material.ROCK) .mapColor(MaterialColor.STONE) .hardnessAndResistance(1.5f, 6f) @JvmStatic public val defaultMetalBlockProperties: FoundationBlockProperties get() = FoundationBlockProperties() .material(Material.IRON) .hardnessAndResistance(3f, 6f) .sound(SoundType.METAL) @JvmStatic public val defaultGemBlockProperties: FoundationBlockProperties get() = FoundationBlockProperties() .material(Material.IRON) .hardnessAndResistance(5f, 6f) .sound(SoundType.METAL) } }
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/block/BaseBlock.kt
1217695976
/* * 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 org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor class RsCompletionFilteringTest: RsCompletionTestBase() { fun `test unsatisfied bound filtered 1`() = doSingleCompletion(""" trait Bound {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S./*caret*/ } """, """ trait Bound {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S.bar()/*caret*/ } """) fun `test unsatisfied bound filtered 2`() = doSingleCompletion(""" trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn main() { S./*caret*/ } """, """ trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn main() { S.foo()/*caret*/ } """) fun `test unsatisfied bound filtered 3`() = doSingleCompletion(""" trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn foo(a: &S) { a./*caret*/ } """, """ trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn foo(a: &S) { a.foo()/*caret*/ } """) fun `test unsatisfied bound not filtered for unknown type`() = doSingleCompletion(""" trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn main() { S1(SomeUnknownType).f/*caret*/ } """, """ trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn main() { S1(SomeUnknownType).foo()/*caret*/ } """) fun `test unsatisfied bound not filtered for unconstrained type var`() = doSingleCompletion(""" trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn ty_var<T>() -> T { unimplemented!() } fn main() { S1(ty_var()).f/*caret*/ } """, """ trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn ty_var<T>() -> T { unimplemented!() } fn main() { S1(ty_var()).foo()/*caret*/ } """) fun `test unsatisfied bound path filtering`() = doSingleCompletion(""" trait Bound {} trait Trait1 { fn foo(){} } trait Trait2 { fn bar() {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S::/*caret*/ } """, """ trait Bound {} trait Trait1 { fn foo(){} } trait Trait2 { fn bar() {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S::bar()/*caret*/ } """) @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test method is not filtered by Sync+Send bounds`() = doSingleCompletion(""" struct S; trait Trait { fn foo(&self) {} } impl<T: Sync + Send> Trait for T {} fn main() { S.fo/*caret*/ } """, """ struct S; trait Trait { fn foo(&self) {} } impl<T: Sync + Send> Trait for T {} fn main() { S.foo()/*caret*/ } """) fun `test private function`() = checkNoCompletion(""" mod foo { fn bar() {} } fn main() { foo::ba/*caret*/ } """) fun `test private mod`() = checkNoCompletion(""" mod foo { mod bar {} } fn main() { foo::ba/*caret*/ } """) fun `test private enum`() = checkNoCompletion(""" mod foo { enum MyEnum {} } fn main() { foo::MyEn/*caret*/ } """) fun `test private method 1`() = checkNoCompletion(""" mod foo { pub struct S; impl S { fn bar(&self) {} } } fn main() { foo::S.b/*caret*/() } """) fun `test private method 2`() = checkNoCompletion(""" mod foo { pub struct S; impl S { fn bar(&self) {} } } fn main() { foo::S.b/*caret*/ } """) fun `test private field`() = checkNoCompletion(""" mod foo { pub struct S { field: i32 } } fn bar(s: S) { s.f/*caret*/ } """) fun `test public item reexported with restricted visibility 1`() = checkNoCompletion(""" pub mod inner1 { pub mod inner2 { pub fn foo() {} pub(in crate::inner1) use foo as bar; } } fn main() { crate::inner1::inner2::ba/*caret*/ } """) fun `test public item reexported with restricted visibility 2`() = checkContainsCompletion("bar2", """ pub mod inner1 { pub mod inner2 { pub fn bar1() {} pub(in crate::inner1) use bar1 as bar2; } fn main() { crate::inner1::inner2::ba/*caret*/ } } """) fun `test private reexport of public function`() = checkNoCompletion(""" mod mod1 { pub fn foo() {} } mod mod2 { use crate::mod1::foo as bar; } fn main() { mod2::b/*caret*/ } """) // there was error in new resolve when legacy textual macros are always completed fun `test no completion on empty mod 1`() = checkNoCompletion(""" macro_rules! empty { () => {}; } mod foo {} pub use foo::empt/*caret*/ """) @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test no completion on empty mod 2`() = checkNoCompletion(""" mod foo {} pub use foo::asser/*caret*/ """) // Issue https://github.com/intellij-rust/intellij-rust/issues/3694 fun `test issue 3694`() = doSingleCompletion(""" mod foo { pub struct S { field: i32 } fn bar(s: S) { s./*caret*/ } } """, """ mod foo { pub struct S { field: i32 } fn bar(s: S) { s.field/*caret*/ } } """) fun `test doc(hidden) item`() = checkNoCompletion(""" mod foo { #[doc(hidden)] pub struct MyStruct; } fn main() { foo::My/*caret*/ } """) fun `test doc(hidden) item from the same module isn't filtered`() = doSingleCompletion(""" #[doc(hidden)] struct MyStruct; fn main() { My/*caret*/ } """, """ #[doc(hidden)] struct MyStruct; fn main() { MyStruct/*caret*/ } """) fun `test derived method is not completed if the derived trait is not implemented to type argument`() = checkNoCompletion(""" #[lang = "clone"] pub trait Clone { fn clone(&self) -> Self; } struct X; // Not `Clone` #[derive(Clone)] struct S<T>(T); fn main() { S(X).cl/*caret*/; } """) fun `test derived method is not completed UFCS if the derived trait is not implemented to type argument`() = checkNoCompletion(""" #[lang = "clone"] pub trait Clone { fn clone(&self) -> Self; } struct X; // Not `Clone` #[derive(Clone)] struct S<T>(T); fn main() { <S<X>>::cl/*caret*/; } """) fun `test trait implementation on multiple dereference levels`() = doSingleCompletion(""" struct S; trait T { fn foo(&self); } impl T for S { fn foo(&self) {} } impl T for &S { fn foo(&self) {} } fn main(a: &S) { a.f/*caret*/ } """, """ struct S; trait T { fn foo(&self); } impl T for S { fn foo(&self) {} } impl T for &S { fn foo(&self) {} } fn main(a: &S) { a.foo()/*caret*/ } """) fun `test filter by a bound unsatisfied because of a negative impl`() = doSingleCompletion(""" auto trait Sync {} struct S<T> { value: T } impl<T: Sync> S<T> { fn foo1(&self) {} } impl<T> S<T> { fn foo2(&self) {} } struct S0; impl !Sync for S0 {} fn main1(v: S<S0>) { v.fo/*caret*/ } """, """ auto trait Sync {} struct S<T> { value: T } impl<T: Sync> S<T> { fn foo1(&self) {} } impl<T> S<T> { fn foo2(&self) {} } struct S0; impl !Sync for S0 {} fn main1(v: S<S0>) { v.foo2()/*caret*/ } """) }
src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt
3879258698
package de.tum.`in`.tumcampusapp.activities import android.support.v4.view.ViewPager import android.view.View import de.tum.`in`.tumcampusapp.BuildConfig import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.TestApp import de.tum.`in`.tumcampusapp.component.ui.news.KinoViewModel import de.tum.`in`.tumcampusapp.component.ui.news.repository.KinoLocalRepository import de.tum.`in`.tumcampusapp.component.ui.news.repository.KinoRemoteRepository import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoActivity import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoAdapter import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoDao import de.tum.`in`.tumcampusapp.component.ui.tufilm.model.Kino import de.tum.`in`.tumcampusapp.database.TcaDb import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.disposables.CompositeDisposable import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @Ignore @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class, application = TestApp::class) class KinoActivityTest { private var kinoActivity: KinoActivity? = null private lateinit var dao: KinoDao private lateinit var viewModel: KinoViewModel @Before fun setUp() { val db = TcaDb.getInstance(RuntimeEnvironment.application) KinoLocalRepository.db = db viewModel = KinoViewModel(KinoLocalRepository, KinoRemoteRepository, CompositeDisposable()) RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setSingleSchedulerHandler { Schedulers.trampoline() } RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() } dao = db.kinoDao() dao.flush() } @After fun tearDown() { TcaDb.getInstance(RuntimeEnvironment.application).close() RxJavaPlugins.reset() RxAndroidPlugins.reset() } /** * Default usage - there are some movies * Expected output: default Kino activity layout */ @Test fun mainComponentDisplayedTest() { dao.insert(Kino()) kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() assertThat(kinoActivity!!.findViewById<View>(R.id.drawer_layout).visibility).isEqualTo(View.VISIBLE) } /** * There are no movies to display * Expected output: no movies layout displayed */ @Test fun mainComponentNoMoviesDisplayedTest() { kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() //For some reason the ui needs a while until it's been updated. Thread.sleep(100) assertThat(kinoActivity!!.findViewById<View>(R.id.error_layout).visibility).isEqualTo(View.VISIBLE) } /** * There are movies available * Expected output: KinoAdapter is used for pager. */ @Test fun kinoAdapterUsedTest() { dao.insert(Kino()) kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() Thread.sleep(100) assertThat((kinoActivity!!.findViewById<View>(R.id.pager) as ViewPager).adapter!!.javaClass).isEqualTo(KinoAdapter::class.java) } /** * Since we have an immediate scheduler which runs on the same thread and thus can only execute actions sequentially, this will * make the test wait until any previous tasks (like the activity waiting for kinos) are done. */ private fun waitForUI(){ viewModel.getAllKinos().blockingFirst() } }
app/src/test/java/de/tum/in/tumcampusapp/activities/KinoActivityTest.kt
2054290516
package autodagger.example_kotlin import android.app.Application import autodagger.AutoComponent /** * Created by lukasz on 02/12/15. */ @AutoComponent @DaggerScope(KotlinExampleApplication::class) class KotlinExampleApplication : Application() { override fun onCreate() { super.onCreate() } }
example-kotlin/src/main/kotlin/autodagger/example_kotlin/KotlinExampleApplication.kt
827967170
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import android.os.Build import androidx.compose.foundation.layout.Column import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) @OptIn(ExperimentalMaterial3Api::class) class ListItemScreenshotTest { @get:Rule val composeTestRule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_MATERIAL3) @Test fun listItem_customColor() { composeTestRule.setMaterialContent(lightColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem( headlineText = { Text("One line list item with 24x24 icon") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) }, colors = ListItemDefaults.colors(containerColor = Color.Red) ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_oneLine_customColor") } @Test fun oneLine_lightTheme() { composeTestRule.setMaterialContent(lightColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem(headlineText = { Text("One line list item with no icon") }) Divider() ListItem( headlineText = { Text("One line list item with 24x24 icon") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) } ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_oneLine_lightTheme") } @Test fun oneLine_darkTheme() { composeTestRule.setMaterialContent(darkColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem(headlineText = { Text("One line list item with no icon") }) Divider() ListItem( headlineText = { Text("One line list item with 24x24 icon") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) } ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_oneLine_darkTheme") } @Test fun twoLine_lightTheme() { composeTestRule.setMaterialContent(lightColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem( headlineText = { Text("Two line list item") }, supportingText = { Text("Secondary text") } ) Divider() ListItem( headlineText = { Text("Two line list item") }, overlineText = { Text("OVERLINE") } ) Divider() ListItem( headlineText = { Text("Two line list item with 24x24 icon") }, supportingText = { Text("Secondary text") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) } ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_twoLine_lightTheme") } @Test fun twoLine_darkTheme() { composeTestRule.setMaterialContent(darkColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem( headlineText = { Text("Two line list item") }, supportingText = { Text("Secondary text") } ) Divider() ListItem( headlineText = { Text("Two line list item") }, overlineText = { Text("OVERLINE") } ) Divider() ListItem( headlineText = { Text("Two line list item with 24x24 icon") }, supportingText = { Text("Secondary text") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) } ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_twoLine_darkTheme") } @Test fun threeLine_lightTheme() { composeTestRule.setMaterialContent(lightColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem( headlineText = { Text("Three line list item") }, overlineText = { Text("OVERLINE") }, supportingText = { Text("Secondary text") }, trailingContent = { Text("meta") } ) Divider() ListItem( headlineText = { Text("Three line list item") }, overlineText = { Text("OVERLINE") }, supportingText = { Text("Secondary text") } ) Divider() ListItem( headlineText = { Text("Three line list item") }, overlineText = { Text("OVERLINE") }, supportingText = { Text("Secondary text") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) } ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_threeLine_lightTheme") } @Test fun threeLine_darkTheme() { composeTestRule.setMaterialContent(darkColorScheme()) { Column(Modifier.testTag(Tag)) { ListItem( headlineText = { Text("Three line list item") }, overlineText = { Text("OVERLINE") }, supportingText = { Text("Secondary text") }, trailingContent = { Text("meta") } ) Divider() ListItem( headlineText = { Text("Three line list item") }, overlineText = { Text("OVERLINE") }, supportingText = { Text("Secondary text") } ) Divider() ListItem( headlineText = { Text("Three line list item") }, overlineText = { Text("OVERLINE") }, supportingText = { Text("Secondary text") }, leadingContent = { Icon( Icons.Filled.Favorite, contentDescription = null ) } ) Divider() } } composeTestRule.onNodeWithTag(Tag) .captureToImage() .assertAgainstGolden(screenshotRule, "list_threeLine_darkTheme") } } private const val Tag = "List"
compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/ListItemScreenshotTest.kt
760993201
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark import android.os.Build import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import java.io.File import kotlin.test.assertSame import kotlin.test.assertTrue import org.junit.Assume.assumeFalse import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class ProfilerTest { @Test fun getByName() { assertSame( if (Build.VERSION.SDK_INT >= 29) StackSamplingSimpleperf else StackSamplingLegacy, Profiler.getByName("StackSampling") ) assertSame(MethodTracing, Profiler.getByName("MethodTracing")) assertSame(ConnectedAllocation, Profiler.getByName("ConnectedAllocation")) assertSame(ConnectedSampling, Profiler.getByName("ConnectedSampling")) // Compat names assertSame(StackSamplingLegacy, Profiler.getByName("MethodSampling")) assertSame(StackSamplingSimpleperf, Profiler.getByName("MethodSamplingSimpleperf")) assertSame(MethodTracing, Profiler.getByName("Method")) assertSame(StackSamplingLegacy, Profiler.getByName("Sampled")) assertSame(ConnectedSampling, Profiler.getByName("ConnectedSampled")) } private fun verifyProfiler( profiler: Profiler, regex: Regex ) { assumeFalse( "Workaround native crash on API 21 in CI, see b/173662168", profiler == MethodTracing && Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP, ) val outputRelPath = profiler.start("test")!!.outputRelativePath profiler.stop() val file = File(Outputs.outputDirectory, outputRelPath) assertTrue( actual = regex.matches(outputRelPath), message = "expected profiler output path $outputRelPath to match $regex" ) assertTrue(file.exists(), "Profiler should create: ${file.absolutePath}") // we don't delete the file to enable inspecting the file // TODO: post the trace to the studio UI via FileLinkingRule or similar } @Test fun methodTracing() = verifyProfiler( profiler = MethodTracing, regex = Regex("test-methodTracing-.+.trace") ) @Test fun stackSamplingLegacy() = verifyProfiler( profiler = StackSamplingLegacy, regex = Regex("test-stackSamplingLegacy-.+.trace") ) @SdkSuppress(minSdkVersion = 29) // simpleperf on system image starting API 29 @Test fun stackSamplingSimpleperf() { // TODO: Investigate cuttlefish API 29 failure assumeFalse(Build.MODEL.contains("Cuttlefish") && Build.VERSION.SDK_INT == 29) verifyProfiler( profiler = StackSamplingSimpleperf, regex = Regex("test-stackSampling-.+.trace") ) } }
benchmark/benchmark-common/src/androidTest/java/androidx/benchmark/ProfilerTest.kt
3399804864
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client.impl.response import android.os.Parcelable import androidx.annotation.RestrictTo import androidx.health.services.client.data.PassiveGoal import androidx.health.services.client.data.ProtoParcelable import androidx.health.services.client.proto.ResponsesProto /** * Response containing an achieved [PassiveGoal]. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) public class PassiveMonitoringGoalResponse(public val passiveGoal: PassiveGoal) : ProtoParcelable<ResponsesProto.PassiveMonitoringGoalResponse>() { /** @hide */ public constructor( proto: ResponsesProto.PassiveMonitoringGoalResponse ) : this(PassiveGoal(proto.goal)) override val proto: ResponsesProto.PassiveMonitoringGoalResponse = ResponsesProto.PassiveMonitoringGoalResponse.newBuilder().setGoal(passiveGoal.proto).build() public companion object { @JvmField public val CREATOR: Parcelable.Creator<PassiveMonitoringGoalResponse> = newCreator { bytes -> val proto = ResponsesProto.PassiveMonitoringGoalResponse.parseFrom(bytes) PassiveMonitoringGoalResponse(proto) } } }
health/health-services-client/src/main/java/androidx/health/services/client/impl/response/PassiveMonitoringGoalResponse.kt
3484779455
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.viewfinder.internal.quirk import android.os.Build import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.internal.DoNotInstrument import org.robolectric.util.ReflectionHelpers /** * Instrument tests for [SurfaceViewNotCroppedByParentQuirk]. */ @RunWith(RobolectricTestRunner::class) @DoNotInstrument @Config(minSdk = Build.VERSION_CODES.LOLLIPOP) class SurfaceViewNotCroppedByParentQuirkTest { @Test fun quirkExistsOnRedMiNote10() { // Arrange. ReflectionHelpers.setStaticField(Build::class.java, "MODEL", "M2101K7AG") ReflectionHelpers.setStaticField(Build::class.java, "MANUFACTURER", "Xiaomi") // Act. val quirk = DeviceQuirks.get( SurfaceViewNotCroppedByParentQuirk::class.java ) // Assert. assertThat(quirk).isNotNull() } }
camera/camera-viewfinder/src/test/java/androidx/camera/viewfinder/internal/quirk/SurfaceViewNotCroppedByParentQuirkTest.kt
2154754564
package com.devbrackets.android.exomedia.listener import androidx.annotation.IntRange /** * Interface definition of a callback to be invoked indicating buffering * status of a media resource being streamed. */ interface OnBufferUpdateListener { /** * Called to update status in buffering a media stream. * The received buffering percentage * indicates how much of the content has been buffered or played. * For example a buffering update of 80 percent when half the content * has already been played indicates that the next 30 percent of the * content to play has been buffered. * * @param percent The integer percent that is buffered [0, 100] inclusive */ fun onBufferingUpdate(@IntRange(from = 0, to = 100) percent: Int) }
library/src/main/kotlin/com/devbrackets/android/exomedia/listener/OnBufferUpdateListener.kt
178200314
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.streams.ui import java.util.* /** * @author Vitaliy.Bibaev */ interface PaintingListener : EventListener { fun componentPainted() }
src/main/java/com/intellij/debugger/streams/ui/PaintingListener.kt
1046985515
inline fun <reified T> Iterable<*>.filterIsInstance() = filter { it is T } fun main(args: Array<String>) { val set = setOf("1984", 2, 3, "Brave new world", 11) println(set.filterIsInstance<Int>()) }
projects/tutorials-master/tutorials-master/core-kotlin/src/main/kotlin/com/baeldung/generic/Reified.kt
1073157983
package org.jetbrains.builtInWebServer import com.intellij.execution.process.OSProcessHandler import com.intellij.openapi.project.Project import com.intellij.util.Consumer import com.intellij.util.net.loopbackSocketAddress import io.netty.bootstrap.Bootstrap import io.netty.channel.Channel import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.catchError import org.jetbrains.concurrency.resolvedPromise import org.jetbrains.io.* import java.util.concurrent.atomic.AtomicReference abstract class SingleConnectionNetService(project: Project) : NetService(project) { protected val processChannel = AtomicReference<Channel>() private @Volatile var port = -1 private @Volatile var bootstrap: Bootstrap? = null protected abstract fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) override final fun connectToProcess(promise: AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) { val bootstrap = oioClientBootstrap() configureBootstrap(bootstrap, errorOutputConsumer) this.bootstrap = bootstrap this.port = port bootstrap.connect(loopbackSocketAddress(port), promise)?.let { promise.catchError { processChannel.set(it) addCloseListener(it) promise.setResult(processHandler) } } } protected fun connectAgain(): Promise<Channel> { val channel = processChannel.get() if (channel != null) { return resolvedPromise(channel) } val promise = AsyncPromise<Channel>() bootstrap!!.connect(loopbackSocketAddress(port), promise)?.let { promise.catchError { processChannel.set(it) addCloseListener(it) promise.setResult(it) } } return promise } private fun addCloseListener(it: Channel) { it.closeFuture().addChannelListener { val channel = it.channel() processChannel.compareAndSet(channel, null) channel.eventLoop().shutdownIfOio() } } override fun closeProcessConnections() { processChannel.getAndSet(null)?.let { it.closeAndShutdownEventLoop() } } }
platform/built-in-server/src/org/jetbrains/builtInWebServer/SingleConnectionNetService.kt
1585253581
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.db.impl.core.changetypes import org.eclipse.collections.api.map.ImmutableMap import org.eclipse.collections.api.map.sorted.ImmutableSortedMap import org.eclipse.collections.impl.map.sorted.mutable.TreeSortedMap class StaticDataDeleteRow internal constructor( whereParams: ImmutableMap<String, Any> ) { val whereParams: ImmutableSortedMap<String, Any> = TreeSortedMap(whereParams.castToMap()).toImmutable() }
obevo-db/src/main/java/com/gs/obevo/db/impl/core/changetypes/StaticDataDeleteRow.kt
783090382
package org.elm.ide.typing import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.psi.PsiFile import org.elm.lang.core.psi.ElmFile import org.elm.lang.core.psi.elements.ElmStringConstantExpr // A BackspaceHandlerDelegate is called during character deletion. // We use this to delete triple quotes, since the QuoteHandler can only delete single characters. class ElmBackspaceHandler : BackspaceHandlerDelegate() { private var rangeMarker: RangeMarker? = null // Called when a character is about to be deleted. There's no return value, so you can't affect behavior // here. override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) { rangeMarker = null // If we didn't insert the matching quote, don't do anything if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) return if (file !is ElmFile) return val offset = editor.caretModel.offset val psiElement = file.findElementAt(offset) ?: return // We need to save the element range now, because the PSI will be changed by the time charDeleted is // called val parent = psiElement.parent ?: return if (parent is ElmStringConstantExpr && parent.text == "\"\"\"\"\"\"" && editor.caretModel.offset == parent.textOffset + 3) { rangeMarker = editor.document.createRangeMarker(parent.textRange) } } // Called immediately after a character is deleted. If this returns true, no automatic quote or brace // deletion will happen. override fun charDeleted(c: Char, file: PsiFile, editor: Editor): Boolean { // The range marker is automatically adjusted with the deleted character, so we can just delete the // whole thing. rangeMarker?.let { editor.document.deleteString(it.startOffset, it.endOffset) rangeMarker = null return true } return false } }
src/main/kotlin/org/elm/ide/typing/ElmBackspaceHandler.kt
1722427941
package me.proxer.app.chat.prv import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import me.proxer.app.ui.view.bbcode.toSimpleBBTree import me.proxer.app.util.extension.toDate import me.proxer.library.entity.messenger.Message import me.proxer.library.enums.Device import me.proxer.library.enums.MessageAction import org.threeten.bp.Instant /** * @author Ruben Gees */ @Entity( tableName = "messages", foreignKeys = [ForeignKey( entity = LocalConference::class, parentColumns = ["id"], childColumns = ["conferenceId"] )], indices = [Index("conferenceId")] ) data class LocalMessage( @PrimaryKey(autoGenerate = true) val id: Long, val conferenceId: Long, val userId: String, val username: String, val message: String, val action: MessageAction, val date: Instant, val device: Device ) { @Transient val styledMessage = message.toSimpleBBTree() fun toNonLocalMessage() = Message( id.toString(), conferenceId.toString(), userId, username, message, action, date.toDate(), device ) }
src/main/kotlin/me/proxer/app/chat/prv/LocalMessage.kt
431719410
package cyberpunk.image import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.graphics.g2d.TextureRegion object ImageManager { /** * Key for the default [TextureAtlas]. * It's not unusual to use just one texture atlas. If that's the case, change this field to the desired name, * via [load], and [take] can be called without supplying an atlas key. */ @JvmStatic var DEFAULT_ATLAS_KEY: String? = null private set /** * Data structure that will hold all loaded [TextureAtlas]. * When [load] is called, all [TextureAtlas] will be stored here. */ private val atlases: MutableMap<String, TextureAtlas> = mutableMapOf() /** * Loads a [TextureAtlas] stored in the assets folder under [path] and stores it * into [atlases] with the given key. * @param key key that will identify this [TextureAtlas] in the [atlases] structure. * @param path path of the atlas, under the assets folder. * @param setAsDefault whether or not this [TextureAtlas] should be set as the [DEFAULT_ATLAS_KEY]. */ @JvmStatic @JvmOverloads fun load(key: String, path: String, setAsDefault: Boolean = false) { val atlas = TextureAtlas(Gdx.files.internal(path)) atlases[key] = atlas if (setAsDefault) { DEFAULT_ATLAS_KEY = key } } /** * Returns the [TextureAtlas] identified by the given key. * @param key key that identifies the [TextureAtlas] in the [atlases] structure. * @return the correct [TextureAtlas] or null, in case of failure. */ @JvmStatic fun getAtlas(key: String): TextureAtlas? = atlases[key] /** * Disposes the given [TextureAtlas]. If none matches the supplied [key], this * action has no effect at all. * This releases all the textures backing all [TextureRegion] and sprites, * which should no longer be used after calling this method. * @param key key that identifies the [TextureAtlas] in the [atlases] structure. */ @JvmStatic fun disposeAtlas(key: String) = atlases[key]?.dispose() /** * Fetches a [TextureRegion] identified by the given [region] name from a [TextureAtlas] * identified by the given [key]. * If no atlas key is supplied, then [DEFAULT_ATLAS_KEY] will be used - which can be null! * @param region region that identifies the [TextureRegion] wanted. * @param key key that identifies the [TextureAtlas] in the [atlases] structure. * @return the [TextureRegion] wanted, or null, in case it was not found. */ @JvmStatic @JvmOverloads fun take(region: String, key: String? = DEFAULT_ATLAS_KEY): TextureRegion? = atlases[key]?.findRegion(region) }
image/src/main/kotlin/cyberpunk/image/ImageManager.kt
1289961964
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.debugger.remote.value import com.intellij.icons.AllIcons import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.impl.XDebugSessionImpl import com.tang.intellij.lua.debugger.remote.LuaMobDebugProcess import org.luaj.vm2.LuaTable import org.luaj.vm2.LuaValue import java.util.* /** * * Created by tangzx on 2017/4/16. */ class LuaRTable(name: String) : LuaRValue(name) { private var list: XValueChildrenList? = null private val desc = "table" private var data: LuaValue? = null override fun parse(data: LuaValue, desc: String) { this.data = data } override fun computePresentation(xValueNode: XValueNode, xValuePlace: XValuePlace) { xValueNode.setPresentation(AllIcons.Json.Object, "table", desc, true) } private val evalExpr: String get() { var name = name val properties = ArrayList<String>() var parent = this.parent while (parent != null) { val parentName = parent.name properties.add(name) name = parentName parent = parent.parent } return buildString { append(name) for (i in properties.indices.reversed()) { val parentName = properties[i] when { parentName.startsWith("[") -> append(parentName) parentName.matches("[0-9]+".toRegex()) -> append("[$parentName]") else -> append(String.format("[\"%s\"]", parentName)) } } } } override fun computeChildren(node: XCompositeNode) { if (list == null) { val process = session.debugProcess as LuaMobDebugProcess process.evaluator?.evaluate(evalExpr, object : XDebuggerEvaluator.XEvaluationCallback { override fun errorOccurred(err: String) { node.setErrorMessage(err) } override fun evaluated(tableValue: XValue) { //////////tmp solution,非栈顶帧处理 var tableValue = tableValue if (data != null && !(process.session as XDebugSessionImpl).isTopFrameSelected) tableValue = LuaRValue.create(myName, data as LuaValue, myName, process.session) ////////// val list = XValueChildrenList() val tbl = tableValue as? LuaRTable ?: return val table = tbl.data?.checktable() if (table != null) for (key in table.keys()) { val value = LuaRValue.create(key.toString(), table.get(key), "", session) value.parent = this@LuaRTable list.add(value) } node.addChildren(list, true) [email protected] = list } }, null) } else node.addChildren(list!!, true) } }
src/main/java/com/tang/intellij/lua/debugger/remote/value/LuaRTable.kt
2013914199
package jetbrains.xodus.browser.web import io.ktor.server.engine.embeddedServer import io.ktor.server.jetty.Jetty import jetbrains.exodus.entitystore.PersistentEntityStoreImpl import jetbrains.exodus.entitystore.PersistentEntityStores import jetbrains.exodus.env.Environments fun main() { Home.setup() val appPort = Integer.getInteger("server.port", 18080) val appHost = System.getProperty("server.host", "localhost") val context = System.getProperty("server.context", "/") val store = PersistentEntityStores.newInstance(Environments.newInstance("some path to app"), "teamsysstore") val server = embeddedServer(Jetty, port = appPort, host = appHost) { val webApplication = object : EmbeddableWebApplication(lookup = { listOf(store) }) { override fun PersistentEntityStoreImpl.isForcedlyReadonly() = true } HttpServer(webApplication, context).setup(this) } server.start(false) OS.launchBrowser(appHost, appPort, context) }
entity-browser-app/src/main/kotlin/jetbrains/xodus/browser/web/EmbeddableMain.kt
2254100106
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.refactoring import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil.isJavaIdentifierPart import com.intellij.openapi.util.text.StringUtil.isJavaIdentifierStart import com.intellij.psi.PsiElement import com.tang.intellij.lua.psi.LuaVisitor import java.util.* /** * RefactoringUtil * Created by tangzx on 2017/4/30. */ object LuaRefactoringUtil { fun getOccurrences(pattern: PsiElement, context: PsiElement?): List<PsiElement> { if (context == null) { return emptyList() } val occurrences = ArrayList<PsiElement>() val visitor = object : LuaVisitor() { override fun visitElement(element: PsiElement) { if (PsiEquivalenceUtil.areElementsEquivalent(element, pattern)) { occurrences.add(element) return } element.acceptChildren(this) } } context.acceptChildren(visitor) return occurrences } fun isLuaIdentifier(name: String): Boolean { return StringUtil.isJavaIdentifier(name) } fun isLuaTypeIdentifier(text: String): Boolean { val len = text.length if (len == 0) { return false } else if (!isJavaIdentifierStart(text[0])) { return false } else { for (i in 1 until len) { val c = text[i] if (!isJavaIdentifierPart(c) && c != '.') { return false } } return true } } }
src/main/java/com/tang/intellij/lua/refactoring/LuaRefactoringUtil.kt
428758784