content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.github.christophpickl.kpotpourri.http4k import com.fasterxml.jackson.core.type.TypeReference import com.github.christophpickl.kpotpourri.common.KPotpourriException import com.github.christophpickl.kpotpourri.http4k.BasicAuthMode.BasicAuthDisabled import com.github.christophpickl.kpotpourri.http4k.StatusCheckMode.Anything import com.github.christophpickl.kpotpourri.http4k.internal.HeadersMap import com.github.christophpickl.kpotpourri.http4k.internal.Http4kImpl import com.github.christophpickl.kpotpourri.http4k.internal.HttpClient import com.github.christophpickl.kpotpourri.http4k.internal.HttpClientFactoryDetector import com.github.christophpickl.kpotpourri.http4k.internal.MutableMetaMap import com.github.christophpickl.kpotpourri.http4k.internal.mapper import kotlin.reflect.KClass /** * Core entry point to build a [Http4k] instance in a DSL falvour. */ fun buildHttp4k(withBuilder: Http4kBuilder.() -> Unit = {}): Http4k { val builder = Http4kBuilder() withBuilder.invoke(builder) return builder.end() } /** * Http4k can be globally configured consisting of the following interfaces. */ interface GlobalHttp4kConfigurable : BaseUrlConfigurable, BasicAuthConfigurable, HeadersConfigurable, StatusCheckConfigurable, QueryParamConfigurable /** * Core DSL class to prepare a http4k instance, configuring global options (which can be overridden per request). */ class Http4kBuilder : GlobalHttp4kConfigurable { /** Global URL query parameters for each request. */ override val queryParams: MutableMap<String, String> = HashMap() /** Global HTTP headers. */ override val headers: HeadersMap = HeadersMap() /** By default the base URL is not defined/used and reach request must be an absolute URL. */ override var baseUrl: BaseUrl = NoBaseUrl /** By default basic authentication is disabled. */ override var basicAuth: BasicAuthMode = BasicAuthDisabled /** By default any HTTP status code is ok and will not throw an exception (depending on concrete HTTP implementation). */ override var statusCheck: StatusCheckMode = Anything internal var overrideHttpClient: HttpClient? = null /** Actually not visible to the outside, but still must be public for per-implementation extensions. */ val _implMetaMap = MutableMetaMap() /** * Detects (or using overridden) HTTP client implementation based on classpath availability. */ fun end(): Http4k { val restClient = if (overrideHttpClient != null) { overrideHttpClient!! } else { val httpClientFactory = HttpClientFactoryDetector().detect() httpClientFactory.build(_implMetaMap) } return Http4kImpl(restClient, this) } } // in order to reifie generic type, must not be in an interface /** Reified version of GET. */ inline fun <reified R : Any> Http4k.get(url: String, noinline withOpts: BodylessRequestOpts.() -> Unit = {}) = getGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of POST. */ inline fun <reified R : Any> Http4k.post(url: String, noinline withOpts: BodyfullRequestOpts.() -> Unit = {}) = postGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of PUT. */ inline fun <reified R : Any> Http4k.put(url: String, noinline withOpts: BodyfullRequestOpts.() -> Unit = {}) = putGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of DELETE. */ inline fun <reified R : Any> Http4k.delete(url: String, noinline withOpts: BodylessRequestOpts.() -> Unit = {}) = deleteGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of PATCH. */ inline fun <reified R : Any> Http4k.patch(url: String, noinline withOpts: BodyfullRequestOpts.() -> Unit = {}) = patchGeneric(url, object: TypeReference<R>() {}, withOpts) /** * Core interface to execute HTTP requests for any method (GET, POST, ...) configurable via request options. * * return type: either any jackson unmarshallable object, or an [Response4k] instance by default. * url: combined with optional global base URL * body: something which will be marshalled by jackson */ interface Http4k { /** GET response with explicity return type. */ fun <R : Any> getReturning(url: String, returnType: KClass<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** GET response for generic return types. */ fun <R : Any> getGeneric(url: String, returnType: TypeReference<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** POST response with return type set to [Response4k]. */ fun <R : Any> postAndReturnResponse(url: String, withOpts: BodyfullRequestOpts.() -> Unit = {}) = postReturning(url, Response4k::class, { withOpts(this) }) /** POST response with explicity return type. */ fun <R : Any> postReturning(url: String, returnType: KClass<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** POST response for generic return types. */ fun <R : Any> postGeneric(url: String, returnType: TypeReference<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** PUT response with return type set to [Response4k]. */ fun <R : Any> putAndReturnResponse(url: String, body: Any, withOpts: BodyfullRequestOpts.() -> Unit = {}) = putReturning(url, Response4k::class, { requestBody(body); withOpts(this) }) /** PUT response with explicity return type. */ fun <R : Any> putReturning(url: String, returnType: KClass<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** PUT response for generic return types. */ fun <R : Any> putGeneric(url: String, returnType: TypeReference<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** DELETE response with explicity return type. */ fun <R : Any> deleteReturning(url: String, returnType: KClass<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** DELETE response for generic return types. */ fun <R : Any> deleteGeneric(url: String, returnType: TypeReference<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** PATCH response with return type set to [Response4k]. */ fun <R : Any> patchAndReturnResponse(url: String, withOpts: BodyfullRequestOpts.() -> Unit = {}) = patchReturning(url, Response4k::class, { withOpts(this) }) /** PATCH response with explicity return type. */ fun <R : Any> patchReturning(url: String, returnType: KClass<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** PATCH response for generic return types. */ fun <R : Any> patchGeneric(url: String, returnType: TypeReference<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R } /** * Core request object abstraction. */ data class Request4k( val method: HttpMethod4k, val url: String, val headers: Map<String, String> = emptyMap(), val requestBody: DefiniteRequestBody? = null ) { companion object {}// for extensions init { // for simplicity sake no perfectly clean design but lazy check for data integrity if (!method.isRequestBodySupported && requestBody != null) { throw Http4kException("Invalid request! HTTP method [$method] does not support request body: $requestBody") } } /** * Don't render authorization header. */ override fun toString() = "Request4k(" + "method=$method, " + "url=$url, " + "headers=${headerWithoutAuthorizationSecret()}, " + "requestBody=<<$requestBody>>" + ")" private fun headerWithoutAuthorizationSecret(): Map<String, String> { val newHeaders = HashMap<String, String>(headers.size) headers.forEach { (k, v) -> if ("authorization" == k.toLowerCase()) { newHeaders += k to "xxxxx" } else { newHeaders += k to v } } return newHeaders } } /** * Core response object abstraction. */ data class Response4k( /** HTTP status code. */ val statusCode: StatusCode, /** Eagerly response body as a string. */ val bodyAsString: String, /** Response headers, obviously. */ val headers: Map<String, String> = emptyMap() ) { companion object // test extensions /** * Transform the response body to a custom JSON object. */ fun <T : Any> readJson(targetType: KClass<T>): T { // MINOR could do also here an annotation check (if option is enabled to do so) return mapper.readValue(bodyAsString, targetType.java) } } /** * Global custom exception type. */ open class Http4kException(message: String, cause: Exception? = null) : KPotpourriException(message, cause)
http4k/src/main/kotlin/com/github/christophpickl/kpotpourri/http4k/api.kt
3056232710
package uk.co.appsbystudio.geoshare.utils import android.app.Activity import android.app.Activity.RESULT_OK import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Environment import android.provider.MediaStore import android.widget.Toast import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.theartofdev.edmodo.cropper.CropImage import com.theartofdev.edmodo.cropper.CropImageView import uk.co.appsbystudio.geoshare.base.MainView import uk.co.appsbystudio.geoshare.setup.InitialSetupView import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* class ProfileSelectionResult(private var main: MainView? = null, private var initial: InitialSetupView? = null) { fun profilePictureResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?, uid: String?) { if (resultCode == RESULT_OK) { when (requestCode) { 1 -> { val imageFileName = "profile_picture" val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val image = File(storageDir, "$imageFileName.png") CropImage.activity(Uri.fromFile(image)) .setGuidelines(CropImageView.Guidelines.ON) .setAspectRatio(1, 1).setRequestedSize(256, 256) .setFixAspectRatio(true) .start(activity) } 2 -> { val uri = data!!.data if (uri != null) CropImage.activity(uri) .setGuidelines(CropImageView.Guidelines.ON) .setAspectRatio(1, 1).setRequestedSize(256, 256) .setFixAspectRatio(true).start(activity) } } } if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && data != null && uid != null) { val result = CropImage.getActivityResult(data) if (resultCode == RESULT_OK) { val resultUri = result.uri val storageReference = FirebaseStorage.getInstance().reference val profileRef = storageReference.child("profile_pictures/$uid.png") profileRef.putFile(resultUri) .addOnSuccessListener { FirebaseDatabase.getInstance().getReference("picture").child(uid).setValue(Date().time) initial?.onNext() try { val bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver, resultUri) val file = File(activity.cacheDir, "$uid.png") val fileOutputStream = FileOutputStream(file) bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream) main?.updateProfilePicture() } catch (e: IOException) { e.printStackTrace() } }.addOnFailureListener { Toast.makeText(activity, "Hmm...Something went wrong.\nPlease check your internet connection and try again.", Toast.LENGTH_LONG).show() } } } } }
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/ProfileSelectionResult.kt
380270630
package net.yested.ext.moment import net.yested.core.properties.Property import net.yested.core.properties.bind @JsModule("moment") @JsNonModule @JsName("moment") external private fun moment_js(): MomentJs = definedExternally @JsModule("moment") @JsNonModule @JsName("moment") external private fun moment_js(millisecondsSinceUnixEpoch: Double): MomentJs = definedExternally @JsModule("moment") @JsNonModule @JsName("moment") external private fun moment_js(input: String, format: String = definedExternally): MomentJs = definedExternally external class MomentJs { fun format(formatString: String? = definedExternally): String = definedExternally // This would be Long except that Kotlin's Long is a Javascript Object. fun valueOf(): Number = definedExternally fun millisecond(value: Int? = definedExternally): Int = definedExternally fun second(value: Int? = definedExternally): Int = definedExternally fun minute(value: Int? = definedExternally): Int = definedExternally fun hour(value: Int? = definedExternally): Int = definedExternally fun date(value: Int? = definedExternally): Int = definedExternally fun day(value: Int? = definedExternally): Int = definedExternally fun weekday(value: Int? = definedExternally): Int = definedExternally fun isoWeekday(value: Int? = definedExternally): Int = definedExternally fun dayOfYear(value: Int? = definedExternally): Int = definedExternally fun week(value: Int? = definedExternally): Int = definedExternally fun isoWeek(value: Int? = definedExternally): Int = definedExternally fun month(value: Int? = definedExternally): Int = definedExternally fun quarter(value: Int? = definedExternally): Int = definedExternally fun year(value: Int? = definedExternally): Int = definedExternally fun weekYear(value: Int? = definedExternally): Int = definedExternally fun isoWeekYear(value: Int? = definedExternally): Int = definedExternally fun weeksInYear(): Int = definedExternally fun locale(localeName: String): Unit = definedExternally fun unix():Int = definedExternally fun unix(t:Int): Unit = definedExternally } class Moment(private val moment: MomentJs) { /** Returns the default ISO format: 2018-03-22T05:55:49-06:00 */ fun format(): String = moment.format() fun format(format: String): String = moment.format(format) fun format(format: FormatString): String = moment.format(format.toString()) val millisecondsSinceUnixEpoch: Long get() = moment.valueOf().toLong() var unix: Int get() = moment.unix() set(value) { moment.unix(value) } var millisecond: Int get() = moment.millisecond() set(value) { moment.millisecond(value) } var second: Int get() = moment.second() set(value) { moment.second(value) } var minute: Int get() = moment.minute() set(value) { moment.minute(value) } var hour: Int get() = moment.hour() set(value) { moment.hour(value) } var dayOfMonth: Int get() = moment.date() set(value) { moment.date(value) } var dayOfYear: Int get() = moment.dayOfYear() set(value) { moment.dayOfYear(value) } var month: Int get() = moment.month() set(value) { moment.month(value) } var year: Int get() = moment.year() set(value) { moment.year(value) } companion object { fun now(): Moment = Moment(moment_js()) fun parse(input: String): Moment = Moment(moment_js(input)) fun parse(input: String, format: String): Moment = Moment(moment_js(input, format)) fun parseMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Long): Moment { return fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch) } fun fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Long): Moment { requireNotNull(millisecondsSinceUnixEpoch) return fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch.toDouble()) } fun fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Double): Moment { requireNotNull(millisecondsSinceUnixEpoch) return Moment(moment_js(millisecondsSinceUnixEpoch)) } fun setLocale(localeName: String) { moment_js().locale(localeName) } } } class FormatElement (val str: String) { fun plus(b: FormatElement): FormatString { return FormatString(arrayListOf(this, b)) } operator fun plus(b: String): FormatString { return FormatString(arrayListOf(this, FormatElement(b))) } } class FormatString(private val elements: MutableList<FormatElement> = arrayListOf()) { operator fun plus(b: FormatElement): FormatString { elements.add(b) return FormatString(elements) } operator fun plus(b: String): FormatString { elements.add(FormatElement(b)) return FormatString(elements) } override fun toString(): String = elements.map { it.str }.joinToString(separator = "") } class Digit(private val oneDigitFactory: ()-> FormatElement, private val twoDigitsFactory: ()-> FormatElement, private val fourDigitsFactory: ()-> FormatElement) { val oneDigit: FormatElement get() = oneDigitFactory() val twoDigits: FormatElement get() = twoDigitsFactory() val fourDigits: FormatElement get() = fourDigitsFactory() } class FormatStringBuilder() { val year: Digit = Digit({throw UnsupportedOperationException("bla")}, {FormatElement("YY")}, {FormatElement("YYYY")}) val month: Digit = Digit({FormatElement("M")}, {FormatElement("MM")}, {throw UnsupportedOperationException()}) val dayOfMonth: Digit = Digit({FormatElement("D")}, {FormatElement("DD")}, {throw UnsupportedOperationException()}) val hour24: Digit = Digit({FormatElement("H")}, {FormatElement("HH")}, {throw UnsupportedOperationException()}) val hour12: Digit = Digit({FormatElement("h")}, {FormatElement("hh")}, {throw UnsupportedOperationException()}) val minutes: Digit = Digit({FormatElement("m")}, {FormatElement("mm")}, {throw UnsupportedOperationException()}) val seconds: Digit = Digit({FormatElement("s")}, {FormatElement("ss")}, {throw UnsupportedOperationException()}) } fun format(init: FormatStringBuilder.() -> FormatString): FormatString { return FormatStringBuilder().init() } fun Property<Moment?>.asText(formatString: String): Property<String> { return this.bind( transform = { if (it == null) "" else it.format(formatString) }, reverse = { if (it.isEmpty()) null else Moment.parse(it, formatString) }) }
src/jsMain/kotlin/net/yested/ext/moment/moment.kt
3958157178
// Copyright Kevin D.Hall 2018 package com.khallware.api.util import java.sql.DriverManager import java.sql.Connection import java.sql.Statement import java.util.Properties import java.math.BigDecimal class Datastore(props: Properties) { var initialized = false var connection : Connection? = null val jdbcurl = props.getProperty("jdbc_url","jdbc:sqlite:apis.db") val driver = props.getProperty("jdbc_driver", "org.sqlite.JDBC") fun initialize() { if (!initialized) { Class.forName(driver).newInstance() connection = DriverManager.getConnection(jdbcurl) } initialized = true } fun listTags() : ArrayList<Tag> { val retval = ArrayList<Tag>() val sql = "SELECT id,name FROM tags" initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Tag( getInt("id"), getString("name"))) } } } return(retval) } fun addTag(tag: Tag, parent: Int = 1) : Int { var retval = -1 val sql = """ INSERT INTO tags (name,user,group_,parent) VALUES (?,?,?,?) """ initialize() connection!!.prepareStatement( sql, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, tag.name) it.setInt(2, tag.user) it.setInt(3, tag.group) it.setInt(4, parent) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { retval = rsltset.getInt(1) } } return(retval) } fun listBookmarks() : ArrayList<Bookmark> { val retval = ArrayList<Bookmark>() val sql = """ SELECT id,name,url,rating, ( SELECT count(*) FROM bookmark_tags WHERE bookmark = b.id ) AS numtags FROM bookmarks b """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Bookmark( getInt("id"), getString("name"), getString("url"), getString("rating"), getInt("numtags"))) } } } return(retval) } fun addBookmark(bookmark: Bookmark, tag: Int = 1) { val sql1 = """ INSERT INTO bookmarks (name,user,url,group_,rating) VALUES (?,?,?,?,?) """ val sql2 = """ INSERT INTO bookmark_tags (bookmark,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, bookmark.name) it.setInt(2, bookmark.user) it.setString(3, bookmark.url) it.setInt(4, bookmark.group) it.setString(5, bookmark.rating) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun listLocations() : ArrayList<Location> { val retval = ArrayList<Location>() val sql = """ SELECT id,name,latitude,longitude,address, description, ( SELECT count(*) FROM location_tags WHERE location = l.id ) AS numtags FROM locations l """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Location( getInt("id"), getString("name"), BigDecimal(getDouble("lat")), BigDecimal(getDouble("lon")), getString("address"), getString("description"), getInt("numtags"))) } } } return(retval) } fun listContacts() : ArrayList<Contact> { val retval = ArrayList<Contact>() val sql = """ SELECT id,name,uid,email,phone,title,address, organization,vcard,description, ( SELECT count(*) FROM contact_tags WHERE contact = c.id ) AS numtags FROM contacts c """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Contact( getInt("id"), getString("name"), getString("uid"), getString("email"), getString("phone"), getString("title"), getString("address"), getString("organization"), getString("vcard"), getString("description"), getInt("numtags"))) } } } return(retval) } fun listPhotos() : ArrayList<Photo> { val retval = ArrayList<Photo>() val sql = """ SELECT id,name,path,md5sum,description, ( SELECT count(*) FROM photo_tags WHERE photo = p.id ) AS numtags FROM photos p """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Photo( getInt("id"), getString("name"), getString("path"), getString("md5sum"), getString("description"), getInt("numtags"))) } } } return(retval) } fun addPhoto(photo: Photo, tag: Int = 1) { val sql1 = """ INSERT INTO photos (name,path,md5sum,user,group_, description) VALUES (?,?,?,?,?,?) """ val sql2 = """ INSERT INTO photo_tags (photo,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, photo.name) it.setString(2, photo.path) it.setString(3, photo.md5sum) it.setInt(4, photo.user) it.setInt(5, photo.group) it.setString(6, photo.desc) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun listFileItems() : ArrayList<FileItem> { val retval = ArrayList<FileItem>() val sql = """ SELECT id,name,ext,mime,path,md5sum,description, ( SELECT count(*) FROM fileitem_tags WHERE fileitem = f.id ) AS numtags FROM fileitems f """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(FileItem( getInt("id"), getString("name"), getString("ext"), getString("md5sum"), getString("description"), getString("mime"), getString("path"), getInt("numtags"))) } } } return(retval) } fun addFileItem(fileitem: FileItem, tag: Int = 1) { val sql1 = """ INSERT INTO fileitems (name,ext,mime,path,md5sum, user,group_, description) VALUES (?,?,?,?,?,?,?,?) """ val sql2 = """ INSERT INTO fileitem_tags (fileitem,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, fileitem.name) it.setString(2, fileitem.ext) it.setString(3, fileitem.mime) it.setString(4, fileitem.path) it.setString(5, fileitem.md5sum) it.setInt(6, fileitem.user) it.setInt(7, fileitem.group) it.setString(8, fileitem.desc) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun addSound(sound: Sound, tag: Int = 1) { val sql1 = """ INSERT INTO sounds (name,path,md5sum, user,group_,description,title,artist,genre, album,publisher) VALUES (?,?,?,?,?,?,?,?,?,?,?) """ val sql2 = """ INSERT INTO sound_tags (sound,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, sound.name) it.setString(2, sound.path) it.setString(3, sound.md5sum) it.setInt(4, sound.user) it.setInt(5, sound.group) it.setString(6, sound.desc) it.setString(7, sound.title) it.setString(8, sound.artist) it.setString(9, sound.genre) it.setString(10, sound.album) it.setString(11, sound.publisher) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun listSounds() : ArrayList<Sound> { val retval = ArrayList<Sound>() val sql = """ SELECT id,name,path,md5sum,title,artist,genre, album,publisher,description, ( SELECT count(*) FROM sound_tags WHERE sound = s.id ) AS numtags FROM sounds s """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Sound( getInt("id"), getString("name"), getString("path"), getString("md5sum"), getString("description"), getString("title"), getString("artist"), getString("genre"), getString("album"), getString("publisher"), getInt("numtags"))) } } } return(retval) } fun listVideos() : ArrayList<Video> { val retval = ArrayList<Video>() val sql = """ SELECT id,name,path,md5sum,description, ( SELECT count(*) FROM video_tags WHERE video = v.id ) AS numtags FROM videos v """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Video( getInt("id"), getString("name"), getString("path"), getString("md5sum"), getString("description"), getInt("numtags"))) } } } return(retval) } fun addVideo(video: Video, tag: Int = 1) { val sql1 = """ INSERT INTO videos (name,path,md5sum,user,group_, description) VALUES (?,?,?,?,?,?) """ val sql2 = """ INSERT INTO video_tags (video,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, video.name) it.setString(2, video.path) it.setString(3, video.md5sum) it.setInt(4, video.user) it.setInt(5, video.group) it.setString(6, video.desc) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } }
tools/src/main/kotlin/com/khallware/api/util/datastore.kt
1837266634
package com.jetbrains.rider.plugins.unity.run import com.intellij.openapi.project.Project import com.jetbrains.rider.plugins.unity.run.configurations.UnityDebugConfigurationType import com.jetbrains.rider.plugins.unity.run.configurations.unityExe.UnityExeConfigurationType import com.jetbrains.rider.run.configurations.RiderNewRunConfigurationTreeGroupingProvider import icons.UnityIcons class UnityNewRunConfigurationTreeGroupingProvider: RiderNewRunConfigurationTreeGroupingProvider { override fun getGroups(project: Project): List<RiderNewRunConfigurationTreeGroupingProvider.Group> { return listOf(RiderNewRunConfigurationTreeGroupingProvider.Group( UnityIcons.Icons.UnityLogo, "Unity", listOf( UnityDebugConfigurationType.id, UnityExeConfigurationType.id ) )) } }
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/UnityNewRunConfigurationTreeGroupingProvider.kt
1669364593
package elite.gils.country /** * Continent: (Name) * Country: (Name) */ enum class AU private constructor( //Leave the code below alone (unless optimizing) private val name: String) { //List of State/Province names (Use 2 Letter/Number Combination codes) /** * Name: */ AA("Example"), /** * Name: */ AB("Example"), /** * Name: */ AC("Example"); fun getName(state: AU): String { return state.name } }
ObjectAvoidance/kotlin/src/elite/gils/country/AU.kt
1579715406
package de.markhaehnel.rbtv.rocketbeanstv.ui.common /** * Generic interface for retry buttons. */ interface RetryCallback { fun retry() }
app/src/main/java/de/markhaehnel/rbtv/rocketbeanstv/ui/common/RetryCallback.kt
3448496694
package org.fdroid.download import io.ktor.http.URLBuilder import io.ktor.http.URLParserException import io.ktor.http.Url import io.ktor.http.appendPathSegments import mu.KotlinLogging public data class Mirror @JvmOverloads constructor( val baseUrl: String, val location: String? = null, ) { public val url: Url by lazy { try { URLBuilder(baseUrl.trimEnd('/')).build() // we fall back to a non-existent URL if someone tries to sneak in an invalid mirror URL to crash us // to make it easier for potential callers } catch (e: URLParserException) { val log = KotlinLogging.logger {} log.warn { "Someone gave us an invalid URL: $baseUrl" } URLBuilder("http://127.0.0.1:64335").build() } catch (e: IllegalArgumentException) { val log = KotlinLogging.logger {} log.warn { "Someone gave us an invalid URL: $baseUrl" } URLBuilder("http://127.0.0.1:64335").build() } } public fun getUrl(path: String): Url { return URLBuilder(url).appendPathSegments(path).build() } public fun isOnion(): Boolean = url.isOnion() public fun isLocal(): Boolean = url.isLocal() public fun isHttp(): Boolean = url.protocol.name.startsWith("http") public companion object { @JvmStatic public fun fromStrings(list: List<String>): List<Mirror> = list.map { Mirror(it) } } } internal fun Mirror?.isLocal(): Boolean = this?.isLocal() == true internal fun Url.isOnion(): Boolean = host.endsWith(".onion") /** * Returns true when no proxy should be used for connecting to this [Url]. */ internal fun Url.isLocal(): Boolean { if (!host.matches(Regex("[0-9.]{7,15}"))) return false if (host.startsWith("172.")) { val second = host.substring(4..6) if (!second.endsWith('.')) return false val num = second.trimEnd('.').toIntOrNull() ?: return false return num in 16..31 } return host.startsWith("169.254.") || host.startsWith("10.") || host.startsWith("192.168.") || host == "127.0.0.1" }
libs/download/src/commonMain/kotlin/org/fdroid/download/Mirror.kt
2355341609
package com.wenhaiz.himusic.module.playhistory import android.content.Context import com.wenhaiz.himusic.base.BasePresenter import com.wenhaiz.himusic.base.BaseView import com.wenhaiz.himusic.data.bean.PlayHistory interface PlayHistoryContract { interface View : BaseView<Presenter> { fun onPlayHistoryLoad(playHistory: List<PlayHistory>) fun onNoPlayHistory() } interface Presenter : BasePresenter { fun loadPlayHistory(context: Context) } }
app/src/main/java/com/wenhaiz/himusic/module/playhistory/PlayHistoryContract.kt
4123625598
package org.koin.androidx.experimental.dsl import androidx.lifecycle.ViewModel import org.koin.androidx.viewmodel.dsl.setIsViewModel import org.koin.core.definition.BeanDefinition import org.koin.core.qualifier.Qualifier import org.koin.dsl.ScopeDSL import org.koin.experimental.builder.create /** * ViewModel DSL Extension * Allow to declare a ViewModel - be later inject into Activity/Fragment with dedicated injector * * @author Arnaud Giuliani * * @param qualifier - definition qualifier * @param override - allow definition override */ inline fun <reified T : ViewModel> ScopeDSL.viewModel( qualifier: Qualifier? = null, override: Boolean = false ): BeanDefinition<T> { val factory = factory(qualifier, override) { create<T>() } factory.setIsViewModel() return factory }
koin-projects/koin-androidx-ext/src/main/java/org/koin/androidx/experimental/dsl/ScopeSetExt.kt
4233774752
@file:Suppress( "INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "unused", "PropertyName" ) package com.supercilex.robotscouter.server.utils.types import kotlin.js.Json import kotlin.js.Promise val functions by lazy { js("require('firebase-functions')").unsafeCast<Functions>() } val admin by lazy { val admin = js("require('firebase-admin')").unsafeCast<Admin>() admin.initializeApp() admin } external val SDK_VERSION: String = definedExternally external val apps: Array<App> = definedExternally external interface AppOptions { var credential: Credential? get() = definedExternally; set(value) = definedExternally var databaseAuthVariableOverride: Any? get() = definedExternally; set(value) = definedExternally var databaseURL: String? get() = definedExternally; set(value) = definedExternally var storageBucket: String? get() = definedExternally; set(value) = definedExternally var projectId: String? get() = definedExternally; set(value) = definedExternally } external interface Credential { fun getAccessToken(): Promise<GoogleOAuthAccessToken> } external interface GoogleOAuthAccessToken { val access_token: String val expires_in: Number } external interface App { val name: String val options: AppOptions fun firestore(): Firestore fun delete(): Promise<Unit> } external interface AuthContext { var uid: String var token: Any } external interface EventContext { val eventId: String val timestamp: String val eventType: String val params: Json val authType: String? get() = definedExternally val auth: AuthContext? get() = definedExternally } external class Change<out T>(before: T? = definedExternally, after: T? = definedExternally) { val before: T = definedExternally val after: T = definedExternally companion object { fun <T> fromObjects(before: T, after: T): Change<T> = definedExternally fun <T> fromJSON(json: ChangeJson, customizer: ((any: Any) -> T)? = definedExternally): Change<T> = definedExternally } } external interface ChangeJson { val before: Any? get() = definedExternally val after: Any? get() = definedExternally val fieldMask: String? get() = definedExternally } external class Functions { val firestore: NamespaceBuilder = definedExternally val pubsub: Pubsub = definedExternally val https: Https = definedExternally val auth: FunctionsAuth = definedExternally fun runWith(options: dynamic): Functions fun config(): dynamic } external class Admin { fun initializeApp(options: AppOptions? = definedExternally, name: String? = definedExternally): App = definedExternally fun app(name: String? = definedExternally): App = definedExternally fun firestore(app: App? = definedExternally): Firestore = definedExternally fun auth(app: App? = definedExternally): Auth = definedExternally }
app/server/functions/src/main/kotlin/com/supercilex/robotscouter/server/utils/types/Functions.kt
2400735920
package io.jentz.winter.compiler import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.metadata.ImmutableKmProperty import com.squareup.kotlinpoet.metadata.ImmutableKmType import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview import kotlinx.metadata.Flag import kotlinx.metadata.KmClassifier import kotlinx.metadata.KmProperty import kotlinx.metadata.jvm.jvmInternalName @KotlinPoetMetadataPreview val ImmutableKmProperty.hasAccessibleSetter: Boolean get() = Flag.IS_PUBLIC(setterFlags) || Flag.IS_INTERNAL(setterFlags) val KmProperty.isNullable: Boolean get() = Flag.Type.IS_NULLABLE(returnType.flags) @KotlinPoetMetadataPreview fun ImmutableKmType.asTypeName(): TypeName { val tokens = (classifier as KmClassifier.Class).name.jvmInternalName.split("/") val packageParts = tokens.dropLast(1) val classParts = tokens.last().split("$") val className = ClassName(packageParts.joinToString("."), *classParts.toTypedArray()) if (arguments.isNotEmpty()) { val args = arguments.mapNotNull { it.type?.asTypeName() } return className.parameterizedBy(args) } return className }
winter-compiler/src/main/java/io/jentz/winter/compiler/KotlinMetadataExt.kt
1357798766
package me.mrkirby153.KirBot.command.args class ArgumentParseException(msg: String) : Exception(msg)
src/main/kotlin/me/mrkirby153/KirBot/command/args/ArgumentParseException.kt
3943396762
package com.youniversals.playupgo.flux.model import com.youniversals.playupgo.api.RestApi import com.youniversals.playupgo.data.Sport import rx.Observable /** * YOYO HOLDINGS * @author A-Ar Andrew Concepcion * * * @since 20/12/2016 */ class SportModel(restApi: RestApi) { private var mRestApi: RestApi = restApi fun getSports(): Observable<List<Sport>> { return mRestApi.getSports() } fun getSport(id: Long): Observable<Sport> { return mRestApi.getSport(id) } }
app/src/main/java/com/youniversals/playupgo/flux/model/SportModel.kt
3334033601
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.mappers import app.tivi.data.entities.ImageType import app.tivi.data.entities.ShowTmdbImage import app.tivi.data.entities.TiviShow import com.uwetrottmann.tmdb2.entities.TvShowResultsPage import javax.inject.Inject import javax.inject.Singleton @Singleton class TmdbShowResultsPageToTiviShows @Inject constructor( private val tmdbShowMapper: TmdbBaseShowToTiviShow ) : Mapper<TvShowResultsPage, List<Pair<TiviShow, List<ShowTmdbImage>>>> { override suspend fun map(from: TvShowResultsPage): List<Pair<TiviShow, List<ShowTmdbImage>>> { return from.results.map { val show = tmdbShowMapper.map(it) val images = ArrayList<ShowTmdbImage>() if (it.poster_path != null) { images += ShowTmdbImage( showId = 0, path = it.poster_path, isPrimary = true, type = ImageType.POSTER ) } if (it.backdrop_path != null) { images += ShowTmdbImage( showId = 0, path = it.backdrop_path, isPrimary = true, type = ImageType.BACKDROP ) } show to images } } }
data/src/main/java/app/tivi/data/mappers/TmdbShowResultsPageToTiviShows.kt
105956447
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.actions.api import com.google.actions.api.response.ResponseBuilder import org.slf4j.LoggerFactory import java.util.concurrent.CompletableFuture /** * Default implementation of an Actions App. This class provides most of the * functionality of an App such as request parsing and routing. */ abstract class DefaultApp : App { val errorMsg_badReturnValue = "The return value of an intent handler" + " must be ActionResponse or CompletableFuture<ActionResponse>" private companion object { val LOG = LoggerFactory.getLogger(DefaultApp::class.java.name) } /** * Creates an ActionRequest for the specified JSON and metadata. * @param inputJson The input JSON. * @param headers Map containing metadata, usually from the HTTP request * headers. */ abstract fun createRequest(inputJson: String, headers: Map<*, *>?): ActionRequest /** * @return A ResponseBuilder for this App. */ abstract fun getResponseBuilder(request: ActionRequest): ResponseBuilder override fun handleRequest( inputJson: String?, headers: Map<*, *>?): CompletableFuture<String> { if (inputJson == null || inputJson.isEmpty()) { return handleError("Invalid or empty JSON") } val request: ActionRequest val future: CompletableFuture<ActionResponse> try { request = createRequest(inputJson, headers) future = routeRequest(request) } catch (e: Exception) { return handleError(e) } return future .thenApply { it.toJson() } .exceptionally { throwable -> throwable.message } } @Throws(Exception::class) fun routeRequest(request: ActionRequest): CompletableFuture<ActionResponse> { val intent = request.intent val forIntentType = ForIntent::class.java for (method in javaClass.declaredMethods) { if (method.isAnnotationPresent(forIntentType)) { val annotation = method.getAnnotation(forIntentType) val forIntent = annotation as ForIntent if (forIntent.value == intent) { val result = method.invoke(this, request) return if (result is ActionResponse) { CompletableFuture.completedFuture(result) } else if (result is CompletableFuture<*>) { result as CompletableFuture<ActionResponse> } else { LOG.warn(errorMsg_badReturnValue) throw Exception(errorMsg_badReturnValue) } } } } // Unable to find a method with the annotation matching the intent. LOG.warn("Intent handler not found: {}", intent) throw Exception("Intent handler not found - $intent") } fun handleError(exception: Exception): CompletableFuture<String> { exception.printStackTrace() return handleError(exception.message) } private fun handleError(message: String?): CompletableFuture<String> { val future = CompletableFuture<String>() future.completeExceptionally(Exception(message)) return future } }
src/main/kotlin/com/google/actions/api/DefaultApp.kt
420660186
package org.ozinger.ika.service.command.commands import org.jetbrains.exposed.sql.transactions.transaction import org.ozinger.ika.annotation.ServiceCommand import org.ozinger.ika.channel.OutgoingPacketChannel import org.ozinger.ika.command.CHGHOST import org.ozinger.ika.command.FMODE import org.ozinger.ika.command.NOTICE import org.ozinger.ika.database.models.Account import org.ozinger.ika.definition.* import org.ozinger.ika.enumeration.Permission import org.ozinger.ika.serialization.format.IRCFormat import org.ozinger.ika.serialization.serializer.ChannelModeChangelistSerializer import org.ozinger.ika.serialization.serializer.UserModeChangelistSerializer import org.ozinger.ika.service.Service import org.ozinger.ika.state.IRCChannels import org.ozinger.ika.state.IRCUsers object AdminServiceCommands { @ServiceCommand( name = "공지", aliases = ["ANN", "ANNOUNCE"], syntax = "<내용>", summary = "모든 IRC 채널에 공지사항을 출력합니다.", description = "NOTICE를 이용해 채널 라인으로 출력하므로 주의하십시오.\n" + "명령을 실행하는 순간 발송하므로 명령을 실행하기 전 다시 한번 공지사항의 내용을 확인해주세요.\n", permission = Permission.ADMIN, ) suspend fun announce(sender: UniversalUserId, content: String) { Service.sendMessageAsServiceUser(sender, "${IRCChannels.size}개 채널에 공지사항을 발송합니다.") IRCChannels.forEach { Service.sendAsServiceUser(NOTICE(it.name, " \u0002[공지]\u0002 $content")) } Service.sendMessageAsServiceUser(sender, "${IRCChannels.size}개 채널에 공지사항을 발송했습니다.") } @ServiceCommand( name = "모드", aliases = ["MODE"], syntax = "<대상> {모드}", summary = "특정 대상의 모드를 강제로 변경합니다.", description = "이 명령을 사용할 시 해당 유저 혹은 채널의 모드를 강제로 변경합니다.", permission = Permission.ADMIN, ) suspend fun mode(sender: UniversalUserId, target: String, modeChange: String) { if (target.startsWith("#")) { val channelName = ChannelName(target) if (channelName !in IRCChannels) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$target\u0002 채널이 존재하지 않습니다.") return } val ircChannel = IRCChannels[channelName] val modeChangelist = try { IRCFormat.decodeFromString(ChannelModeChangelistSerializer, modeChange) } catch (ex: Throwable) { Service.sendErrorMessageAsServiceUser(sender, "모드 파싱에 실패했습니다.") return } val transform = { mode: IMode -> if (mode is EphemeralMemberMode) { val user = IRCUsers.first { it.nickname.equals(mode.target, ignoreCase = true) } MemberMode(user.id, mode.mode) } else { mode } } val transformedModeChangelist = try { ModeChangelist( adding = modeChangelist.adding.map(transform).toSet(), removing = modeChangelist.removing.map(transform).toSet(), ) } catch (ex: NoSuchElementException) { Service.sendErrorMessageAsServiceUser(sender, "모드 변환에 실패했습니다.") return } Service.sendAsServiceUser(FMODE(channelName, ircChannel.timestamp, transformedModeChangelist)) Service.sendMessageAsServiceUser(sender, "\u0002$target\u0002 채널에 \u0002$modeChange\u0002 모드를 적용했습니다.") } else { val user = IRCUsers.firstOrNull { it.nickname.equals(target, ignoreCase = true) } if (user == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$target\u0002 사용자가 존재하지 않습니다.") return } val modeChangelist = try { IRCFormat.decodeFromString(UserModeChangelistSerializer, modeChange) } catch (ex: Throwable) { Service.sendErrorMessageAsServiceUser(sender, "모드 파싱에 실패했습니다.") return } Service.sendAsServiceUser(FMODE(user.id, user.timestamp, modeChangelist)) Service.sendMessageAsServiceUser(sender, "\u0002$target\u0002 사용자에 \u0002$modeChange\u0002 모드를 적용했습니다.") } } @ServiceCommand( name = "강제비밀번호변경", aliases = ["FCHANGEPASSWORD"], syntax = "<계정명> <새 비밀번호>", summary = "오징어 IRC 네트워크에 등록되어 있는 계정의 비밀번호를 강제로 변경합니다.", description = "이 명령을 사용할 시 해당 계정의 비밀번호를 강제로 변경합니다.", permission = Permission.ADMIN, ) suspend fun forceChangePassword(sender: UniversalUserId, accountName: String, password: String) { val account = transaction { Account.getByNickname(accountName) } if (account == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정이 존재하지 않습니다.") return } transaction { account.changePassword(password) } Service.sendMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 비밀번호가 \u0002${password}\u0002 (으)로 강제 변경되었습니다." ) } @ServiceCommand( name = "강제가상호스트변경", aliases = ["FCHANGEVHOST"], syntax = "<계정명> [새 가상 호스트]", summary = "오징어 IRC 네트워크에 등록되어 있는 계정의 가상 호스트를 강제로 변경합니다.", description = "이 명령을 사용할 시 해당 계정의 가상 호스트를 강제로 설정하거나 삭제할 수 있습니다.", permission = Permission.ADMIN, ) suspend fun forceChangeVhost(sender: UniversalUserId, accountName: String, vhost: String?) { val account = transaction { Account.getByNickname(accountName) } if (account == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정이 존재하지 않습니다.") return } transaction { account.vhost = vhost ?: "" } if (vhost != null) { OutgoingPacketChannel.sendAsServer(CHGHOST(sender, vhost)) } Service.sendMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 가상 호스트가 \u0002${vhost}\u0002 (으)로 강제 변경되었습니다." ) } }
app/src/main/kotlin/org/ozinger/ika/service/command/commands/AdminServiceCommands.kt
2638173829
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.ty import org.rust.lang.core.psi.RsTypeParameter import org.rust.lang.core.resolve.ImplLookup typealias Substitution = Map<TyTypeParameter, Ty> typealias TypeMapping = MutableMap<TyTypeParameter, Ty> val emptySubstitution: Substitution = emptyMap() /** * Represents both a type, like `i32` or `S<Foo, Bar>`, as well * as an unbound constructor `S`. * * The name `Ty` is short for `Type`, inspired by the Rust * compiler. */ interface Ty { /** * Checks if `other` type may be represented as this type. * * Note that `t1.unifyWith(t2)` is not the same as `t2.unifyWith(t1)`. */ fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult /** * Substitute type parameters for their values * * This works for `struct S<T> { field: T }`, when we * know the type of `T` and want to find the type of `field`. */ fun substitute(subst: Substitution): Ty = this /** * Bindings between formal type parameters and actual type arguments. */ val typeParameterValues: Substitution get() = emptySubstitution /** * User visible string representation of a type */ override fun toString(): String } enum class Mutability { MUTABLE, IMMUTABLE; val isMut: Boolean get() = this == MUTABLE companion object { fun valueOf(mutable: Boolean): Mutability = if (mutable) MUTABLE else IMMUTABLE } } fun Ty.getTypeParameter(name: String): TyTypeParameter? { return typeParameterValues.keys.find { it.toString() == name } } fun getMoreCompleteType(ty1: Ty, ty2: Ty): Ty { return when { ty1 is TyUnknown -> ty2 ty1 is TyNever -> ty2 ty1 is TyInteger && ty2 is TyInteger && ty1.isKindWeak -> ty2 ty1 is TyFloat && ty2 is TyFloat && ty1.isKindWeak -> ty2 else -> ty1 } } fun Substitution.substituteInValues(map: Substitution): Substitution = mapValues { (_, value) -> value.substitute(map) } fun Substitution.get(psi: RsTypeParameter): Ty? { return get(TyTypeParameter.named((psi))) }
src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt
3822942590
/* * Copyright (C) 2021. Uber Technologies * * 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.uber.rib.compose.root.main.logged_in.tic_tac_toe import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.uber.rib.compose.util.EventStream @OptIn(ExperimentalFoundationApi::class) @Composable fun TicTacToeView(viewModel: State<TicTacToeViewModel>, eventStream: EventStream<TicTacToeEvent>) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top, modifier = Modifier .fillMaxSize() .background(Color.Blue) ) { Text("Current Player: ${viewModel.value.currentPlayer}", color = Color.White) Box( modifier = Modifier .aspectRatio(1f) .fillMaxSize() ) { LazyVerticalGrid(columns = GridCells.Fixed(3), modifier = Modifier.fillMaxSize()) { val board = viewModel.value.board items(9) { i -> val row = i / 3 val col = i % 3 Text( text = when (board.cells[row][col]) { Board.MarkerType.CROSS -> "X" Board.MarkerType.NOUGHT -> "O" else -> " " }, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .padding(16.dp) .background(Color.LightGray) .clickable( enabled = board.cells[row][col] == null, onClick = { eventStream.notify(TicTacToeEvent.BoardClick(BoardCoordinate(row, col))) } ) .padding(32.dp) ) } } } } } @Preview @Composable fun ProductSelectionViewPreview() { val board = Board() board.cells[0][2] = Board.MarkerType.CROSS board.cells[1][0] = Board.MarkerType.NOUGHT board.cells[2][1] = Board.MarkerType.CROSS val viewModel = remember { mutableStateOf(TicTacToeViewModel("James", board)) } TicTacToeView(viewModel, EventStream()) }
android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_in/tic_tac_toe/TicTacToeView.kt
2263818497
package wu.seal.jsontokotlin.model.codeelements /** * Name class * Created by Seal.Wu on 2017/9/21. */ interface IKName { fun getName(rawName: String): String } abstract class KName : IKName { private val suffix = "X" protected val illegalNameList = listOf( "as", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", "interface", "is", "null" , "object", "package", "return", "super", "this", "throw", "true", "try", "typealias", "val", "var", "when", "while" ) protected val illegalCharacter = listOf( "\\+", "\\-", "\\*", "/", "%", "=", "&", "\\|", "!", "\\[", "\\]", "\\{", "\\}", "\\(", "\\)", "\\\\", "\"", "_" , ",", ":", "\\?", "\\>", "\\<", "@", ";", "'", "\\`", "\\~", "\\$", "\\^", "#", "\\", "/", " ", "\t", "\n" ) protected val nameSeparator = listOf(" ", "_", "\\-", ":","\\.") /** * remove the start number or whiteSpace characters in this string */ protected fun removeStartNumberAndIllegalCharacter(it: String): String { val numberAndIllegalCharacters = listOf(*illegalCharacter.toTypedArray(), "\\d") val firstNumberAndIllegalCharactersRegex = "^(${numberAndIllegalCharacters.toRegex()})+".toRegex() return it.trim().replaceFirst(firstNumberAndIllegalCharactersRegex, "") } protected fun toBeLegalName(name: String): String { val tempName = name.replace(illegalCharacter.toRegex(), "") return if (tempName in illegalNameList) { tempName + suffix } else { tempName } } /** * array string into regex match patten that could match any element of the array */ protected fun Iterable<String>.toRegex() = joinToString(separator = "|").toRegex() }
src/main/kotlin/wu/seal/jsontokotlin/model/codeelements/KName.kt
4184185207
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.intellij.lang.annotations.Language import org.rust.lang.RsTestBase abstract class RsLineMarkerProviderTestBase : RsTestBase() { protected fun doTestByText(@Language("Rust") source: String) { myFixture.configureByText("lib.rs", source) myFixture.doHighlighting() val expected = markersFrom(source) val actual = markersFrom(myFixture.editor, myFixture.project) assertEquals(expected.joinToString(COMPARE_SEPARATOR), actual.joinToString(COMPARE_SEPARATOR)) } private fun markersFrom(text: String) = text.split('\n') .withIndex() .filter { it.value.contains(MARKER) } .map { Pair(it.index, it.value.substring(it.value.indexOf(MARKER) + MARKER.length).trim()) } private fun markersFrom(editor: Editor, project: Project) = DaemonCodeAnalyzerImpl.getLineMarkers(editor.document, project) .map { Pair(editor.document.getLineNumber(it.element?.textRange?.startOffset as Int), it.lineMarkerTooltip) } .sortedBy { it.first } private companion object { val MARKER = "// - " val COMPARE_SEPARATOR = " | " } }
src/test/kotlin/org/rust/ide/annotator/RsLineMarkerProviderTestBase.kt
4118678100
/* * Copyright (c) 2022, Nordic Semiconductor * 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. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.nrftoolbox.view import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import no.nordicsemi.android.theme.ScreenSection import no.nordicsemi.android.nrftoolbox.R @Composable fun FeatureButton( @DrawableRes iconId: Int, @StringRes nameCode: Int, @StringRes name: Int, isRunning: Boolean? = null, @StringRes description: Int? = null, onClick: () -> Unit ) { ScreenSection(onClick = onClick) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { val color = if (isRunning == true) { colorResource(id = R.color.nordicGrass) } else { MaterialTheme.colorScheme.secondary } Image( painter = painterResource(iconId), contentDescription = stringResource(id = name), contentScale = ContentScale.Crop, colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSecondary), modifier = Modifier .size(64.dp) .clip(CircleShape) .background(color) .padding(16.dp) ) Spacer(modifier = Modifier.size(16.dp)) Column(modifier = Modifier.weight(1f)) { Text( modifier = Modifier.fillMaxWidth(), text = stringResource(id = name), style = MaterialTheme.typography.bodyLarge, textAlign = TextAlign.Center ) description?.let { Spacer(modifier = Modifier.size(4.dp)) Text( modifier = Modifier.fillMaxWidth(), text = stringResource(id = it), style = MaterialTheme.typography.labelMedium, textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } } } @Preview @Composable private fun FeatureButtonPreview() { FeatureButton(R.drawable.ic_csc, R.string.csc_module, R.string.csc_module_full) { } }
app/src/main/java/no/nordicsemi/android/nrftoolbox/view/FeatureButton.kt
3095460114
package org.stt.gui.jfx import javafx.scene.Node import javafx.scene.control.Button internal class FramelessButton(node: Node) : Button() { private var releasedStyle = STYLE_NORMAL init { graphic = node style = STYLE_NORMAL setOnMousePressed { style = STYLE_PRESSED } setOnMouseReleased { style = releasedStyle } setOnMouseEntered { setStyleAndReleaseStyle(STYLE_HOVER) } setOnMouseExited { setStyleAndReleaseStyle(STYLE_NORMAL) } } private fun setStyleAndReleaseStyle(style: String) { setStyle(style) releasedStyle = style } companion object { private const val STYLE_HOVER = "-fx-background-color: transparent; -fx-padding: 5; -fx-effect: innershadow(gaussian, rgba(60, 100, 220, 0.8), 20, 0.5, 2, 2);" private const val STYLE_NORMAL = "-fx-background-color: transparent; -fx-padding: 5; -fx-effect: null" private const val STYLE_PRESSED = "-fx-background-color: transparent; -fx-padding: 7 4 3 6; -fx-effect: innershadow(gaussian, rgba(60, 100, 220, 0.8), 20, 0.5, 2, 2);" } }
src/main/kotlin/org/stt/gui/jfx/FramelessButton.kt
1876945220
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sdibt.korm.core.mapping.type import java.sql.ResultSet import java.util.* class DateTypeHandler : TypeHandler { override fun getValue(rs: ResultSet, index:Int): Date? { val result = rs.getTimestamp(index) if (rs.wasNull()) { return null } else { return result } } }
src/main/kotlin/com/sdibt/korm/core/mapping/type/DateTypeHandler.kt
1298781802
package com.morph.engine.script import com.morph.engine.core.Game import com.morph.engine.entities.Component import com.morph.engine.entities.Entity import com.morph.engine.util.ScriptUtils import java.util.* /** * Created on 7/5/2017. */ class ScriptContainer(private val game: Game) : Component() { private val behaviors: HashMap<String, EntityBehavior> = HashMap() fun addBehavior(filename: String) { ScriptUtils.getScriptBehaviorAsync(filename).subscribe({ behavior -> val eBehavior = behavior as EntityBehavior eBehavior.setGame(game) eBehavior.self = parent behaviors[filename] = eBehavior eBehavior.init() eBehavior.start() }) } fun replaceBehavior(filename: String, newBehavior: EntityBehavior) { newBehavior.setGame(game) newBehavior.self = parent behaviors.replace(filename, newBehavior) newBehavior.start() } fun removeBehavior(filename: String) { val behavior = behaviors[filename] behaviors.remove(filename) behavior?.destroy() } fun getBehaviors(): List<EntityBehavior> { return ArrayList<EntityBehavior>(behaviors.values) } }
src/main/kotlin/com/morph/engine/script/ScriptContainer.kt
2011030151
package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.SetStreamSerializers import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils import com.openlattice.collections.CollectionTemplateType import com.openlattice.collections.EntityTypeCollection import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.mapstores.TestDataFactory import org.springframework.stereotype.Component import java.util.* import kotlin.collections.LinkedHashSet @Component class EntityTypeCollectionStreamSerializer : TestableSelfRegisteringStreamSerializer<EntityTypeCollection> { override fun getTypeId(): Int { return StreamSerializerTypeIds.ENTITY_TYPE_COLLECTION.ordinal } override fun getClazz(): Class<out EntityTypeCollection> { return EntityTypeCollection::class.java } override fun write(out: ObjectDataOutput, `object`: EntityTypeCollection) { UUIDStreamSerializerUtils.serialize(out, `object`.id) FullQualifiedNameStreamSerializer.serialize(out, `object`.type) out.writeUTF(`object`.title) out.writeUTF(`object`.description) SetStreamSerializers.serialize(out, `object`.schemas, FullQualifiedNameStreamSerializer::serialize) out.writeInt(`object`.template.size) `object`.template.forEach { CollectionTemplateTypeStreamSerializer.serialize(out, it) } } override fun read(`in`: ObjectDataInput): EntityTypeCollection { val id = UUIDStreamSerializerUtils.deserialize(`in`) val type = FullQualifiedNameStreamSerializer.deserialize(`in`) val title = `in`.readUTF() val description = Optional.of(`in`.readUTF()) val schemas = SetStreamSerializers.deserialize(`in`, FullQualifiedNameStreamSerializer::deserialize) val templateSize = `in`.readInt() val template = LinkedHashSet<CollectionTemplateType>(templateSize) for (i in 0 until templateSize) { template.add(CollectionTemplateTypeStreamSerializer.deserialize(`in`)) } return EntityTypeCollection(id, type, title, description, schemas, template) } override fun generateTestValue(): EntityTypeCollection { return TestDataFactory.entityTypeCollection() } }
src/main/kotlin/com/openlattice/hazelcast/serializers/EntityTypeCollectionStreamSerializer.kt
59057151
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.moez.QKSMS.interactor.UpdateScheduledMessageAlarms import dagger.android.AndroidInjection import javax.inject.Inject class BootReceiver : BroadcastReceiver() { @Inject lateinit var updateScheduledMessageAlarms: UpdateScheduledMessageAlarms override fun onReceive(context: Context, intent: Intent?) { AndroidInjection.inject(this, context) val result = goAsync() updateScheduledMessageAlarms.execute(Unit) { result.finish() } } }
data/src/main/java/com/moez/QKSMS/receiver/BootReceiver.kt
3643518685
package nl.sjtek.control.data.parsers import com.google.gson.Gson import com.google.gson.JsonParseException import com.google.gson.reflect.TypeToken import nl.sjtek.control.data.staticdata.User object UserParser { fun parse(input: String?): UserHolder { val type = object : TypeToken<List<User>>() {}.type return try { UserHolder(Gson().fromJson(input, type)) } catch (e: JsonParseException) { UserHolder(exception = e) } } }
data/src/main/kotlin/nl/sjtek/control/data/parsers/UserParser.kt
1591601469
import org.junit.Assert import org.junit.Test class TestForLoop { @Test(timeout = 1000) fun testIterateOverDateRange() { val actualDateRange = arrayListOf<MyDate>() iterateOverDateRange(MyDate(2016, 5, 1), MyDate(2016, 5, 5)) { date -> actualDateRange.add(date) } val expectedDateRange = arrayListOf( MyDate(2016, 5, 1), MyDate(2016, 5, 2), MyDate(2016, 5, 3), MyDate(2016, 5, 4), MyDate(2016, 5, 5)) Assert.assertEquals("Incorrect iteration over the following dates:\n", expectedDateRange, actualDateRange) } @Test(timeout = 1000) fun testIterateOverEmptyRange() { var invoked = false iterateOverDateRange(MyDate(2016, 1, 1), MyDate(2015, 1, 1), { invoked = true }) Assert.assertFalse("Handler was invoked on an empty range:\n", invoked) } }
kotlin-koans/Conventions/For loop/test/tests.kt
3709043053
package i_introduction._5_String_Templates import util.TODO import util.doc5 fun example1(a: Any, b: Any) = "This is some text in which variables ($a, $b) appear." fun example2(a: Any, b: Any) = "You can write it in a Java way as well. Like this: " + a + ", " + b + "!" fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}" fun example4() = """ You can use raw strings to write multiline text. There is no escaping here, so raw strings are useful for writing regex patterns, you don't need to escape a backslash by a backslash. String template entries (${42}) are allowed here. """ fun getPattern() = """\d{2}\.\d{2}\.\d{4}""" fun example() = "13.06.1992".matches(getPattern().toRegex()) //true val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" fun todoTask5(): Nothing = TODO( """ Task 5. Copy the body of 'getPattern()' to the 'task5()' function below and rewrite it in such a way that it matches '13 JUN 1992'. Use the 'month' variable. """, documentation = doc5(), references = { getPattern(); month }) fun task5() = """\d{2} $month \d{4}"""
src/i_introduction/_5_String_Templates/n05StringTemplates.kt
3318858882
package org.http4k.serverless import com.google.cloud.functions.Context import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.format.Moshi import org.http4k.util.proxy import org.junit.jupiter.api.Test import java.util.concurrent.atomic.AtomicReference data class MyEvent(val value: String) class GoogleCloudEventFunctionTest { @Test fun `can build function and call it`() { val captured = AtomicReference<MyEvent>() val input = MyEvent("hello") val function = object : GoogleCloudEventFunction(FnLoader { FnHandler { e: MyEvent, _: Context -> captured.set(e) } }) {} function.accept(Moshi.asFormatString(input), proxy()) assertThat(captured.get(), equalTo(input)) } }
http4k-serverless/gcf/src/test/kotlin/org/http4k/serverless/GoogleCloudEventFunctionTest.kt
2432673988
package nl.ecci.hamers.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_hamers_tab.* import nl.ecci.hamers.R import nl.ecci.hamers.ui.adapters.EventFragmentAdapter class EventFragment : HamersTabFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_hamers_tab, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) tab_fragment_viewpager.adapter = EventFragmentAdapter(requireContext(), childFragmentManager) } override fun onResume() { super.onResume() activity?.title = resources.getString(R.string.navigation_item_events) } }
hamersapp/src/main/java/nl/ecci/hamers/ui/fragments/EventFragment.kt
3546378447
package me.sweetll.tucao.business.download.adapter import android.widget.CheckBox import android.widget.ImageView import android.widget.LinearLayout import com.chad.library.adapter.base.BaseMultiItemQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.chad.library.adapter.base.entity.MultiItemEntity import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.android.schedulers.AndroidSchedulers import me.sweetll.tucao.R import me.sweetll.tucao.business.download.DownloadActivity import me.sweetll.tucao.model.json.Part import me.sweetll.tucao.model.json.StateController import me.sweetll.tucao.model.json.Video import me.sweetll.tucao.business.video.VideoActivity import me.sweetll.tucao.extension.DownloadHelpers import me.sweetll.tucao.extension.load import me.sweetll.tucao.extension.logD import me.sweetll.tucao.extension.toast import me.sweetll.tucao.rxdownload.RxDownload import me.sweetll.tucao.rxdownload.entity.DownloadEvent import me.sweetll.tucao.rxdownload.entity.DownloadStatus import java.util.concurrent.TimeUnit class DownloadingVideoAdapter(val downloadActivity: DownloadActivity, data: MutableList<MultiItemEntity>?): BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder>(data) { companion object { const val TYPE_VIDEO = 0 const val TYPE_PART = 1 } val rxDownload: RxDownload by lazy { RxDownload.getInstance(mContext) } init { addItemType(TYPE_VIDEO, R.layout.item_downloaded_video) addItemType(TYPE_PART, R.layout.item_downloaded_part) } override fun convert(helper: BaseViewHolder, item: MultiItemEntity) { when (helper.itemViewType) { TYPE_VIDEO -> { val video = item as Video helper.setText(R.id.text_title, video.title) helper.setGone(R.id.text_size, false) val thumbImg = helper.getView<ImageView>(R.id.img_thumb) thumbImg.load(mContext, video.thumb) helper.setGone(R.id.checkbox, video.checkable) val checkBox = helper.getView<CheckBox>(R.id.checkbox) checkBox.isChecked = video.checked checkBox.setOnCheckedChangeListener { _, checked -> video.checked = checked updateMenu() } helper.itemView.setOnClickListener { if (video.checkable) { checkBox.isChecked = !checkBox.isChecked video.subItems.forEach { it.checked = checkBox.isChecked } if (video.isExpanded) { notifyItemRangeChanged(helper.adapterPosition + 1, video.subItems.size) } updateMenu() } else { if (video.isExpanded) { collapse(helper.adapterPosition) } else { expand(helper.adapterPosition) } } } helper.getView<LinearLayout>(R.id.linear_detail).setOnClickListener { VideoActivity.intentTo(mContext, video.hid) } } TYPE_PART -> { val part = item as Part part.stateController = StateController(helper.getView(R.id.text_size), helper.getView(R.id.img_status), helper.getView(R.id.progress)) helper.setText(R.id.text_title, part.title) rxDownload.receive(part.vid) .bindToLifecycle(downloadActivity) .sample(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ (status, downloadSize, totalSize) -> "接收下载状态....".logD() val newEvent = DownloadEvent(status, downloadSize, totalSize) if (part.flag == DownloadStatus.COMPLETED) { // DownloadHelpers.saveDownloadPart(part) } else { part.stateController?.setEvent(newEvent) } }, { error -> error.printStackTrace() error.message?.toast() }) helper.setGone(R.id.checkbox, part.checkable) val checkBox = helper.getView<CheckBox>(R.id.checkbox) checkBox.isChecked = part.checked checkBox.setOnCheckedChangeListener { _, checked -> part.checked = checked updateMenu() } helper.itemView.setOnClickListener { if (part.checkable) { checkBox.isChecked = !checkBox.isChecked val parentVideo = data.find { video -> (video is Video) && video.subItems.any { it.vid == part.vid } } as Video val currentPosition = parentVideo.subItems.indexOf(part) val newParentChecked = parentVideo.subItems.all(Part::checked) if (newParentChecked != parentVideo.checked) { parentVideo.checked = newParentChecked notifyItemChanged(helper.adapterPosition - 1 - currentPosition) } updateMenu() } else { val parentVideo = data.find { video -> (video is Video) && video.subItems.any { it.vid == part.vid } } as Video val callback = object : DownloadHelpers.Callback { override fun startDownload() { DownloadHelpers.resumeDownload(parentVideo, part) } override fun pauseDownload() { DownloadHelpers.pauseDownload(part) } } part.stateController?.handleClick(callback) } } } } } fun updateMenu() { val deleteEnabled = data.any { when (it) { is Video -> it.checked is Part -> it.checked else -> false } } val isPickAll = data.all { when (it) { is Video -> it.checked is Part -> it.checked else -> false } } downloadActivity.updateBottomMenu(deleteEnabled, isPickAll) } override fun getItemViewType(position: Int): Int { val type = super.getItemViewType(position) return type } }
app/src/main/kotlin/me/sweetll/tucao/business/download/adapter/DownloadingVideoAdapter.kt
1367234095
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.savingsaccountactivate import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.fragment.app.DialogFragment import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.mifos.api.GenericResponse import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.mifosxdroid.core.util.Toaster import com.mifos.mifosxdroid.uihelpers.MFDatePicker import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener import com.mifos.objects.accounts.savings.DepositType import com.mifos.utils.Constants import com.mifos.utils.DateHelper import com.mifos.utils.FragmentConstants import com.mifos.utils.SafeUIBlockingUtility import java.util.* import javax.inject.Inject /** * Created by Tarun on 01/06/17. * Fragment to allow user to select a date for account approval. * It uses the same layout as Savings Account Approve Fragment. */ class SavingsAccountActivateFragment : MifosBaseFragment(), OnDatePickListener, SavingsAccountActivateMvpView { val LOG_TAG = javaClass.simpleName @JvmField @BindView(R.id.tv_approval_date_on) var tvActivateDateHeading: TextView? = null @JvmField @BindView(R.id.tv_approval_date) var tvActivationDate: TextView? = null @JvmField @BindView(R.id.btn_approve_savings) var btnActivateSavings: Button? = null @JvmField @BindView(R.id.et_savings_approval_reason) var etSavingsActivateReason: EditText? = null @JvmField @Inject var mSavingsAccountActivatePresenter: SavingsAccountActivatePresenter? = null lateinit var rootView: View var activationDate: String? = null var savingsAccountNumber = 0 var savingsAccountType: DepositType? = null private var mfDatePicker: DialogFragment? = null private var safeUIBlockingUtility: SafeUIBlockingUtility? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) if (arguments != null) { savingsAccountNumber = requireArguments().getInt(Constants.SAVINGS_ACCOUNT_NUMBER) savingsAccountType = requireArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE) } setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment activity?.actionBar?.setDisplayHomeAsUpEnabled(true) rootView = inflater.inflate(R.layout.dialog_fragment_approve_savings, null) ButterKnife.bind(this, rootView) mSavingsAccountActivatePresenter!!.attachView(this) safeUIBlockingUtility = SafeUIBlockingUtility(activity, getString(R.string.savings_account_loading_message)) showUserInterface() return rootView } override fun showUserInterface() { etSavingsActivateReason!!.visibility = View.GONE tvActivateDateHeading!!.text = resources.getString(R.string.activated_on) mfDatePicker = MFDatePicker.newInsance(this) tvActivationDate!!.text = MFDatePicker.getDatePickedAsString() activationDate = tvActivationDate!!.text.toString() showActivationDate() } @OnClick(R.id.btn_approve_savings) fun onClickActivateSavings() { val hashMap = HashMap<String, Any?>() hashMap["dateFormat"] = "dd MMMM yyyy" hashMap["activatedOnDate"] = activationDate hashMap["locale"] = "en" mSavingsAccountActivatePresenter!!.activateSavings(savingsAccountNumber, hashMap) } @OnClick(R.id.tv_approval_date) fun onClickApprovalDate() { mfDatePicker!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER) } override fun onDatePicked(date: String) { tvActivationDate!!.text = date activationDate = date showActivationDate() } fun showActivationDate() { activationDate = DateHelper.getDateAsStringUsedForCollectionSheetPayload(activationDate) .replace("-", " ") } override fun showSavingAccountActivatedSuccessfully(genericResponse: GenericResponse?) { Toaster.show(tvActivateDateHeading, resources.getString(R.string.savings_account_activated)) Toast.makeText(activity, "Savings Activated", Toast.LENGTH_LONG).show() requireActivity().supportFragmentManager.popBackStack() } override fun showError(message: String?) { Toast.makeText(activity, message, Toast.LENGTH_LONG).show() } override fun showProgressbar(b: Boolean) { if (b) { safeUIBlockingUtility!!.safelyBlockUI() } else { safeUIBlockingUtility!!.safelyUnBlockUI() } } override fun onDestroyView() { super.onDestroyView() mSavingsAccountActivatePresenter!!.detachView() } companion object { fun newInstance(savingsAccountNumber: Int, type: DepositType?): SavingsAccountActivateFragment { val savingsAccountApproval = SavingsAccountActivateFragment() val args = Bundle() args.putInt(Constants.SAVINGS_ACCOUNT_NUMBER, savingsAccountNumber) args.putParcelable(Constants.SAVINGS_ACCOUNT_TYPE, type) savingsAccountApproval.arguments = args return savingsAccountApproval } } }
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingsaccountactivate/SavingsAccountActivateFragment.kt
979084400
package org.jetbrains.settingsRepository import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.SystemInfo val PROJECTS_DIR_NAME: String = "_projects/" private fun getOsFolderName() = when { SystemInfo.isMac -> "_mac" SystemInfo.isWindows -> "_windows" SystemInfo.isLinux -> "_linux" SystemInfo.isFreeBSD -> "_freebsd" SystemInfo.isUnix -> "_unix" else -> "_unknown" } fun buildPath(path: String, roamingType: RoamingType, projectKey: String? = null): String { fun String.osIfNeed() = if (roamingType == RoamingType.PER_OS) "${getOsFolderName()}/$this" else this return if (projectKey == null) path.osIfNeed() else "$PROJECTS_DIR_NAME$projectKey/$path" }
plugins/settings-repository/src/IcsUrlBuilder.kt
2847237239
package ml.adamsprogs.bimba.models import android.content.Context import ml.adamsprogs.bimba.Declinator import ml.adamsprogs.bimba.R import ml.adamsprogs.bimba.rollTime import ml.adamsprogs.bimba.safeSplit import java.util.* data class Departure(val line: String, val mode: List<Int>, val time: Int, val lowFloor: Boolean, //time in seconds since midnight val modification: List<String>, val headsign: String, val vm: Boolean = false, var tomorrow: Boolean = false, val onStop: Boolean = false, val ticketMachine: Int= TICKET_MACHINE_NONE) { val isModified: Boolean get() { return modification.isNotEmpty() } override fun toString(): String { return "$line|${mode.joinToString(";")}|$time|$lowFloor|${modification.joinToString(";")}|$headsign|$vm|$tomorrow|$onStop|$ticketMachine" } fun copy(): Departure { return Departure.fromString(this.toString()) } companion object { const val TICKET_MACHINE_NONE = 0 const val TICKET_MACHINE_AUTOMAT = 1 const val TICKET_MACHINE_DRIVER = 2 fun fromString(string: String): Departure { val array = string.split("|") if (array.size != 10) throw IllegalArgumentException() val modification = array[4].safeSplit(";")!! return Departure(array[0], array[1].safeSplit(";")!!.map { Integer.parseInt(it) }, Integer.parseInt(array[2]), array[3] == "true", modification, array[5], array[6] == "true", array[7] == "true", array[8] == "true", Integer.parseInt(array[9])) } } fun timeTill(relativeTo: Int): Int { var time = this.time if (this.tomorrow) time += 24 * 60 * 60 return (time - relativeTo) / 60 } val lineText: String = line fun timeTillText(context: Context, relativeTime: Boolean = true): String { val now = Calendar.getInstance() val departureTime = Calendar.getInstance().rollTime(time) if (tomorrow) departureTime.add(Calendar.DAY_OF_MONTH, 1) val departureIn = ((departureTime.timeInMillis - now.timeInMillis) / (1000 * 60)).toInt() return if (departureIn > 60 || departureIn < 0 || !relativeTime) context.getString(R.string.departure_at, "${String.format("%02d", departureTime.get(Calendar.HOUR_OF_DAY))}:${String.format("%02d", departureTime.get(Calendar.MINUTE))}") else if (departureIn > 0 && !onStop) context.getString(Declinator.decline(departureIn), departureIn.toString()) else if (departureIn == 0 && !onStop) context.getString(R.string.in_a_moment) else if (departureIn == 0) context.getString(R.string.now) else context.getString(R.string.just_departed) } fun timeAtMessage(context: Context): String { val departureTime = Calendar.getInstance().rollTime(time) if (tomorrow) departureTime.add(Calendar.DAY_OF_MONTH, 1) return context.getString(R.string.departure_at, "${String.format("%02d", departureTime.get(Calendar.HOUR_OF_DAY))}:${String.format("%02d", departureTime.get(Calendar.MINUTE))}") + if (isModified) " " + modification.joinToString("; ", "(", ")") else "" } }
app/src/main/java/ml/adamsprogs/bimba/models/Departure.kt
3015290906
package lt.vilnius.tvarkau.fragments import android.Manifest import android.app.Activity import android.app.DatePickerDialog import android.app.Dialog import android.app.ProgressDialog import android.app.TimePickerDialog import android.content.Intent import android.location.Address import android.location.Geocoder import android.os.Bundle import android.support.design.widget.TextInputLayout import android.support.v4.app.ActivityOptionsCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.content.res.AppCompatResources import android.util.Patterns import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.DatePicker import android.widget.EditText import android.widget.TimePicker import android.widget.Toast import com.google.android.gms.location.places.ui.PlacePicker import com.google.android.gms.maps.model.LatLng import kotlinx.android.synthetic.main.app_bar.* import kotlinx.android.synthetic.main.fragment_new_report.* import kotlinx.android.synthetic.main.image_picker_dialog.view.* import lt.vilnius.tvarkau.FullscreenImageActivity import lt.vilnius.tvarkau.R import lt.vilnius.tvarkau.activity.ActivityConstants import lt.vilnius.tvarkau.activity.ReportRegistrationActivity import lt.vilnius.tvarkau.activity.available import lt.vilnius.tvarkau.activity.googlePlayServicesAvailability import lt.vilnius.tvarkau.activity.resolutionDialog import lt.vilnius.tvarkau.activity.resultCode import lt.vilnius.tvarkau.api.ApiError import lt.vilnius.tvarkau.entity.Profile import lt.vilnius.tvarkau.entity.ReportEntity import lt.vilnius.tvarkau.entity.ReportType import lt.vilnius.tvarkau.extensions.gone import lt.vilnius.tvarkau.extensions.observe import lt.vilnius.tvarkau.extensions.observeNonNull import lt.vilnius.tvarkau.extensions.visible import lt.vilnius.tvarkau.extensions.withViewModel import lt.vilnius.tvarkau.mvp.presenters.NewReportData import lt.vilnius.tvarkau.utils.FieldAwareValidator import lt.vilnius.tvarkau.utils.FormatUtils.formatLocalDateTime import lt.vilnius.tvarkau.utils.KeyboardUtils import lt.vilnius.tvarkau.utils.PermissionUtils import lt.vilnius.tvarkau.utils.PersonalCodeValidator import lt.vilnius.tvarkau.utils.ProgressState import lt.vilnius.tvarkau.viewmodel.NewReportViewModel import lt.vilnius.tvarkau.views.adapters.NewProblemPhotosPagerAdapter import org.threeten.bp.Duration import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneOffset import pl.aprilapps.easyphotopicker.DefaultCallback import pl.aprilapps.easyphotopicker.EasyImage import timber.log.Timber import java.io.File import java.util.* import java.util.Calendar.DAY_OF_MONTH import java.util.Calendar.HOUR_OF_DAY import java.util.Calendar.MINUTE import java.util.Calendar.MONTH import java.util.Calendar.YEAR @Screen( navigationMode = NavigationMode.BACK, trackingScreenName = ActivityConstants.SCREEN_NEW_REPORT ) class NewReportFragment : BaseFragment(), NewProblemPhotosPagerAdapter.OnPhotoClickedListener { private var googlePlayServicesResolutionDialog: Dialog? = null private lateinit var viewModel: NewReportViewModel var locationCords: LatLng? = null var imageFiles = ArrayList<File>() private var progressDialog: ProgressDialog? = null private val validateParkingViolationData: Boolean get() = reportType.isParkingViolation private val shouldDisplayPhotoInstructions: Boolean get() { val delta = System.currentTimeMillis() - appPreferences.photoInstructionsLastSeen.get() return reportType.isParkingViolation && Duration.ofMillis(delta).toDays() >= 1 } private val reportType by lazy { arguments!!.getParcelable<ReportType>(KEY_REPORT_TYPE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.let { locationCords = it.getParcelable(SAVE_LOCATION) imageFiles = it.getSerializable(SAVE_PHOTOS) as ArrayList<File> } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_new_report, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) with(activity!! as AppCompatActivity) { setSupportActionBar(toolbar) supportActionBar?.title = reportType.title } problem_images_view_pager.adapter = NewProblemPhotosPagerAdapter(imageFiles, this) problem_images_view_pager.offscreenPageLimit = 3 problem_images_view_pager_indicator.setViewPager(problem_images_view_pager) problem_images_view_pager_indicator.gone() report_problem_location.setOnClickListener { onProblemLocationClicked(it) } report_problem_take_photo.setOnClickListener { onTakePhotoClicked() } report_problem_date_time.setOnClickListener { onProblemDateTimeClicked() } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.new_problem_toolbar_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onGoBack() true } R.id.action_send -> { activity!!.currentFocus?.let { KeyboardUtils.closeSoftKeyboard(activity!!, it) } viewModel.submit(createValidator()) true } else -> super.onOptionsItemSelected(item) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = withViewModel(viewModelFactory) { observeNonNull(errorEvents, ::showError) observeNonNull(validationError, ::showValidationError) observeNonNull(progressState, ::handleProgressState) observeNonNull(submittedReport, ::onReportSubmitted) observe(personalData, ::showParkingViolationFields) } viewModel.initWith(reportType) EasyImage.configuration(context!!).setAllowMultiplePickInGallery(true) } private fun showParkingViolationFields(profile: Profile?) { new_report_date_time_container.visible() new_report_licence_plate_container.visible() val drawable = AppCompatResources.getDrawable(context!!, R.drawable.ic_autorenew) report_problem_date_time.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null) report_problem_date_time.setOnTouchListener { view, event -> val DRAWABLE_RIGHT = 2 var result = false val ediText = view as EditText if (event.action == MotionEvent.ACTION_UP) { if (event.rawX >= (ediText.right - ediText.compoundDrawables[DRAWABLE_RIGHT].bounds.width())) { report_problem_date_time.setText(formatLocalDateTime(LocalDateTime.now())) result = true } } result } new_report_personal_code_container.visible() new_report_email_container.visible() new_report_name_container.visible() report_problem_personal_data_agreement.visible() profile?.let { report_problem_submitter_email.setText(it.email) report_problem_submitter_name.setText(it.name) report_problem_submitter_personal_code.setText(it.personalCode) } } private fun createValidator(): FieldAwareValidator<NewReportData> { val data = NewReportData( reportType = reportType, description = report_problem_description.text.toString(), address = report_problem_location.text.toString(), latitude = locationCords?.latitude, longitude = locationCords?.longitude, dateTime = report_problem_date_time.text.toString(), email = report_problem_submitter_email.text.toString(), name = report_problem_submitter_name.text.toString(), personalCode = report_problem_submitter_personal_code.text.toString(), photoUrls = imageFiles, licencePlate = report_problem_licence_plate_number.text.toString() ) var validator = FieldAwareValidator.of(data) .validate( { it.address.isNotBlank() }, report_problem_location_wrapper.id, getText(R.string.error_problem_location_is_empty) ) .validate( { report_problem_description.text.isNotBlank() }, report_problem_description_wrapper.id, getText(R.string.error_problem_description_is_empty) ) if (validateParkingViolationData) { validator = validator .validate( { it.licencePlate?.isNotBlank() ?: false }, report_problem_licence_plate_number_wrapper.id, getString(R.string.error_new_report_fill_licence_plate) ) .validate( { it.dateTime?.isNotBlank() ?: false }, report_problem_date_time_wrapper.id, getString(R.string.error_report_fill_date_time) ) .validate( { it.email?.isNotBlank() ?: false }, report_problem_submitter_email_wrapper.id, getString(R.string.error_profile_fill_email) ) .validate( { Patterns.EMAIL_ADDRESS.matcher(it.email).matches() }, report_problem_submitter_email_wrapper.id, getString(R.string.error_profile_email_invalid) ) .validate( { it.name?.isNotBlank() ?: false }, report_problem_submitter_name_wrapper.id, getText(R.string.error_profile_fill_name).toString() ) .validate( { it.name!!.split(" ").size >= 2 }, report_problem_submitter_name_wrapper.id, getText(R.string.error_profile_name_invalid).toString() ) .validate( { it.personalCode?.isNotBlank() ?: false }, report_problem_submitter_personal_code_wrapper.id, getText(R.string.error_new_report_enter_personal_code).toString() ) .validate( { PersonalCodeValidator.validate(it.personalCode!!) }, report_problem_submitter_personal_code_wrapper.id, getText(R.string.error_new_report_invalid_personal_code).toString() ) .validate( { it.photoUrls.size >= 2 }, 0, getText(R.string.error_minimum_photo_requirement).toString() ) } return validator } private fun showValidationError(error: FieldAwareValidator.ValidationException) { report_problem_location_wrapper.isErrorEnabled = false report_problem_description_wrapper.isErrorEnabled = false report_problem_date_time_wrapper.isErrorEnabled = false report_problem_submitter_name_wrapper.isErrorEnabled = false report_problem_submitter_personal_code_wrapper.isErrorEnabled = false report_problem_submitter_email_wrapper.isErrorEnabled = false report_problem_licence_plate_number_wrapper.isErrorEnabled = false view?.findViewById<TextInputLayout>(error.viewId)?.let { it.error = error.message } ?: Toast.makeText(context!!, error.message, Toast.LENGTH_SHORT).show() } private fun showError(error: Throwable) { val message = if (error is ApiError && error.isValidationError) { error.firstErrorMessage } else { getString(R.string.error_submitting_problem) } Toast.makeText(context!!, message, Toast.LENGTH_SHORT).show() } private fun onReportSubmitted(report: ReportEntity) { activity!!.currentFocus?.run { KeyboardUtils.closeSoftKeyboard(activity!!, this) } Toast.makeText(context!!, R.string.problem_successfully_sent, Toast.LENGTH_SHORT).show() (activity!! as ReportRegistrationActivity).onReportSubmitted() } //TODO restore after image upload implemented private fun fillReportDateTime(dateTime: String) { report_problem_date_time.setText(dateTime) } //TODO restore after image upload implemented private fun displayImages(imageFiles: List<File>) { this.imageFiles.addAll(imageFiles) problem_images_view_pager.adapter!!.notifyDataSetChanged() if (this.imageFiles.size > 1) { problem_images_view_pager_indicator.visible() problem_images_view_pager.currentItem = this.imageFiles.lastIndex } } fun onTakePhotoClicked() { if (PermissionUtils.isAllPermissionsGranted(activity!!, TAKE_PHOTO_PERMISSIONS)) { openPhotoSelectorDialog(shouldDisplayPhotoInstructions) } else { requestPermissions(TAKE_PHOTO_PERMISSIONS, ActivityConstants.REQUEST_CODE_TAKE_PHOTO_PERMISSIONS) } } private fun openPhotoSelectorDialog(displayPhotoInstructions: Boolean) { activity!!.currentFocus?.let { KeyboardUtils.closeSoftKeyboard(activity!!, it) } if (displayPhotoInstructions) { arguments!!.putBoolean(KEY_TAKE_PHOTO, true) (activity!! as ReportRegistrationActivity).displayPhotoInstructions() return } val imagePickerDialogBuilder = AlertDialog.Builder(context!!, R.style.MyDialogTheme) val view = LayoutInflater.from(context!!).inflate(R.layout.image_picker_dialog, null) val cameraButton = view.camera_button val galleryButton = view.gallery_button if (!EasyImage.canDeviceHandleGallery(context!!)) { galleryButton.gone() } imagePickerDialogBuilder .setTitle(R.string.add_photos) .setView(view) .setPositiveButton(R.string.cancel) { dialog, whichButton -> dialog.dismiss() } .create() val imagePickerDialog = imagePickerDialogBuilder.show() cameraButton.setOnClickListener { EasyImage.openCamera(this, 0) imagePickerDialog.dismiss() } galleryButton.setOnClickListener { EasyImage.openGallery(this, 0) imagePickerDialog.dismiss() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { ActivityConstants.REQUEST_CODE_TAKE_PHOTO_PERMISSIONS -> if (PermissionUtils.isAllPermissionsGranted( activity!!, TAKE_PHOTO_PERMISSIONS ) ) { openPhotoSelectorDialog(shouldDisplayPhotoInstructions) } else { Toast.makeText(context!!, R.string.error_need_camera_and_storage_permission, Toast.LENGTH_SHORT).show() } ActivityConstants.REQUEST_CODE_MAP_PERMISSION -> if (PermissionUtils.isAllPermissionsGranted( activity!!, MAP_PERMISSIONS ) ) { showPlacePicker(view!!) } else { Toast.makeText(context!!, R.string.error_need_location_permission, Toast.LENGTH_SHORT).show() } else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private fun isEditedByUser(): Boolean { return report_problem_description.text.isNotBlank() || report_problem_location.text.isNotBlank() || imageFiles.isNotEmpty() } private fun onGoBack() { if (report_problem_description.hasFocus()) { KeyboardUtils.closeSoftKeyboard(activity!!, report_problem_description) } if (isEditedByUser()) { AlertDialog.Builder(context!!, R.style.MyDialogTheme) .setMessage(getString(R.string.discard_changes_title)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.discard_changes_positive) { dialog, whichButton -> activity!!.onBackPressed() } .setNegativeButton(R.string.discard_changes_negative, null).show() } else { activity!!.onBackPressed() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { EasyImage.handleActivityResult(requestCode, resultCode, data, activity!!, object : DefaultCallback() { override fun onImagePickerError(e: Exception?, source: EasyImage.ImageSource?, type: Int) { Toast.makeText(activity!!, R.string.photo_capture_error, Toast.LENGTH_SHORT).show() Timber.w(e, "Unable to take a picture") } override fun onImagesPicked(imageFiles: List<File>, source: EasyImage.ImageSource, type: Int) { viewModel.onImagesPicked(imageFiles) } override fun onCanceled(source: EasyImage.ImageSource?, type: Int) { if (source == EasyImage.ImageSource.CAMERA) { val photoFile = EasyImage.lastlyTakenButCanceledPhoto(context!!) photoFile?.delete() } } }) if (resultCode == Activity.RESULT_OK) { when (requestCode) { ActivityConstants.REQUEST_CODE_PLACE_PICKER -> { val geocoder = Geocoder(context!!) val place = PlacePicker.getPlace(context!!, data) val addresses = mutableListOf<Address>() place.latLng?.let { locationCords = it try { geocoder.getFromLocation(it.latitude, it.longitude, 1)?.let { addresses.addAll(it) } } catch (e: Throwable) { Timber.e(GeocoderException(e)) } } val firstAddress = addresses.firstOrNull() if (firstAddress?.locality != null) { val address = firstAddress.getAddressLine(0) report_problem_location_wrapper.error = null report_problem_location.setText(address) } else { // Mostly when Geocoder throws IOException // backup solution which in not 100% reliable val addressSlice = place.address ?.split(", ".toRegex()) ?.dropLastWhile(String::isEmpty) ?.toTypedArray() val addressText = if (addressSlice == null || addressSlice.isEmpty()) { locationCords?.let { "${it.latitude}; ${it.longitude}" } } else { addressSlice[0] } if (addressText.isNullOrEmpty()) { report_problem_location_wrapper.error = getText(R.string.error_failed_to_determine_address) report_problem_location.text = null } else { report_problem_location_wrapper.error = null report_problem_location.setText(addressText) } } } } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(SAVE_LOCATION, locationCords) outState.putSerializable(SAVE_PHOTOS, imageFiles) } private fun onProblemLocationClicked(view: View) { if (PermissionUtils.isAllPermissionsGranted(activity!!, MAP_PERMISSIONS)) { showPlacePicker(view) } else { requestPermissions(MAP_PERMISSIONS, ActivityConstants.REQUEST_CODE_MAP_PERMISSION) } } private fun showPlacePicker(view: View) { val googlePlayServicesAvailability = activity!!.googlePlayServicesAvailability() if (googlePlayServicesAvailability.available()) { val intent = PlacePicker.IntentBuilder().build(activity!!) val bundle = ActivityOptionsCompat.makeScaleUpAnimation(view, 0, 0, view.width, view.height).toBundle() startActivityForResult(intent, ActivityConstants.REQUEST_CODE_PLACE_PICKER, bundle) } else { analytics.trackGooglePlayServicesError(googlePlayServicesAvailability.resultCode()) googlePlayServicesResolutionDialog?.dismiss() googlePlayServicesResolutionDialog = googlePlayServicesAvailability.resolutionDialog(activity!!) googlePlayServicesResolutionDialog?.show() } } private fun onProblemDateTimeClicked() { val calendar = Calendar.getInstance() calendar.time = Date() val year = calendar.get(YEAR) val month = calendar.get(MONTH) val day = calendar.get(DAY_OF_MONTH) val dialogDatePicker = DatePickerDialog( activity!!, { _: DatePicker, selectedYear: Int, selectedMonth: Int, selectedDay: Int -> calendar.set(YEAR, selectedYear) calendar.set(MONTH, selectedMonth) calendar.set(DAY_OF_MONTH, selectedDay) TimePickerDialog(activity!!, { _: TimePicker, hour: Int, minutes: Int -> calendar.set(HOUR_OF_DAY, hour) calendar.set(MINUTE, minutes) val dateTime = LocalDateTime.of( calendar.get(YEAR), calendar.get(MONTH) + 1, //LocalDateTime expects month starting from 1 instead of 0 calendar.get(DAY_OF_MONTH), calendar.get(HOUR_OF_DAY), calendar.get(MINUTE) ) report_problem_date_time.setText(formatLocalDateTime(dateTime)) }, 0, 0, true).show() }, year, month, day ) dialogDatePicker.datePicker.maxDate = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() dialogDatePicker.setTitle(null) dialogDatePicker.show() } override fun onPhotoClicked(position: Int, photos: List<String>) { val intent = Intent(activity!!, FullscreenImageActivity::class.java) intent.putExtra(FullscreenImageActivity.EXTRA_PHOTOS, photos.toTypedArray()) intent.putExtra(FullscreenImageActivity.EXTRA_IMAGE_POSITION, position) startActivity(intent) } private fun handleProgressState(progressState: ProgressState) { when (progressState) { ProgressState.show -> showProgress() ProgressState.hide -> hideProgress() } } private fun showProgress() { if (progressDialog == null) { progressDialog = ProgressDialog(context!!).apply { setMessage(getString(R.string.sending_problem)) setProgressStyle(ProgressDialog.STYLE_SPINNER) setCancelable(false) } } progressDialog?.show() } private fun hideProgress() { progressDialog?.dismiss() } override fun onResume() { super.onResume() if (arguments!!.containsKey(KEY_TAKE_PHOTO)) { arguments!!.remove(KEY_TAKE_PHOTO) openPhotoSelectorDialog(displayPhotoInstructions = false) } } override fun onDestroy() { EasyImage.clearConfiguration(context!!) super.onDestroy() } override fun onDestroyView() { progressDialog?.dismiss() super.onDestroyView() } companion object { val TAKE_PHOTO_PERMISSIONS = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA) val MAP_PERMISSIONS = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) const val PARKING_VIOLATIONS = "Transporto priemonių stovėjimo tvarkos pažeidimai" private const val SAVE_LOCATION = "location" private const val SAVE_PHOTOS = "photos" const val KEY_REPORT_TYPE = "report_type" const val KEY_TAKE_PHOTO = "take_photo" fun newInstance(reportType: ReportType): NewReportFragment { return NewReportFragment().apply { arguments = Bundle().apply { putParcelable(KEY_REPORT_TYPE, reportType) } } } } class GeocoderException(cause: Throwable) : RuntimeException(cause) }
app/src/main/java/lt/vilnius/tvarkau/fragments/NewReportFragment.kt
2092535034
package com.infinum.dbinspector.domain.shared.models.dsl internal class DropTrigger { companion object { val pattern = "\\s+".toRegex() } private lateinit var trigger: String fun name(trigger: String) { this.trigger = "\"$trigger\"" } fun build(): String { if (!::trigger.isInitialized) { error("Failed to build - target view is undefined") } return toString() } override fun toString(): String { return "DROP TRIGGER $trigger".replace(pattern, " ") } }
dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/shared/models/dsl/DropTrigger.kt
675698808
package io.javalin.core.plugin import io.javalin.Javalin /** Extend [Plugin] with a new lifecycle */ interface PluginLifecycleInit { /** * Initialize properties and event listener. * This will be called before any handler is registered. * It is not allowed to register handler during this lifecycle. */ fun init(app: Javalin) }
javalin/src/main/java/io/javalin/core/plugin/PluginLifecyles.kt
2098082647
// Copyright 2021 [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 cfig.bootloader_message import cfig.io.Struct3 import org.slf4j.LoggerFactory import java.io.FileInputStream class BootloaderMsgAB( //offset 2k, size 2k var slotSuffix: String = "", var updateChannel: String = "", var reserved: ByteArray = byteArrayOf() ) { companion object { private const val FORMAT_STRING = "32s128s1888b" const val SIZE = 2048 private val log = LoggerFactory.getLogger(BootloaderMsgAB::class.java.simpleName) init { assert(SIZE == Struct3(FORMAT_STRING).calcSize()) } } constructor(fis: FileInputStream) : this() { val info = Struct3(FORMAT_STRING).unpack(fis) this.slotSuffix = info[0] as String this.updateChannel = info[1] as String this.reserved = info[2] as ByteArray } fun encode(): ByteArray { return Struct3(FORMAT_STRING).pack( this.slotSuffix, this.updateChannel, byteArrayOf()) } }
bbootimg/src/main/kotlin/bootloader_message/BootloaderMsgAB.kt
1374221318
package org.kantega.niagara.eff typealias Pipe<A,B> = (Source<A>) -> Source<B> fun <A,B> map(f:(A)->B): Pipe<A, B> = { it.map(f) }
niagara-effect/src/main/kotlin/org/kantega/niagara/eff/pipes.kt
1902055412
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.advancement.criteria import org.lanternpowered.api.util.ToStringHelper import org.lanternpowered.api.util.collections.toImmutableSet import org.spongepowered.api.advancement.criteria.AdvancementCriterion import org.spongepowered.api.advancement.criteria.AndCriterion import org.spongepowered.api.advancement.criteria.OperatorCriterion import org.spongepowered.api.advancement.criteria.OrCriterion abstract class AbstractCriterion internal constructor(private val name: String) : AdvancementCriterion { override fun getName(): String = this.name override fun and(vararg criteria: AdvancementCriterion): AdvancementCriterion = this.and(criteria.asList()) override fun and(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = build(AndCriterion::class.java, sequenceOf(this) + criteria.asSequence(), ::LanternAndCriterion) override fun or(vararg criteria: AdvancementCriterion): AdvancementCriterion = this.or(criteria.asList()) override fun or(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = build(OrCriterion::class.java, sequenceOf(this) + criteria.asSequence(), ::LanternOrCriterion) override fun toString(): String = this.toStringHelper().toString() open fun toStringHelper(): ToStringHelper = ToStringHelper(this) .add("name", this.name) companion object { @JvmStatic fun getRecursiveCriteria(criterion: AdvancementCriterion): Collection<AdvancementCriterion> = if (criterion is AbstractOperatorCriterion) criterion.recursiveChildren else listOf(criterion) fun build( type: Class<out OperatorCriterion>, criteria: Sequence<AdvancementCriterion>, function: (Set<AdvancementCriterion>) -> AdvancementCriterion ): AdvancementCriterion { val builder = mutableListOf<AdvancementCriterion>() for (criterion in criteria) this.build(type, criterion, builder) if (builder.isEmpty()) return EmptyCriterion return if (builder.size == 1) builder[0] else function(builder.toImmutableSet()) } private fun build(type: Class<out OperatorCriterion>, criterion: AdvancementCriterion, criteria: MutableList<AdvancementCriterion>) { if (criterion === EmptyCriterion) return if (type.isInstance(criterion)) { criteria.addAll((criterion as OperatorCriterion).criteria) } else { criteria.add(criterion) } } } }
src/main/kotlin/org/lanternpowered/server/advancement/criteria/AbstractCriterion.kt
3193990748
package pref.impl import android.content.SharedPreferences import android.content.SharedPreferences.Editor import pref.Pref import pref.ext.editThenApply import kotlin.reflect.KProperty class GenericNullablePref<T : Any?> @JvmOverloads constructor( private val get: SharedPreferences.(String, Boolean) -> T?, private val put: Editor.(String, T) -> Unit, private val key: String? = null ) { operator fun getValue(pref: Pref, prop: KProperty<*>): T? { val noNullKey = key ?: prop.name return get( pref.preferences, noNullKey, pref.preferences.contains(noNullKey) ) } operator fun setValue(pref: Pref, prop: KProperty<*>, value: T?) { val noNullKey = key ?: prop.name pref.editThenApply { editor -> value?.let { put(editor, noNullKey, it) } ?: editor.remove(noNullKey) } } }
pref/src/main/java/pref/impl/GenericNullablePref.kt
2564269407
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.util.guice import com.google.inject.Binder import com.google.inject.Binding import com.google.inject.Module import com.google.inject.Provider import com.google.inject.matcher.AbstractMatcher import com.google.inject.spi.DependencyAndSource import com.google.inject.spi.ProviderInstanceBinding import com.google.inject.spi.ProvisionListener import org.lanternpowered.api.util.type.typeToken import java.lang.reflect.Executable import java.lang.reflect.Field /** * Allows injecting the [InjectionPoint] in [Provider]s. */ class InjectionPointProvider : AbstractMatcher<Binding<*>>(), Module, ProvisionListener, Provider<InjectionPoint> { private var injectionPoint: InjectionPoint? = null override fun get(): InjectionPoint? = this.injectionPoint override fun matches(binding: Binding<*>) = binding is ProviderInstanceBinding<*> && binding.userSuppliedProvider === this override fun <T> onProvision(provision: ProvisionListener.ProvisionInvocation<T>) { try { this.injectionPoint = this.findInjectionPoint(provision.dependencyChain) provision.provision() } finally { this.injectionPoint = null } } private fun findInjectionPoint(dependencyChain: List<DependencyAndSource>): InjectionPoint? { if (dependencyChain.size < 3) AssertionError("Provider is not included in the dependency chain").printStackTrace() // @Inject InjectionPoint is the last, so we can skip it for (i in dependencyChain.size - 2 downTo 0) { val dependency = dependencyChain[i].dependency ?: return null val spiInjectionPoint = dependency.injectionPoint if (spiInjectionPoint != null) { val source = spiInjectionPoint.declaringType.type.typeToken return when (val member = spiInjectionPoint.member) { is Field -> LanternInjectionPoint.Field(source, member.genericType.typeToken, member.annotations, member) is Executable -> { val parameterAnnotations = member.parameterAnnotations val parameterTypes = member.genericParameterTypes val index = dependency.parameterIndex LanternInjectionPoint.Parameter(source, parameterTypes[index].typeToken, parameterAnnotations[index], member, index) } else -> throw IllegalStateException("Unsupported Member type: ${member.javaClass.name}") } } } return null } override fun configure(binder: Binder) { binder.bind(InjectionPoint::class.java).toProvider(this) binder.bindListener(this, this) } }
src/main/kotlin/org/lanternpowered/server/util/guice/InjectionPointProvider.kt
3892461887
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.common.identity import com.google.protobuf.ByteString import io.grpc.BindableService import io.grpc.Context import io.grpc.Contexts import io.grpc.Metadata import io.grpc.ServerCall import io.grpc.ServerCallHandler import io.grpc.ServerInterceptor import io.grpc.ServerInterceptors import io.grpc.ServerServiceDefinition import io.grpc.Status import io.grpc.stub.AbstractStub import io.grpc.stub.MetadataUtils /** * Details about an authenticated Duchy. * * @property[id] Stable identifier for a duchy. */ data class DuchyIdentity(val id: String) { init { requireNotNull(DuchyInfo.getByDuchyId(id)) { "Duchy $id is unknown; known Duchies are ${DuchyInfo.ALL_DUCHY_IDS}" } } } val duchyIdentityFromContext: DuchyIdentity get() = requireNotNull(DUCHY_IDENTITY_CONTEXT_KEY.get()) { "gRPC context is missing key $DUCHY_IDENTITY_CONTEXT_KEY" } private const val KEY_NAME = "duchy-identity" val DUCHY_IDENTITY_CONTEXT_KEY: Context.Key<DuchyIdentity> = Context.key(KEY_NAME) val DUCHY_ID_METADATA_KEY: Metadata.Key<String> = Metadata.Key.of(KEY_NAME, Metadata.ASCII_STRING_MARSHALLER) /** * Add an interceptor that sets DuchyIdentity in the context. * * Note that this doesn't provide any guarantees that the Duchy is who it claims to be -- that is * still required. * * To install in a server, wrap a service with: * ``` * yourService.withDuchyIdentities() * ``` * On the client side, use [withDuchyId]. */ class DuchyTlsIdentityInterceptor : ServerInterceptor { override fun <ReqT, RespT> interceptCall( call: ServerCall<ReqT, RespT>, headers: Metadata, next: ServerCallHandler<ReqT, RespT> ): ServerCall.Listener<ReqT> { val authorityKeyIdentifiers: List<ByteString> = authorityKeyIdentifiersFromCurrentContext if (authorityKeyIdentifiers.isEmpty()) { call.close( Status.UNAUTHENTICATED.withDescription("No authorityKeyIdentifiers found"), Metadata() ) return object : ServerCall.Listener<ReqT>() {} } for (authorityKeyIdentifier in authorityKeyIdentifiers) { val duchyInfo = DuchyInfo.getByRootCertificateSkid(authorityKeyIdentifier) ?: continue val context = Context.current().withValue(DUCHY_IDENTITY_CONTEXT_KEY, DuchyIdentity(duchyInfo.duchyId)) return Contexts.interceptCall(context, call, headers, next) } call.close(Status.UNAUTHENTICATED.withDescription("No Duchy identity found"), Metadata()) return object : ServerCall.Listener<ReqT>() {} } } /** Convenience helper for [DuchyTlsIdentityInterceptor]. */ fun BindableService.withDuchyIdentities(): ServerServiceDefinition = ServerInterceptors.interceptForward( this, AuthorityKeyServerInterceptor(), DuchyTlsIdentityInterceptor() ) /** * Sets metadata key "duchy_id" on all outgoing requests. * * Usage: val someStub = SomeServiceCoroutineStub(channel).withDuchyId("MyDuchyId") */ fun <T : AbstractStub<T>> T.withDuchyId(duchyId: String): T { val extraHeaders = Metadata() extraHeaders.put(DUCHY_ID_METADATA_KEY, duchyId) return withInterceptors(MetadataUtils.newAttachHeadersInterceptor(extraHeaders)) }
src/main/kotlin/org/wfanet/measurement/common/identity/DuchyIdentity.kt
952448013
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.duchy.deploy.gcloud.server import org.wfanet.measurement.common.commandLineMain import org.wfanet.measurement.duchy.deploy.common.server.RequisitionFulfillmentServer import org.wfanet.measurement.gcloud.gcs.GcsFromFlags import org.wfanet.measurement.gcloud.gcs.GcsStorageClient import picocli.CommandLine /** Implementation of [RequisitionFulfillmentServer] using Google Cloud Storage (GCS). */ @CommandLine.Command( name = "GcsRequisitionFulfillmentServer", description = ["Server daemon for ${RequisitionFulfillmentServer.SERVICE_NAME} service."], mixinStandardHelpOptions = true, showDefaultValues = true ) class GcsRequisitionFulfillmentServer : RequisitionFulfillmentServer() { @CommandLine.Mixin private lateinit var gcsFlags: GcsFromFlags.Flags override fun run() { val gcs = GcsFromFlags(gcsFlags) run(GcsStorageClient.fromFlags(gcs)) } } fun main(args: Array<String>) = commandLineMain(GcsRequisitionFulfillmentServer(), args)
src/main/kotlin/org/wfanet/measurement/duchy/deploy/gcloud/server/GcsRequisitionFulfillmentServer.kt
3811180170
/* * Copyright 2022 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wfanet.measurement.common.k8s.testing import io.kubernetes.client.util.Config import java.io.InputStream import java.nio.file.Path import java.util.UUID import java.util.logging.Logger import org.jetbrains.annotations.Blocking import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import org.wfanet.measurement.common.k8s.KubernetesClient /** * [TestRule] for a Kubernetes cluster in [KinD](https://kind.sigs.k8s.io/). * * This assumes that you have KinD installed and in your path. This creates a cluster using `kind * create cluster` and attempts to delete it using `kind delete cluster`. These commands may have * other side effects. */ class KindCluster : TestRule { lateinit var uuid: UUID private set val name: String by lazy { "kind-$uuid" } val nameOption: String by lazy { "--name=$name" } lateinit var k8sClient: KubernetesClient private set override fun apply(base: Statement, description: Description): Statement { return object : Statement() { override fun evaluate() { uuid = UUID.randomUUID() runCommand("kind", "create", "cluster", nameOption) try { val apiClient = runCommand("kind", "get", "kubeconfig", nameOption) { Config.fromConfig(it) } k8sClient = KubernetesClient(apiClient) base.evaluate() } finally { runCommand("kind", "delete", "cluster", nameOption) } } } } @Blocking fun loadImage(archivePath: Path) { runCommand("kind", "load", "image-archive", archivePath.toString(), nameOption) } @Blocking fun exportLogs(outputDir: Path) { runCommand("kind", "export", "logs", outputDir.toString(), nameOption) } companion object { private val logger = Logger.getLogger(this::class.java.name) @Blocking private fun runCommand(vararg command: String) { logger.fine { "Running `${command.joinToString(" ")}`" } val process: Process = ProcessBuilder(*command) .redirectOutput(ProcessBuilder.Redirect.INHERIT) .redirectError(ProcessBuilder.Redirect.INHERIT) .start() val exitCode: Int = process.waitFor() check(exitCode == 0) { "`${command.joinToString(" ")}` failed with exit code $exitCode" } } @Blocking private inline fun <T> runCommand( vararg command: String, consumeOutput: (InputStream) -> T ): T { logger.fine { "Running `${command.joinToString(" ")}`" } val process: Process = ProcessBuilder(*command).start() val result = process.inputStream.use { consumeOutput(it) } val exitCode: Int = process.waitFor() check(exitCode == 0) { val errOutput = process.errorStream.bufferedReader().use { it.readText() } "`${command.joinToString(" ")}` failed with exit code $exitCode\n$errOutput" } return result } } }
src/main/kotlin/org/wfanet/measurement/common/k8s/testing/KindCluster.kt
4132073255
package com.mercadopago.android.px.tracking.internal.events object BiometricsFrictionTracker : FrictionEventTracker("$BASE_PATH/biometrics", Id.GENERIC, Style.CUSTOM_COMPONENT)
px-checkout/src/main/java/com/mercadopago/android/px/tracking/internal/events/BiometricsFrictionTracker.kt
512337276
package nl.hannahsten.texifyidea.editor.typedhandlers import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.openapi.editor.CaretModel import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.file.LatexFileType import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand import nl.hannahsten.texifyidea.settings.TexifySettings import nl.hannahsten.texifyidea.util.getOpenAndCloseQuotes import nl.hannahsten.texifyidea.util.inVerbatim import nl.hannahsten.texifyidea.util.insertUsepackage import kotlin.math.min /** * This class performs smart quote substitution. When this is enabled, it will replace double quotes " and single quotes ' with the appropriate LaTeX symbols. * * @author Thomas Schouten */ open class LatexQuoteInsertHandler : TypedHandlerDelegate() { override fun charTyped(char: Char, project: Project, editor: Editor, file: PsiFile): Result { // Only do this for latex files and if the option is enabled if (file.fileType != LatexFileType || TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.NONE) { return super.charTyped(char, project, editor, file) } val document = editor.document val caret = editor.caretModel val offset = caret.offset // Disable in verbatim context. val psi = file.findElementAt(offset) if (psi?.inVerbatim() == true) return super.charTyped(char, project, editor, file) // Only do smart things with double and single quotes if (char != '"' && char != '\'') { return super.charTyped(char, project, editor, file) } // Check if we are not out of the document range if (offset - 1 < 0 || offset - 1 >= document.textLength) { return super.charTyped(char, project, editor, file) } insertReplacement(document, file, caret, offset, char) return super.charTyped(char, project, editor, file) } /** * Insert either opening or closing quotes. * * This behaviour is inspired by the smart quotes functionality of TeXworks, source: * https://github.com/TeXworks/texworks/blob/2f902e2e429fad3e2bbb56dff07c823d1108adf4/src/CompletingEdit.cpp#L762 */ private fun insertReplacement(document: Document, file: PsiFile, caret: CaretModel, offset: Int, char: Char) { val replacementPair = getOpenAndCloseQuotes(char) val openingQuotes = replacementPair.first val closingQuotes = if (TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.CSQUOTES) "" else replacementPair.second // The default replacement of the typed double quotes is a pair of closing quotes var isOpeningQuotes = false // Always use opening quotes at the beginning of the document if (offset == 1) { isOpeningQuotes = true } else { // Character before the cursor val previousChar = document.getText(TextRange.from(offset - 2, 1)) if ((previousChar.firstOrNull())?.isLetter() == true && char == '\'') return // Don't replace when trying to type an escaped quote \" if (previousChar == "\\") return // Assume that if the previous char is a space, we are not closing anything if (previousChar == " ") { isOpeningQuotes = true } // After opening brackets, also use opening quotes if (previousChar == "{" || previousChar == "[" || previousChar == "(") { isOpeningQuotes = true } // If we are not closing the quotes, assume we are opening it (instead of doing nothing) if (TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.CSQUOTES && document.getText(TextRange.from(min(offset, document.textLength - 1), 1)) != "}" ) { isOpeningQuotes = true } } val replacement = if (isOpeningQuotes) openingQuotes else closingQuotes // Insert the replacement of the typed character, recall the offset is now right behind the inserted char document.deleteString(offset - 1, offset) document.insertString(offset - 1, replacement) // Move the cursor behind the replacement which replaced the typed char caret.moveToOffset(min(offset + replacement.length - 1, document.textLength)) handleCsquotesInsertion(document, file, isOpeningQuotes, caret, char) } /** * Special behaviour for \enquote, because it is a command, not just opening and closing quotes. */ private fun handleCsquotesInsertion(document: Document, file: PsiFile, isOpeningQuotes: Boolean, caret: CaretModel, char: Char) { if (TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.CSQUOTES) { if (isOpeningQuotes) { // Insert } after the cursor to close the command document.insertString(caret.offset, "}") } else { // Instead of typing closing quotes, skip over the closing } caret.moveToOffset(caret.offset + 1) } // Package dependencies if (char == '"') { file.insertUsepackage(LatexGenericRegularCommand.ENQUOTE.dependency) } else { file.insertUsepackage(LatexGenericRegularCommand.ENQUOTE_STAR.dependency) } } } }
src/nl/hannahsten/texifyidea/editor/typedhandlers/LatexQuoteInsertHandler.kt
3192502281
package com.kushkipagos.kushki import com.kushkipagos.exceptions.KushkiException import com.kushkipagos.models.* import java.io.* import java.net.HttpURLConnection import java.net.URL import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import java.security.spec.InvalidKeySpecException import java.util.* import javax.crypto.BadPaddingException import javax.crypto.IllegalBlockSizeException import javax.crypto.NoSuchPaddingException internal class KushkiClient(private val environment: Environment, private val publicMerchantId: String , private val regional: Boolean) { constructor(environment: Environment, publicMerchantId: String) : this(environment, publicMerchantId, false) private val kushkiJsonBuilder: KushkiJsonBuilder = KushkiJsonBuilder() @Throws(KushkiException::class) fun getScienceSession(card: Card): SiftScienceObject { var bin:String = card.toJsonObject().getString("number").toString().substring(0, 6) var lastDigits:String = card.toJsonObject().getString("number").toString().substring(card.toJsonObject().getString("number").length - 4) return createSiftScienceSession(bin, lastDigits, publicMerchantId) } @Throws(KushkiException::class) fun createSiftScienceSession(bin: String, lastDigits: String, merchantId: String): SiftScienceObject { var userId:String ="" var sessionId:String="" var uuid: UUID = UUID.randomUUID() if(merchantId ==""){ userId = "" sessionId ="" }else { userId = merchantId+bin+lastDigits sessionId =uuid.toString() } return SiftScienceObject(kushkiJsonBuilder.buildJson(userId, sessionId)) } @Throws(KushkiException::class) fun post(endpoint: String, requestBody: String): Transaction { try { val connection = prepareConnection(endpoint, requestBody) return Transaction(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun post_secure(endpoint: String, requestBody: String): SecureValidation { System.out.println("request--Body") System.out.println(requestBody) try { val connection = prepareConnection(endpoint, requestBody) return SecureValidation(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get (endpoint: String): BankList { try { val connection = prepareGetConnection(endpoint) return BankList(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get_bin (endpoint: String): BinInfo { try { val connection = prepareGetConnection(endpoint) return BinInfo(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get_merchant_settings (endpoint: String): MerchantSettings { try { val connection = prepareGetConnection(endpoint) return MerchantSettings(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get_cybersourceJWT (endpoint: String):CyberSourceJWT{ try { val connection = prepareGetConnection(endpoint) return CyberSourceJWT(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun post_card_secure(endpoint: String, requestBody: String): CardSecureValidation { System.out.println("request--Body") System.out.println(requestBody) try { val connection = prepareConnection(endpoint, requestBody) return CardSecureValidation(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(IOException::class) private fun prepareConnection(endpoint: String, requestBody: String): HttpURLConnection { var urlDestination:String = environment.url if(regional) { when (environment) { KushkiEnvironment.PRODUCTION -> urlDestination = KushkiEnvironment.PRODUCTION_REGIONAL.url KushkiEnvironment.TESTING -> urlDestination = KushkiEnvironment.UAT_REGIONAL.url } } val url = URL(urlDestination + endpoint) System.out.println(url) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8") connection.setRequestProperty("public-merchant-id", publicMerchantId) connection.readTimeout = 25000 connection.connectTimeout = 30000 connection.doOutput = true val dataOutputStream = DataOutputStream(connection.outputStream) dataOutputStream.writeBytes(requestBody) dataOutputStream.flush() dataOutputStream.close() return connection } @Throws(IOException::class) private fun prepareGetConnection(endpoint: String):HttpURLConnection{ var urlDestination:String = environment.url if(regional) { when (environment) { KushkiEnvironment.PRODUCTION -> urlDestination = KushkiEnvironment.PRODUCTION_REGIONAL.url KushkiEnvironment.TESTING -> urlDestination = KushkiEnvironment.UAT_REGIONAL.url } } val url = URL(urlDestination + endpoint) System.out.println(url) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8") connection.setRequestProperty("Public-Merchant-Id", publicMerchantId) connection.readTimeout = 25000 connection.connectTimeout = 30000 return connection } @Throws(IOException::class) private fun parseResponse(connection: HttpURLConnection): String { val responseInputStream = getResponseInputStream(connection) val reader = BufferedReader(InputStreamReader(responseInputStream, "UTF-8")) val stringBuilder = StringBuilder() reader.forEachLine { stringBuilder.append(it) } System.out.println(stringBuilder.toString()) return stringBuilder.toString() } @Throws(IOException::class) private fun getResponseInputStream(connection: HttpURLConnection): InputStream { if (connection.responseCode >= HttpURLConnection.HTTP_BAD_REQUEST) { return connection.errorStream } else { return connection.inputStream } } }
kushki/src/main/java/com/kushkipagos/kushki/KushkiClient.kt
3207818191
package ru.fomenkov.plugin.repository.data sealed class RepositoryResource { data class ClassResource( val packageName: String, val classFilePath: String, val buildDirPath: String, ) : RepositoryResource() data class JarResource( val packageName: String, val jarFilePath: String, ) : RepositoryResource() }
plugin/src/ru/fomenkov/plugin/repository/data/RepositoryResource.kt
3157342446
package voice.logging.core import java.io.PrintWriter import java.io.StringWriter object Logger { fun v(message: String) { log(severity = Severity.Verbose, message = message, throwable = null) } fun d(message: String) { log(severity = Severity.Debug, message = message, throwable = null) } fun d(throwable: Throwable) { log(severity = Severity.Debug, message = null, throwable = throwable) } fun i(message: String) { log(severity = Severity.Info, message = message, throwable = null) } fun w(message: String) { log(severity = Severity.Warn, message = message, throwable = null) } fun w(throwable: Throwable, message: String? = null) { log(severity = Severity.Warn, message = message, throwable = throwable) } fun e(message: String) { log(severity = Severity.Error, message = message, throwable = null) } fun e(throwable: Throwable, message: String) { log(severity = Severity.Error, message = message, throwable = throwable) } private var writers: Set<LogWriter> = emptySet() fun install(writer: LogWriter) { writers = writers + writer } /** * This logic is borrowed from Timber: https://github.com/JakeWharton/timber */ private fun log(severity: Severity, message: String?, throwable: Throwable?) { var messageResult = message if (messageResult.isNullOrEmpty()) { if (throwable == null) { return // Swallow message if it's null and there's no throwable. } messageResult = getStackTraceString(throwable) } else { if (throwable != null) { messageResult += "\n" + getStackTraceString(throwable) } } writers.forEach { it.log(severity, messageResult, throwable) } } private fun getStackTraceString(t: Throwable): String { // Don't replace this with Log.getStackTraceString() - it hides // UnknownHostException, which is not what we want. val sw = StringWriter(256) val pw = PrintWriter(sw, false) t.printStackTrace(pw) pw.flush() return sw.toString() } enum class Severity { Verbose, Debug, Info, Warn, Error, } } interface LogWriter { fun log(severity: Logger.Severity, message: String, throwable: Throwable?) }
logging/core/src/main/kotlin/voice/logging/core/Logger.kt
3645365319
package io.vertx.kotlin.kafka.client.common import io.vertx.kafka.client.common.TopicPartition /** * A function providing a DSL for building [io.vertx.kafka.client.common.TopicPartition] objects. * * Represent information related to a partition for a topic * * @param partition Set the partition number * @param topic Set the topic name * * <p/> * NOTE: This function has been automatically generated from the [io.vertx.kafka.client.common.TopicPartition original] using Vert.x codegen. */ fun TopicPartition( partition: Int? = null, topic: String? = null): TopicPartition = io.vertx.kafka.client.common.TopicPartition().apply { if (partition != null) { this.setPartition(partition) } if (topic != null) { this.setTopic(topic) } }
src/main/kotlin/io/vertx/kotlin/kafka/client/common/TopicPartition.kt
2858238476
package me.ykrank.s1next.data.api.model import android.text.TextUtils import com.github.ykrank.androidtools.util.L import com.github.ykrank.androidtools.util.LooperUtil import me.ykrank.s1next.data.api.model.wrapper.HtmlDataWrapper import org.jsoup.Jsoup import paperparcel.PaperParcel import paperparcel.PaperParcelable import java.util.* /** * Created by ykrank on 2016/7/31 0031. */ @PaperParcel class ThreadType : PaperParcelable { var typeId: String? = null var typeName: String? = null constructor() constructor(typeId: String, typeName: String) { this.typeId = typeId this.typeName = typeName } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ThreadType if (typeId != other.typeId) return false if (typeName != other.typeName) return false return true } override fun hashCode(): Int { var result = typeId?.hashCode() ?: 0 result = 31 * result + (typeName?.hashCode() ?: 0) return result } companion object { @JvmField val CREATOR = PaperParcelThreadType.CREATOR /** * Extracts [Quote] from XML string. * * @param html raw html * @return if no type, return empty list. */ @Throws fun fromXmlString(html: String?): List<ThreadType> { LooperUtil.enforceOnWorkThread() val types = ArrayList<ThreadType>() try { val document = Jsoup.parse(html) HtmlDataWrapper.preAlertHtml(document) HtmlDataWrapper.preTreatHtml(document) val typeIdElements = document.select("#typeid>option") for (i in typeIdElements.indices) { val element = typeIdElements[i] val typeId = element.attr("value").trim() val typeName = element.text() types.add(ThreadType(typeId, typeName)) } } catch (e: Exception) { L.leaveMsg("Source:" + html) throw e } return types } fun nameOf(types: List<ThreadType>?, typeId: String): String? { if (types == null || types.isEmpty()) { return null } for (type in types) { if (TextUtils.equals(type.typeId, typeId)) { return type.typeName } } return null } } }
app/src/main/java/me/ykrank/s1next/data/api/model/ThreadType.kt
2898644474
/* * 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 git4idea.remote import com.intellij.openapi.components.service import git4idea.checkout.GitCheckoutProvider import git4idea.commands.GitHttpAuthService import git4idea.commands.GitHttpAuthenticator import git4idea.test.GitHttpAuthTestService import git4idea.test.GitPlatformTest import java.io.File import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit class GitRemoteTest : GitPlatformTest() { private lateinit var authenticator : TestAuthenticator private lateinit var authTestService : GitHttpAuthTestService private val projectName = "projectA" override fun setUp() { super.setUp() authenticator = TestAuthenticator() authTestService = service<GitHttpAuthService>() as GitHttpAuthTestService authTestService.register(authenticator) } override fun tearDown() { try{ authTestService.cleanup() } finally { super.tearDown() } } fun `test clone from http with username`() { val cloneWaiter = cloneOnPooledThread(makeUrl("gituser")) assertPasswordAsked() authenticator.supplyPassword("gitpassword") assertCloneSuccessful(cloneWaiter) } fun `test clone from http without username`() { val cloneWaiter = cloneOnPooledThread(makeUrl(null)) assertUsernameAsked() authenticator.supplyUsername("gituser") assertPasswordAsked() authenticator.supplyPassword("gitpassword") assertCloneSuccessful(cloneWaiter) } fun `test clone fails if incorrect password`() { val url = makeUrl("gituser") val cloneWaiter = cloneOnPooledThread(url) assertPasswordAsked() authenticator.supplyPassword("incorrect") assertTrue("Clone didn't complete during the reasonable period of time", cloneWaiter.await(30, TimeUnit.SECONDS)) assertFalse("Repository directory shouldn't be created", File(myTestRoot, projectName).exists()) assertErrorNotification("Clone failed", "Authentication failed for '$url/'") } private fun makeUrl(username: String?) : String { val login = if (username == null) "" else "$username@" return "http://${login}deb6-vm7-git/$projectName.git" } private fun cloneOnPooledThread(url: String): CountDownLatch { val cloneWaiter = CountDownLatch(1) executeOnPooledThread { val projectName = url.substring(url.lastIndexOf('/') + 1).replace(".git", "") GitCheckoutProvider.doClone(myProject, myGit, projectName, myTestRoot.path, url) cloneWaiter.countDown() } return cloneWaiter } private fun assertCloneSuccessful(cloneCompleted: CountDownLatch) { assertTrue("Clone didn't complete during the reasonable period of time", cloneCompleted.await(30, TimeUnit.SECONDS)) assertTrue("Repository directory was not found", File(myTestRoot, projectName).exists()) } private fun assertPasswordAsked() { authenticator.waitUntilPasswordIsAsked() assertTrue("Password was not requested", authenticator.wasPasswordAsked()) } private fun assertUsernameAsked() { authenticator.waitUntilUsernameIsAsked() assertTrue("Username was not requested", authenticator.wasUsernameAsked()) } private class TestAuthenticator : GitHttpAuthenticator { private val TIMEOUT = 10 private val passwordAskedWaiter = CountDownLatch(1) private val usernameAskedWaiter = CountDownLatch(1) private val passwordSuppliedWaiter = CountDownLatch(1) private val usernameSuppliedWaiter = CountDownLatch(1) @Volatile private var passwordAsked: Boolean = false @Volatile private var usernameAsked: Boolean = false @Volatile private lateinit var password: String @Volatile private lateinit var username: String override fun askPassword(url: String): String { passwordAsked = true passwordAskedWaiter.countDown() assertTrue("Password was not supplied during the reasonable period of time", passwordSuppliedWaiter.await(TIMEOUT.toLong(), TimeUnit.SECONDS)) return password } override fun askUsername(url: String): String { usernameAsked = true usernameAskedWaiter.countDown() assertTrue("Password was not supplied during the reasonable period of time", usernameSuppliedWaiter.await(TIMEOUT.toLong(), TimeUnit.SECONDS)) return username } internal fun supplyPassword(password: String) { this.password = password passwordSuppliedWaiter.countDown() } internal fun supplyUsername(username: String) { this.username = username usernameSuppliedWaiter.countDown() } internal fun waitUntilPasswordIsAsked() { assertTrue("Password was not asked during the reasonable period of time", passwordAskedWaiter.await(TIMEOUT.toLong(), TimeUnit.SECONDS)) } internal fun waitUntilUsernameIsAsked() { assertTrue("Username was not asked during the reasonable period of time", usernameAskedWaiter.await(TIMEOUT.toLong(), TimeUnit.SECONDS)) } override fun saveAuthData() {} override fun forgetPassword() {} override fun wasCancelled(): Boolean { return false } internal fun wasPasswordAsked(): Boolean { return passwordAsked } internal fun wasUsernameAsked(): Boolean { return usernameAsked } } }
plugins/git4idea/tests/git4idea/remote/GitRemoteTest.kt
1195651295
package org.metplus.cruncher.resume import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.metplus.cruncher.rating.CrunchResumeProcessSpy import org.metplus.cruncher.rating.CruncherMetaData internal class UploadResumeTest { private lateinit var resumeRepository: ResumeRepository private lateinit var uploadResume: UploadResume private lateinit var resumeFileRepository: ResumeFileRepository private lateinit var cruncherResumeProcessSpy: CrunchResumeProcessSpy @BeforeEach fun setup() { resumeRepository = ResumeRepositoryFake() resumeFileRepository = ResumeFileRepositoryFake() cruncherResumeProcessSpy = CrunchResumeProcessSpy() uploadResume = UploadResume(resumeRepository, resumeFileRepository, cruncherResumeProcessSpy) } @Test fun `when resume does not exist, it creates a new resume and enqueues the resume to be processed`() { val newResume = Resume( userId = "someUserId", fileType = "pdf", filename = "some_file_name.pdf", cruncherData = mapOf() ) val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_file_name.pdf", file = fileInputStream, size = 1, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { fail("Called onException when onSuccess was expected") return false } override fun onSuccess(resume: Resume): Boolean { return true } override fun onEmptyFile(resume: Resume): Boolean { fail("Called onEmptyFile when onSuccess was expected") return false } }) as Boolean).isTrue() assertThat(resumeRepository.getByUserId("someUserId")) .isEqualToComparingFieldByField(newResume) assertThat(resumeFileRepository.getByUserId("someUserId")) .isNotNull assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isEqualTo(newResume) } @Test fun `when resume exists, it overrides with new resume and saves the file and enqueues the resume to be processed`() { resumeRepository.save(Resume( filename = "some_file_name.pdf", fileType = "pdf", userId = "someUserId", cruncherData = mapOf("cruncher1" to CruncherMetaData(metaData = hashMapOf())) )) val newResume = Resume( userId = "someUserId", fileType = "doc", filename = "some_other_file.doc", cruncherData = mapOf() ) val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_other_file.doc", file = fileInputStream, size = 1, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { fail("Called onException when onSuccess was expected") return false } override fun onSuccess(resume: Resume): Boolean { return true } override fun onEmptyFile(resume: Resume): Boolean { fail("Called onEmptyFile when onSuccess was expected") return false } }) as Boolean).isTrue() assertThat(resumeRepository.getByUserId("someUserId")) .isEqualToComparingFieldByField(newResume) assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isEqualTo(newResume) } @Test fun `when resume file is empty, it does not save the file and call the onEmptyFile observer`() { val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_other_file.doc", file = fileInputStream, size = 0, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { fail("Called onException when onEmptyFile was expected") return false } override fun onSuccess(resume: Resume): Boolean { fail("Called onSuccess when onSuccess was expected") return false } override fun onEmptyFile(resume: Resume): Boolean { return true } }) as Boolean).isTrue() assertThat(resumeRepository.getByUserId("someUserId")).isNull() assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isNull() } @Test fun `when resume throw exception while saving, it does not save the file and call the onException observer`() { resumeRepository = ResumeRepositoryStub() (resumeRepository as ResumeRepositoryStub).throwOnSave = Exception("Some exception") uploadResume = UploadResume(resumeRepository, resumeFileRepository, cruncherResumeProcessSpy) val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_other_file.doc", file = fileInputStream, size = 1, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { assertThat(exception.message).isEqualTo("Some exception") return true } override fun onSuccess(resume: Resume): Boolean { fail("Called onSuccess when onSuccess was expected") return false } override fun onEmptyFile(resume: Resume): Boolean { fail("Called onException when onEmptyFile was expected") return false } }) as Boolean).isTrue() try { resumeFileRepository.getByUserId("someUserId") fail("Exception should have been thrown") } catch (exception: ResumeNotFound) { assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isNull() } } }
core/src/test/kotlin/org/metplus/cruncher/resume/UploadResumeTest.kt
2652900213
package com.bravelocation.yeltzlandnew.views import androidx.compose.foundation.text.ClickableText import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import com.bravelocation.yeltzlandnew.tweet.DisplayTweet import com.bravelocation.yeltzlandnew.ui.AppColors import com.bravelocation.yeltzlandnew.ui.AppTypography import com.bravelocation.yeltzlandnew.utilities.LinkHelper @Composable fun TweetBodyView(tweet: DisplayTweet) { val context = LocalContext.current val tweetParts = tweet.textParts() val tweetString = buildAnnotatedString { tweetParts.forEach { part -> if (part.highlight() && part.linkUrl != null) { pushStringAnnotation(tag = "URL", annotation = part.linkUrl) withStyle(style = SpanStyle(color = AppColors.linkColor())) { append(part.text) } pop() } else { withStyle(style = SpanStyle(color = MaterialTheme.colors.onBackground)) { append(part.text) } } } } ClickableText( text = tweetString, style = AppTypography.body, onClick = { offset -> // We check if there is an *URL* annotation attached to the text // at the clicked position tweetString.getStringAnnotations(tag = "URL", start = offset, end = offset) .firstOrNull()?.let { annotation -> LinkHelper.openExternalUrl(context, annotation.item) } } ) }
app/src/main/java/com/bravelocation/yeltzlandnew/views/TweetBodyView.kt
84106839
package graphql.kickstart.tools import org.junit.Test class GenericResolverTest { @Test fun `methods from generic resolvers are resolved`() { SchemaParser.newParser() .schemaString( """ type Query { bar: Bar } type Bar { value: String } """) .resolvers(QueryResolver1(), BarResolver()) .build() .makeExecutableSchema() } class QueryResolver1 : GraphQLQueryResolver { fun getBar(): Bar { return Bar() } } class Bar abstract class FooResolver<T> : GraphQLResolver<T> { fun getValue(foo: T): String = "value" } class BarResolver : FooResolver<Bar>(), GraphQLResolver<Bar> @Test fun `methods from generic inherited resolvers are resolved`() { SchemaParser.newParser() .schemaString( """ type Query { car: Car } type Car { value: String } """) .resolvers(QueryResolver2(), CarResolver()) .build() .makeExecutableSchema() } class QueryResolver2 : GraphQLQueryResolver { fun getCar(): Car = Car() } abstract class FooGraphQLResolver<T> : GraphQLResolver<T> { fun getValue(foo: T): String = "value" } class Car class CarResolver : FooGraphQLResolver<Car>() }
src/test/kotlin/graphql/kickstart/tools/GenericResolverTest.kt
2498274485
package com.sys1yagi.mastodon4j.api.exception import okhttp3.Response class Mastodon4jRequestException : Exception { val response: Response? constructor(response: Response) : super(response.message()) { this.response = response } constructor(e : Exception) : super(e) { this.response = null } fun isErrorResponse() = response != null }
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/exception/Mastodon4jRequestException.kt
2739642118
package com.neeplayer.compose import androidx.annotation.DrawableRes import androidx.compose.animation.Crossfade import androidx.compose.foundation.* import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.BottomSheetScaffold import androidx.compose.material.BottomSheetValue import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Slider import androidx.compose.material.Text import androidx.compose.material.rememberBottomSheetScaffoldState import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.rememberImagePainter import coil.size.Scale @Composable fun NowPlayingBottomSheetContent( state: NowPlayingState?, sheetValue: BottomSheetValue, actions: NowPlayingActions, ) { Box { Body(state = state, actions = actions) Crossfade(targetState = sheetValue) { value -> if (value == BottomSheetValue.Collapsed) { Header(state = state, onPlayPauseClick = { actions.playOrPause() }) } } } } @Composable private fun Body(state: NowPlayingState?, actions: NowPlayingActions) { Column { Image( painter = rememberImagePainter(data = state?.album?.art) { scale(Scale.FIT) }, modifier = Modifier.fillMaxWidth().aspectRatio(1f), contentDescription = null, ) Spacer(modifier = Modifier.weight(1f)) Column( modifier = Modifier .padding(16.dp) .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( style = MaterialTheme.typography.body1.copy(fontSize = 22.sp), text = state?.song?.title.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis, ) Text( style = MaterialTheme.typography.body2.copy(fontSize = 18.sp), text = "${state?.artist?.name} — ${state?.album?.title}", maxLines = 1, overflow = TextOverflow.Ellipsis, ) } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, ) { MusicControl(R.drawable.ic_fast_rewind_black_48dp) { actions.playPrevious() } MusicControl(state.playPauseResource()) { actions.playOrPause() } MusicControl(R.drawable.ic_fast_forward_black_48dp) { actions.playNext() } } Box(modifier = Modifier.padding(8.dp)) { Slider( value = state?.progress?.toFloat() ?: 0f, valueRange = 0f..(state?.song?.duration?.toFloat() ?: 1f), onValueChange = { value -> actions.seekTo(value.toLong()) }, ) Row(modifier = Modifier .padding(start = 8.dp, end = 8.dp, top = 40.dp) .align(Alignment.BottomCenter)) { Text( style = MaterialTheme.typography.caption, text = state?.progress.formatDuration(), ) Spacer(modifier = Modifier.weight(1f)) Text( style = MaterialTheme.typography.caption, text = state?.song?.duration.formatDuration(), ) } } Spacer(modifier = Modifier.weight(1f)) } } @Composable private fun Header(state: NowPlayingState?, onPlayPauseClick: () -> Unit = {}) { Row( modifier = Modifier .height(72.dp) .background(MaterialTheme.colors.background) .padding(4.dp), verticalAlignment = Alignment.CenterVertically, ) { Image( painter = rememberImagePainter(data = state?.album?.art) { scale(Scale.FIT) }, contentDescription = null, modifier = Modifier.size(64.dp), ) Column(modifier = Modifier .weight(1f) .padding(start = 12.dp, end = 12.dp)) { Text( text = state?.song?.title.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.body1 ) Text( text = state?.artist?.name.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.body2 ) } MusicControl(iconResource = state.playPauseResource(), width = 48.dp, onClick = onPlayPauseClick) } } @Composable private fun MusicControl( @DrawableRes iconResource: Int, width: Dp = 88.dp, onClick: () -> Unit = {}, ) { Box( modifier = Modifier .width(width) .clickable( onClick = onClick, indication = rememberRipple(bounded = false, radius = 56.dp), interactionSource = remember { MutableInteractionSource() }, ), contentAlignment = Alignment.Center, ) { Icon(painter = painterResource(id = iconResource), contentDescription = null) } } private fun NowPlayingState?.playPauseResource() = if (this?.playing != true) R.drawable.ic_play_arrow_black_48dp else R.drawable.ic_pause_black_48dp @Preview @Composable fun PreviewNowPlayingScreen() = NeeTheme { Body(NowPlayingState( playlist = listOf(PlaylistItem( song = Sample.songs.first(), album = Sample.albums.first().album, artist = Sample.artists.first(), )), position = 0, playing = true, progress = 0, ), AppStateContainer()) }
compose/src/main/java/com/neeplayer/compose/NowPlayingBottomSheet.kt
1939890894
package com.didichuxing.doraemonkit.kit.mc.oldui.record import android.os.Bundle import android.view.View import android.widget.TextView import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.didichuxing.doraemonkit.extension.doKitGlobalScope import com.didichuxing.doraemonkit.kit.core.BaseFragment import com.didichuxing.doraemonkit.kit.mc.ui.adapter.McCaseInfo import com.didichuxing.doraemonkit.kit.mc.ui.adapter.McCaseListAdapter import com.didichuxing.doraemonkit.kit.test.mock.http.HttpMockServer import com.didichuxing.doraemonkit.kit.mc.utils.McCaseUtils import com.didichuxing.doraemonkit.kit.test.DoKitTestManager import com.didichuxing.doraemonkit.mc.R import com.didichuxing.doraemonkit.util.ToastUtils import com.didichuxing.doraemonkit.widget.recyclerview.DividerItemDecoration import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/12/10-10:52 * 描 述: * 修订历史: * ================================================ */ class DoKitMcDatasFragment : BaseFragment() { private lateinit var mRv: RecyclerView private lateinit var mEmpty: TextView private lateinit var mAdapter: McCaseListAdapter override fun onRequestLayout(): Int { return R.layout.dk_fragment_mc_datas } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mRv = findViewById(R.id.rv) mEmpty = findViewById(R.id.tv_empty) mAdapter = McCaseListAdapter(mutableListOf<McCaseInfo>()) mAdapter.setOnItemClickListener { adapter, _, pos -> val item = adapter.data[pos] as McCaseInfo if (item.isChecked) { for (i in adapter.data) { (i as McCaseInfo).isChecked = false } McCaseUtils.saveCaseId("") } else { for (i in adapter.data) { (i as McCaseInfo).isChecked = false } item.isChecked = true McCaseUtils.saveCaseId(item.caseId) ToastUtils.showShort("用例: ${item.caseName} 已被选中") } if (DoKitTestManager.isHostMode()) { doKitGlobalScope.launch { delay(100) adapter.notifyDataSetChanged() } } else { adapter.notifyDataSetChanged() } } mRv.apply { adapter = mAdapter layoutManager = LinearLayoutManager(requireActivity()) val decoration = DividerItemDecoration(DividerItemDecoration.VERTICAL) decoration.setDrawable(resources.getDrawable(R.drawable.dk_divider)) addItemDecoration(decoration) } lifecycleScope.launch { val data = HttpMockServer.caseList<McCaseInfo>().data data?.let { if (it.isEmpty()) { mEmpty.visibility = View.VISIBLE } else { val caseId = McCaseUtils.loadCaseId() it.forEach { info -> info.isChecked = caseId == info.caseId } mAdapter.setList(it) } } } } }
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/record/DoKitMcDatasFragment.kt
436811614
package com.aglushkov.wordteacher.apiproviders.google.model import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import android.os.Parcelable import com.aglushkov.wordteacher.model.WordTeacherWord import java.util.* @Parcelize data class GoogleWord( @SerializedName("meaning") val definitions: GoogleDefinitions, @SerializedName("origin") val origin: String?, @SerializedName("phonetic") val phonetic: String?, @SerializedName("word") val word: String ) : Parcelable fun GoogleWord.asWordTeacherWord(): WordTeacherWord? { return WordTeacherWord(word, phonetic, definitions.asMap(), listOf(this@asWordTeacherWord)) }
app_wordteacher/src/main/java/com/aglushkov/wordteacher/apiproviders/google/model/GoogleWord.kt
457343851
package com.calintat.units.activities import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.net.Uri import android.os.Bundle import android.support.annotation.IdRes import android.support.customtabs.CustomTabsIntent import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.app.AppCompatDelegate import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.view.Gravity import android.widget.EditText import com.calintat.alps.getBoolean import com.calintat.alps.getInt import com.calintat.alps.getString import com.calintat.alps.putInt import com.calintat.units.R import com.calintat.units.api.Converter import com.calintat.units.api.Item import com.calintat.units.recycler.Adapter import com.calintat.units.ui.MainUI import com.calintat.units.utils.BillingHelper import com.calintat.units.utils.CurrencyHelper import org.jetbrains.anko.* import org.jetbrains.anko.sdk21.listeners.textChangedListener class MainActivity : AppCompatActivity() { companion object { private val KEY_ID = "com.calintat.units.KEY_ID" private val KEY_INPUT = "com.calintat.units.KEY_INPUT" } private val ui = MainUI() private var id: Int? = null private var position: Int? = null private var billingHelper: BillingHelper? = null private val adapter by lazy { Adapter(this) } private val currency get() = id == R.id.navigation_currency private val currencyAuto get() = getInt("pref_currency", 0) == 0 //---------------------------------------------------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui.setContentView(this) setTheme() setToolbar() setMainContent() setNavigationView() init(savedInstanceState) billingHelper = BillingHelper(this) } override fun onDestroy() { super.onDestroy() billingHelper?.destroy() } override fun onResume() { super.onResume() refreshActionMenu() refreshRecyclerView() refreshNavigationView() } override fun onBackPressed() { when { ui.drawerLayout.isDrawerOpen(Gravity.START) -> ui.drawerLayout.closeDrawers() else -> super.onBackPressed() } } override fun onSaveInstanceState(outState: Bundle) { id?.let { outState.putInt(KEY_ID, it) } outState.putString(KEY_INPUT, ui.editText.text.toString()) super.onSaveInstanceState(outState) } //---------------------------------------------------------------------------------------------- private fun init(savedInstanceState: Bundle?) { val defaultId = getInt(KEY_ID).takeIf { Item.isIdSafe(it) } ?: R.id.navigation_length if (savedInstanceState == null) { /* opened from launcher or app shortcut */ selectId(Item.get(intent)?.id ?: defaultId) } else { /* orientation change, activity resumed, etc */ selectId(savedInstanceState.getInt(KEY_ID, defaultId)) ui.editText.setText(savedInstanceState.getString(KEY_INPUT)) } } private fun selectId(@IdRes id: Int) { this.id = id if (currency && currencyAuto) actionRefresh() putInt(KEY_ID, id) refreshActionMenu() val item = Item.get(id) ?: return adapter.units = Converter.retrieveUnits(item) selectPosition(0) ui.toolbar.setBackgroundResource(item.color) ui.drawerLayout.setStatusBarBackground(item.colorDark) } private fun selectPosition(position: Int) { this.position = position refreshRecyclerView() ui.textView1.setText(adapter.units[position].label) ui.textView2.setText(adapter.units[position].shortLabel) } private fun setTheme() { AppCompatDelegate.setDefaultNightMode(getInt("pref_theme", 1)) } private fun setToolbar() { ui.toolbar.inflateMenu(R.menu.action) ui.toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.action_refresh -> actionRefresh() R.id.action_clear -> actionClear() } true } ui.toolbar.setNavigationIcon(R.drawable.ic_action_menu) ui.toolbar.setNavigationOnClickListener { ui.drawerLayout.openDrawer(Gravity.START) } ui.toolbar.overflowIcon = ContextCompat.getDrawable(this, R.drawable.ic_action_overflow) } private fun setMainContent() { ui.editText.afterTextChanged { refreshActionMenu(); refreshRecyclerView() } adapter.onClick = { selectPosition(it) } adapter.onLongClick = { copyToClipboard(it) } ui.recyclerView.adapter = adapter ui.recyclerView.layoutManager = LinearLayoutManager(this) ui.recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL)) } private fun setNavigationView() { ui.navigationView.inflateMenu(R.menu.navigation) ui.navigationView.setNavigationItemSelectedListener { ui.drawerLayout.closeDrawers() when (it.itemId) { R.id.navigation_settings -> startActivity<SettingsActivity>() R.id.navigation_feedback -> gotoFeedback() R.id.navigation_donation -> makeDonation() else -> selectId(it.itemId) } true } } private fun actionClear() = ui.editText.text.clear() private fun actionRefresh() = CurrencyHelper.loadData { if (it.date != getString("pref_currency_date", "2017-08-01")) { it.persist(this) refreshRecyclerView() longToast(getString(R.string.msg_retrieved_exchange_rates, it.date)) } else if (!currencyAuto) toast(R.string.err_rates_are_already_up_to_date) } private fun refreshActionMenu() { ui.toolbar.menu.findItem(R.id.action_clear).isVisible = ui.editText.text.isNotEmpty() ui.toolbar.menu.findItem(R.id.action_refresh).isVisible = currency && !currencyAuto } private fun refreshRecyclerView() { val num = ui.editText.text.toString().toDoubleOrNull() ?: Double.NaN position?.let { adapter.input = adapter.units[it].selfToBase(this, num) } } private fun refreshNavigationView() { ui.navigationView.menu.setGroupVisible(R.id.science, getBoolean("pref_science", true)) ui.navigationView.menu.setGroupVisible(R.id.medical, getBoolean("pref_medical", false)) } private fun gotoFeedback() { val builder = CustomTabsIntent.Builder() builder.build().launchUrl(this, Uri.parse("https://github.com/calintat/units/issues")) } private fun makeDonation() { val title = getString(R.string.navigation_donation) val items = listOf("£0.99", "£1.99", "£2.99", "£3.99", "£4.99", "£9.99") selector(title, items) { _, index -> billingHelper?.makeDonation("donation$index") } } private fun copyToClipboard(text: String) { val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.primaryClip = ClipData.newPlainText("conversion output", text) toast(R.string.msg_clipboard) } private fun EditText.afterTextChanged(listener: (Editable?) -> Unit) { textChangedListener { afterTextChanged(listener) } } }
app/src/main/java/com/calintat/units/activities/MainActivity.kt
2636033218
package io.github.detekt.report.sarif import io.github.detekt.psi.toUnifiedString import io.github.detekt.sarif4k.ArtifactLocation import io.github.detekt.sarif4k.Run import io.github.detekt.sarif4k.SarifSchema210 import io.github.detekt.sarif4k.SarifSerializer import io.github.detekt.sarif4k.Tool import io.github.detekt.sarif4k.ToolComponent import io.github.detekt.sarif4k.Version import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.OutputReport import io.gitlab.arturbosch.detekt.api.SetupContext import io.gitlab.arturbosch.detekt.api.SingleAssign import io.gitlab.arturbosch.detekt.api.UnstableApi import io.gitlab.arturbosch.detekt.api.getOrNull import io.gitlab.arturbosch.detekt.api.internal.whichDetekt import java.nio.file.Path const val DETEKT_OUTPUT_REPORT_BASE_PATH_KEY = "detekt.output.report.base.path" const val SRCROOT = "%SRCROOT%" class SarifOutputReport : OutputReport() { override val ending: String = "sarif" override val id: String = "sarif" override val name = "SARIF: a standard format for the output of static analysis tools" private var config: Config by SingleAssign() private var basePath: String? = null @OptIn(UnstableApi::class) override fun init(context: SetupContext) { this.config = context.config this.basePath = context.getOrNull<Path>(DETEKT_OUTPUT_REPORT_BASE_PATH_KEY) ?.toAbsolutePath() ?.toUnifiedString() ?.let { if (!it.endsWith("/")) "$it/" else it } } override fun render(detektion: Detektion): String { val version = whichDetekt() val sarifSchema210 = SarifSchema210( schema = "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json", version = Version.The210, runs = listOf( Run( tool = Tool( driver = ToolComponent( downloadURI = "https://github.com/detekt/detekt/releases/download/v$version/detekt", fullName = "detekt", guid = "022ca8c2-f6a2-4c95-b107-bb72c43263f3", informationURI = "https://detekt.github.io/detekt", language = "en", name = "detekt", rules = toReportingDescriptors(config), organization = "detekt", semanticVersion = version, version = version ) ), originalURIBaseIDS = basePath?.let { mapOf(SRCROOT to ArtifactLocation(uri = "file://$basePath")) }, results = toResults(detektion) ) ) ) return SarifSerializer.toJson(sarifSchema210) } }
detekt-report-sarif/src/main/kotlin/io/github/detekt/report/sarif/SarifOutputReport.kt
582875793
package net.nemerosa.ontrack.extension.stash.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class BitbucketProject( val id: Int, val key: String, val name: String )
ontrack-extension-stash/src/main/java/net/nemerosa/ontrack/extension/stash/model/BitbucketProject.kt
3229291526
package net.nemerosa.ontrack.extension.casc.entities import net.nemerosa.ontrack.model.structure.ProjectEntityType import org.springframework.stereotype.Component @Component class CascEntityProjectContext( propertiesContext: CascEntityPropertiesContext, ) : AbstractCascEntityRootContext(propertiesContext) { override val entityType: ProjectEntityType = ProjectEntityType.PROJECT }
ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/entities/CascEntityProjectContext.kt
307348326
package net.nemerosa.ontrack.extension.github.property import net.nemerosa.ontrack.extension.github.AbstractGitHubTestJUnit4Support import net.nemerosa.ontrack.extension.github.GitHubIssueServiceExtension import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.test.assertIs import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertNotNull class GitHubProjectConfigurationPropertyTypeIT : AbstractGitHubTestJUnit4Support() { @Autowired private lateinit var gitHubConfigurator: GitHubConfigurator @Test fun `Setting GitHub issues as issue service`() { asAdmin { val cfg = gitHubConfig() project { propertyService.editProperty(this, GitHubProjectConfigurationPropertyType::class.java.name, mapOf( "configuration" to cfg.name, "repository" to "nemerosa/ontrack", "indexationInterval" to 0, "issueServiceConfigurationIdentifier" to "self" ).asJson()) // Gets the issue service configuration assertNotNull(gitHubConfigurator.getConfiguration(this)) { gitConfiguration -> assertNotNull(gitConfiguration.configuredIssueService) { configuredIssueService -> assertIs<GitHubIssueServiceExtension>(configuredIssueService.issueServiceExtension) } } } } } }
ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/property/GitHubProjectConfigurationPropertyTypeIT.kt
921114494
@file:JvmName("RxAdapterView") @file:JvmMultifileClass package com.jakewharton.rxbinding3.widget import android.view.View import android.widget.Adapter import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import com.jakewharton.rxbinding3.InitialValueObservable import io.reactivex.Observer import io.reactivex.android.MainThreadDisposable import android.widget.AdapterView.INVALID_POSITION import androidx.annotation.CheckResult import com.jakewharton.rxbinding3.internal.checkMainThread /** * Create an observable of the selected position of `view`. If nothing is selected, * [AdapterView.INVALID_POSITION] will be emitted. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun <T : Adapter> AdapterView<T>.itemSelections(): InitialValueObservable<Int> { return AdapterViewItemSelectionObservable(this) } private class AdapterViewItemSelectionObservable( private val view: AdapterView<*> ) : InitialValueObservable<Int>() { override fun subscribeListener(observer: Observer<in Int>) { if (!checkMainThread(observer)) { return } val listener = Listener(view, observer) view.onItemSelectedListener = listener observer.onSubscribe(listener) } override val initialValue get() = view.selectedItemPosition private class Listener( private val view: AdapterView<*>, private val observer: Observer<in Int> ) : MainThreadDisposable(), OnItemSelectedListener { override fun onItemSelected(adapterView: AdapterView<*>, view: View, position: Int, id: Long) { if (!isDisposed) { observer.onNext(position) } } override fun onNothingSelected(adapterView: AdapterView<*>) { if (!isDisposed) { observer.onNext(INVALID_POSITION) } } override fun onDispose() { view.onItemSelectedListener = null } } }
rxbinding/src/main/java/com/jakewharton/rxbinding3/widget/AdapterViewItemSelectionObservable.kt
3551420446
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import ink.abb.pogo.api.cache.Pokestop import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.Task import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.map.distance import ink.abb.pogo.scraper.util.pokemon.distance import ink.abb.pogo.scraper.util.map.inRangeForLuredPokemon import java.util.* import java.util.concurrent.TimeUnit /** * Task that handles catching pokemon, activating stops, and walking to a new target. */ class ProcessPokestops(var pokestops: List<Pokestop>) : Task { val refetchTime = TimeUnit.SECONDS.toMillis(30) var lastFetch: Long = 0 private val lootTimeouts = HashMap<String, Long>() var startPokestop: Pokestop? = null override fun run(bot: Bot, ctx: Context, settings: Settings) { var writeCampStatus = false if (lastFetch + refetchTime < bot.api.currentTimeMillis()) { writeCampStatus = true lastFetch = bot.api.currentTimeMillis() if (settings.allowLeaveStartArea) { try { val newStops = ctx.api.map.getPokestops(ctx.api.latitude, ctx.api.longitude, 9) if (newStops.size > 0) { pokestops = newStops } } catch (e: Exception) { // ignored failed request } } } val sortedPokestops = pokestops.sortedWith(Comparator { a, b -> a.distance.compareTo(b.distance) }) if (startPokestop == null) startPokestop = sortedPokestops.first() if (settings.lootPokestop) { val loot = LootOneNearbyPokestop(sortedPokestops, lootTimeouts) try { bot.task(loot) } catch (e: Exception) { ctx.pauseWalking.set(false) } } if (settings.campLurePokestop > 0 && !ctx.pokemonInventoryFullStatus.get() && settings.catchPokemon) { val luresInRange = sortedPokestops.filter { it.inRangeForLuredPokemon() && it.fortData.hasLureInfo() } if (luresInRange.size >= settings.campLurePokestop) { if (writeCampStatus) { Log.green("${luresInRange.size} lure(s) in range, pausing") } return } } val walk = Walk(sortedPokestops, lootTimeouts) bot.task(walk) } }
src/main/kotlin/ink/abb/pogo/scraper/tasks/ProcessPokestops.kt
4034919492
package siarhei.luskanau.example.camera.app import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory import com.example.camera.library.FileProviderUtils import siarhei.luskanau.example.camera.app.databinding.ActivityMainBinding import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ActivityMainBinding.inflate(LayoutInflater.from(this)) .also { binding = it setContentView(binding.root) } val takePictureLauncher = registerForActivityResult(ActivityResultContracts.TakePicture()) { val uri = FileProviderUtils.getFileProviderUri(this, CAMERA_TEMP_FILE_NAME) showImageUri(uri) } binding.cameraButton.setOnClickListener { FileProviderUtils.deleteFile(this, CAMERA_TEMP_FILE_NAME) val uri = FileProviderUtils.getFileProviderUri(this, CAMERA_TEMP_FILE_NAME) takePictureLauncher.launch(uri) } val getContentLauncher = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { showImageUri(it) } binding.galleryButton.setOnClickListener { getContentLauncher.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) } showImageUri(null) } @Suppress("TooGenericExceptionCaught") private fun showImageUri(uri: Uri?) { binding.imageUriTextView.text = String.format(Locale.ENGLISH, "Uri: %s", uri.toString()) try { uri?.let { val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri)) val roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap) .apply { isCircular = true } binding.roundedImageView.setImageDrawable(roundedBitmapDrawable) binding.imageView.setImageURI(null) binding.imageView.setImageURI(uri) } ?: run { binding.imageView.setImageResource(R.drawable.ic_android_24dp) binding.roundedImageView.setImageResource(R.drawable.ic_android_24dp) } } catch (t: Throwable) { binding.imageUriTextView.text = t.toString() } } companion object { private const val CAMERA_TEMP_FILE_NAME = "camera_temp.jpg" } }
fileprovider-camera/app/src/main/java/siarhei/luskanau/example/camera/app/MainActivity.kt
4291044183
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.kotmahjan.rules.yaku.yakuimpl import dev.yuriel.kotmahjan.models.PlayerContext import dev.yuriel.kotmahjan.models.RoundContext import dev.yuriel.kotmahjan.rules.MentsuSupport /** * Created by yuriel on 7/24/16. */ fun 門前清模和Impl(r: RoundContext?, p: PlayerContext?, s: MentsuSupport): Boolean { if (r == null || p == null) { return false } var isOpen = false for (mentsu in s.allMentsu) { if (mentsu.isOpen) { isOpen = true } } return p.isTsumo() && !isOpen }
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/rules/yaku/yakuimpl/03_門前清模和.kt
4210830048
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.generator import org.jetbrains.android.anko.* import org.jetbrains.android.anko.annotations.ExternalAnnotation import org.jetbrains.android.anko.utils.fqName import org.jetbrains.android.anko.utils.getConstructors import org.objectweb.asm.tree.ClassNode //return a pair<viewGroup, layoutParams> or null if the viewGroup doesn't contain custom LayoutParams fun GenerationState.extractLayoutParams(viewGroup: ClassNode): LayoutElement? { fun findActualLayoutParamsClass(viewGroup: ClassNode): ClassNode? { fun findForParent() = findActualLayoutParamsClass(classTree.findNode(viewGroup)!!.parent!!.data) val generateMethod = viewGroup.methods.firstOrNull { method -> method.name == "generateLayoutParams" && method.args.size() == 1 && method.args[0].internalName == "android/util/AttributeSet" } ?: return findForParent() val returnTypeClass = classTree.findNode(generateMethod.returnType.internalName)!!.data if (!returnTypeClass.fqName.startsWith(viewGroup.fqName)) return findForParent() return if (returnTypeClass.isLayoutParams) returnTypeClass else findForParent() } val lpInnerClassName = viewGroup.innerClasses?.firstOrNull { it.name.contains("LayoutParams") } val lpInnerClass = lpInnerClassName?.let { classTree.findNode(it.name)!!.data } val externalAnnotations = config.annotationManager.findAnnotationsFor(viewGroup.fqName) val hasGenerateLayoutAnnotation = ExternalAnnotation.GenerateLayout in externalAnnotations val hasGenerateViewAnnotation = ExternalAnnotation.GenerateView in externalAnnotations if (hasGenerateViewAnnotation || (lpInnerClass == null && !hasGenerateLayoutAnnotation)) return null val actualLayoutParamsClass = findActualLayoutParamsClass(viewGroup).let { if (it != null && it.name != "android/view/ViewGroup\$LayoutParams") it else null } return (actualLayoutParamsClass ?: lpInnerClass)?.let { clazz -> LayoutElement(viewGroup, clazz, clazz.getConstructors().filter { it.isPublic }) } }
dsl/src/org/jetbrains/android/anko/generator/layoutParamsUtils.kt
879427006
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.geofence import android.Manifest import android.app.Application import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.preference.PreferenceManager import androidx.core.content.ContextCompat import com.gigigo.orchextra.core.domain.entities.GeoMarketing import com.gigigo.orchextra.core.domain.triggers.OxTrigger import com.gigigo.orchextra.core.utils.LogUtils import com.gigigo.orchextra.core.utils.LogUtils.LOGD import com.gigigo.orchextra.core.utils.LogUtils.LOGE import com.gigigo.orchextra.geofence.utils.toGeofence import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.GeofencingRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task class OxGeofenceImp private constructor( private val context: Application, private val geofencingClient: GeofencingClient ) : OxTrigger<List<GeoMarketing>>, OnCompleteListener<Void> { private var geofenceList: List<Geofence> = ArrayList() private var geofencePendingIntent: PendingIntent? = null override fun init() { if (geofenceList.isEmpty()) { LOGD(TAG, "geofences list is empty") return } connectWithCallbacks() addGeofences() } override fun setConfig(config: List<GeoMarketing>) { geofenceList = config.map { saveGeofenceRadius(context, it.code, it.radius) it.toGeofence() } } override fun finish() { removeGeofences() } private fun addGeofences() { if ( ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) { geofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent()) .addOnCompleteListener(this) } else { throw SecurityException("Geofence trigger needs ACCESS_FINE_LOCATION permission") } } private fun removeGeofences() { geofencingClient.removeGeofences(getGeofencePendingIntent()).addOnCompleteListener(this) } private fun getGeofencePendingIntent(): PendingIntent { if (geofencePendingIntent != null) { return geofencePendingIntent as PendingIntent } val intent = Intent(context, GeofenceBroadcastReceiver::class.java) geofencePendingIntent = PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) return geofencePendingIntent as PendingIntent } private fun connectWithCallbacks() { val googleApiClient = GoogleApiClient.Builder(context) .addApi(LocationServices.API) .addConnectionCallbacks(connectionAddListener) .addOnConnectionFailedListener(connectionFailedListener) .build() googleApiClient.connect() } private val connectionAddListener = object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(bundle: Bundle?) { LOGD(TAG, "connectionAddListener") } override fun onConnectionSuspended(i: Int) { LOGD(TAG, "onConnectionSuspended") } } private val connectionFailedListener = GoogleApiClient.OnConnectionFailedListener { LOGE(TAG, "connectionFailedListener") } override fun onComplete(task: Task<Void>) { if (task.isSuccessful) { updateGeofencesAdded(!getGeofencesAdded()) val message = if (getGeofencesAdded()) context.getString(R.string.geofences_added) else context.getString(R.string.geofences_removed) LOGD(TAG, "onComplete: $message") } else { task.exception?.let { LOGE(TAG, it.message ?: "no exception message") val errorMessage = GeofenceErrorMessages.getErrorString(context, it) LOGE(TAG, "onComplete: $errorMessage") } } } private fun getGeofencingRequest(): GeofencingRequest { val builder = GeofencingRequest.Builder() builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER) builder.addGeofences(geofenceList) return builder.build() } private fun getGeofencesAdded(): Boolean { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(GEOFENCES_ADDED_KEY, false) } private fun updateGeofencesAdded(added: Boolean) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putBoolean(GEOFENCES_ADDED_KEY, added) .apply() } companion object Factory { private val TAG = LogUtils.makeLogTag(OxGeofenceImp::class.java) private const val GEOFENCES_ADDED_KEY = "GEOFENCES_ADDED_KEY" fun create(context: Application) = OxGeofenceImp(context, LocationServices.getGeofencingClient(context)) fun saveGeofenceRadius(context: Context, code: String, radius: Int) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putInt(code, radius) .apply() } fun getGeofenceRadius(context: Context,code: String):Int { return PreferenceManager.getDefaultSharedPreferences(context) .getInt(code, -1) } } }
geofence/src/main/java/com/gigigo/orchextra/geofence/OxGeofenceImp.kt
2074417236
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2020 - present 8x8, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.xmpp import org.jitsi.xmpp.extensions.DefaultPacketExtensionProvider import org.jitsi.xmpp.extensions.colibri.ColibriConferenceIQ import org.jitsi.xmpp.extensions.colibri.ColibriConferenceIqProvider import org.jitsi.xmpp.extensions.colibri.ColibriStatsIqProvider import org.jitsi.xmpp.extensions.colibri.ForcefulShutdownIqProvider import org.jitsi.xmpp.extensions.colibri.GracefulShutdownIqProvider import org.jitsi.xmpp.extensions.colibri2.IqProviderUtils import org.jitsi.xmpp.extensions.health.HealthCheckIQProvider import org.jitsi.xmpp.extensions.health.HealthStatusPacketExt import org.jitsi.xmpp.extensions.jibri.JibriBusyStatusPacketExt import org.jitsi.xmpp.extensions.jibri.JibriIq import org.jitsi.xmpp.extensions.jibri.JibriIqProvider import org.jitsi.xmpp.extensions.jibri.JibriStatusPacketExt import org.jitsi.xmpp.extensions.jingle.JingleIQ import org.jitsi.xmpp.extensions.jingle.JingleIQProvider import org.jitsi.xmpp.extensions.jitsimeet.AudioMutedExtension import org.jitsi.xmpp.extensions.jitsimeet.BridgeSessionPacketExtension import org.jitsi.xmpp.extensions.jitsimeet.ConferenceIqProvider import org.jitsi.xmpp.extensions.jitsimeet.FeatureExtension import org.jitsi.xmpp.extensions.jitsimeet.FeaturesExtension import org.jitsi.xmpp.extensions.jitsimeet.IceStatePacketExtension import org.jitsi.xmpp.extensions.jitsimeet.JitsiParticipantRegionPacketExtension import org.jitsi.xmpp.extensions.jitsimeet.JsonMessageExtension import org.jitsi.xmpp.extensions.jitsimeet.LoginUrlIqProvider import org.jitsi.xmpp.extensions.jitsimeet.LogoutIqProvider import org.jitsi.xmpp.extensions.jitsimeet.MuteIqProvider import org.jitsi.xmpp.extensions.jitsimeet.MuteVideoIqProvider import org.jitsi.xmpp.extensions.jitsimeet.StartMutedProvider import org.jitsi.xmpp.extensions.jitsimeet.StatsId import org.jitsi.xmpp.extensions.jitsimeet.TranscriptionRequestExtension import org.jitsi.xmpp.extensions.jitsimeet.TranscriptionStatusExtension import org.jitsi.xmpp.extensions.jitsimeet.UserInfoPacketExt import org.jitsi.xmpp.extensions.jitsimeet.VideoMutedExtension import org.jitsi.xmpp.extensions.rayo.RayoIqProvider import org.jivesoftware.smack.SmackConfiguration import org.jivesoftware.smack.parsing.ExceptionLoggingCallback import org.jivesoftware.smack.provider.ProviderManager import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy fun initializeSmack() { System.setProperty("jdk.xml.entityExpansionLimit", "0") System.setProperty("jdk.xml.maxOccurLimit", "0") System.setProperty("jdk.xml.elementAttributeLimit", "524288") System.setProperty("jdk.xml.totalEntitySizeLimit", "0") System.setProperty("jdk.xml.maxXMLNameLimit", "524288") System.setProperty("jdk.xml.entityReplacementLimit", "0") SmackConfiguration.setDefaultReplyTimeout(15000) // if there is a parsing error, do not break the connection to the server(the default behaviour) as we need it for // the other conferences. SmackConfiguration.setDefaultParsingExceptionCallback(ExceptionLoggingCallback()) Socks5Proxy.setLocalSocks5ProxyEnabled(false) registerXmppExtensions() } fun registerXmppExtensions() { // Constructors called to register extension providers ConferenceIqProvider() LoginUrlIqProvider() LogoutIqProvider() ColibriConferenceIqProvider() GracefulShutdownIqProvider.registerIQProvider() ForcefulShutdownIqProvider.registerIQProvider() ColibriStatsIqProvider() HealthCheckIQProvider.registerIQProvider() // ice-state ProviderManager.addExtensionProvider( IceStatePacketExtension.ELEMENT, IceStatePacketExtension.NAMESPACE, DefaultPacketExtensionProvider(IceStatePacketExtension::class.java) ) // bridge-session ProviderManager.addExtensionProvider( BridgeSessionPacketExtension.ELEMENT, BridgeSessionPacketExtension.NAMESPACE, DefaultPacketExtensionProvider(BridgeSessionPacketExtension::class.java) ) // Jibri IQs ProviderManager.addIQProvider(JibriIq.ELEMENT, JibriIq.NAMESPACE, JibriIqProvider()) JibriStatusPacketExt.registerExtensionProvider() JibriBusyStatusPacketExt.registerExtensionProvider() HealthStatusPacketExt.registerExtensionProvider() // User info ProviderManager.addExtensionProvider( UserInfoPacketExt.ELEMENT, UserInfoPacketExt.NAMESPACE, DefaultPacketExtensionProvider(UserInfoPacketExt::class.java) ) ProviderManager.addExtensionProvider( JitsiParticipantRegionPacketExtension.ELEMENT, JitsiParticipantRegionPacketExtension.NAMESPACE, DefaultPacketExtensionProvider(JitsiParticipantRegionPacketExtension::class.java) ) ProviderManager.addExtensionProvider( StatsId.ELEMENT, StatsId.NAMESPACE, StatsId.Provider() ) // Add the extensions used for handling the inviting of transcriber ProviderManager.addExtensionProvider( TranscriptionRequestExtension.ELEMENT, TranscriptionRequestExtension.NAMESPACE, DefaultPacketExtensionProvider(TranscriptionRequestExtension::class.java) ) ProviderManager.addExtensionProvider( TranscriptionStatusExtension.ELEMENT, TranscriptionStatusExtension.NAMESPACE, DefaultPacketExtensionProvider(TranscriptionStatusExtension::class.java) ) // Register Colibri ProviderManager.addIQProvider( ColibriConferenceIQ.ELEMENT, ColibriConferenceIQ.NAMESPACE, ColibriConferenceIqProvider() ) // register Jingle ProviderManager.addIQProvider( JingleIQ.ELEMENT, JingleIQ.NAMESPACE, JingleIQProvider() ) ProviderManager.addExtensionProvider( JsonMessageExtension.ELEMENT, JsonMessageExtension.NAMESPACE, DefaultPacketExtensionProvider(JsonMessageExtension::class.java) ) ProviderManager.addExtensionProvider( FeaturesExtension.ELEMENT, FeaturesExtension.NAMESPACE, DefaultPacketExtensionProvider(FeaturesExtension::class.java) ) ProviderManager.addExtensionProvider( FeatureExtension.ELEMENT, FeatureExtension.NAMESPACE, DefaultPacketExtensionProvider(FeatureExtension::class.java) ) RayoIqProvider().registerRayoIQs() MuteIqProvider.registerMuteIqProvider() MuteVideoIqProvider.registerMuteVideoIqProvider() StartMutedProvider.registerStartMutedProvider() ProviderManager.addExtensionProvider( AudioMutedExtension.ELEMENT, AudioMutedExtension.NAMESPACE, DefaultPacketExtensionProvider(AudioMutedExtension::class.java) ) ProviderManager.addExtensionProvider( VideoMutedExtension.ELEMENT, VideoMutedExtension.NAMESPACE, DefaultPacketExtensionProvider(VideoMutedExtension::class.java) ) IqProviderUtils.registerProviders() }
jicofo/src/main/kotlin/org/jitsi/jicofo/xmpp/Smack.kt
1418703442
@file:JvmName("CSGO") package org.abendigo.csgo import org.abendigo.Addressable import org.abendigo.cached.Cached import org.jire.arrowhead.Module import org.jire.arrowhead.get import org.jire.arrowhead.processByName val csgo by lazy(LazyThreadSafetyMode.NONE) { processByName("csgo.exe")!! } val csgoModule by lazy(LazyThreadSafetyMode.NONE) { csgo.modules["csgo.exe"]!! } const val ENTITY_SIZE = 16 const val GLOW_OBJECT_SIZE = 56 inline fun <reified T : Any> cached(address: Int, offset: Int = 0) = Cached<T>({ csgo[address + offset] }) inline fun <reified T : Any> cached(address: Long, offset: Int = 0): Cached<T> = cached(address.toInt(), offset) inline fun <reified T : Any> cached(module: Module, offset: Int = 0) = Cached({ module.get<T>(offset) }) inline fun <reified T : Any> Addressable.cached(offset: Int = 0): Cached<T> = cached(this.address, offset)
src/main/kotlin/org/abendigo/csgo/CSGO.kt
2040529652
package br.com.edsilfer.android.starwarswiki.model.dictionary import com.google.gson.Gson /** * Created by ferna on 2/22/2017. */ class TMDBWrapperResponseDictionary { val results = mutableListOf<TMDBResponseDictionary>() val page = "" val total_pages = "" val total_results = "" override fun toString(): String { return Gson().toJson(this) } }
app/src/main/java/br/com/edsilfer/android/starwarswiki/model/dictionary/TMDBWrapperResponseDictionary.kt
2498653421
package ffc.app.util.value import android.support.annotation.ColorInt import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import android.widget.TextView import ffc.android.gone import ffc.app.R import org.jetbrains.anko.find import org.jetbrains.anko.findOptional class ValueItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val captionView: TextView private val labelView: TextView private val valueView: TextView private val iconView: ImageView? init { captionView = itemView.find(R.id.captionView) labelView = itemView.find(R.id.labelView) valueView = itemView.find(R.id.valueView) iconView = itemView.findOptional(R.id.iconView) } fun bind(value: Value) { bind(value.label, value.value, value.caption, value.color, value.colorRes, value.iconRes) } fun bind( label: String?, value: String = "-", caption: String? = null, @ColorInt color: Int? = null, @ColorRes colorRes: Int? = null, @DrawableRes iconRes: Int? = null ) { with(itemView) { labelView.text = label?.trim() labelView.visibility = if (label.isNullOrBlank()) View.GONE else View.VISIBLE valueView.text = value.trim() captionView.text = caption?.trim() captionView.visibility = if (caption == null) View.GONE else View.VISIBLE color?.let { valueView.setTextColor(it) } colorRes?.let { valueView.setTextColor(ContextCompat.getColor(context, it)) } iconView?.let { it.setImageResource(iconRes ?: 0) } } } fun hindLabel() { labelView.gone() } }
ffc/src/main/kotlin/ffc/app/util/value/ValueItemViewHolder.kt
3383752548
package com.pennapps.labs.pennmobile.classes import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import org.joda.time.DateTime import org.joda.time.Interval import java.util.LinkedList class Gym { // fields from parsing JSON @SerializedName("hours") @Expose private val hoursList: List<GymHours>? = null @Expose val name: String? = null // other fields private var intervalList: List<Interval>? = null // check if we've already gotten the hours. if we have, just return it, if not, get it val hours: List<Interval>? get() { if (intervalList != null) { return intervalList ?: hours } val tempMutableList: MutableList<Interval> = LinkedList() if (hoursList == null) { return null } for (g in hoursList) { tempMutableList.add(g.interval) } intervalList = tempMutableList return intervalList } val isOpen: Boolean get() { hours // update interval list val current = DateTime() intervalList?.let { intervals -> for (i in intervals) { if (i.contains(current)) { return true } } } return false } /*fun currentInterval(): Interval { val current = DateTime() for (i in intervalList!!) { if (i.contains(current)) { return i } } // if this isn't open right now, throw exception throw IllegalStateException() }*/ }
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/Gym.kt
4230471359
package org.wikipedia.gallery import kotlinx.serialization.Serializable @Serializable class MediaList { private val revision: String? = null private val tid: String? = null private val items: List<MediaListItem>? = null fun getItems(vararg types: String): MutableList<MediaListItem> { val list = mutableListOf<MediaListItem>() items?.let { mediaList -> list.addAll(mediaList.filter { it.showInGallery && types.contains(it.type) }) } return list } }
app/src/main/java/org/wikipedia/gallery/MediaList.kt
2533825674
package net.semlang.api.parser data class Position(val lineNumber: Int, val column: Int, val rawIndex: Int) { override fun toString(): String { return "L${lineNumber}:${column}" } } data class Range(val start: Position, val end: Position) { override fun toString(): String { if (start.lineNumber == end.lineNumber) { return "L${start.lineNumber}:${start.column}-${end.column}" } else { return "${start}-${end}" } } } data class Location(val documentUri: String, val range: Range) enum class IssueLevel { WARNING, ERROR, } data class Issue(val message: String, val location: Location?, val level: IssueLevel)
kotlin/semlang-parser-api/src/main/kotlin/parserApi.kt
4122418583
package com.stripe.example.activity import android.os.Bundle import androidx.lifecycle.Observer import com.stripe.android.view.BecsDebitWidget import com.stripe.example.databinding.BecsDebitActivityBinding class BecsDebitPaymentMethodActivity : StripeIntentActivity() { private val viewBinding: BecsDebitActivityBinding by lazy { BecsDebitActivityBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewModel.inProgress.observe(this, { enableUi(!it) }) viewModel.status.observe(this, Observer(viewBinding.status::setText)) viewBinding.element.validParamsCallback = object : BecsDebitWidget.ValidParamsCallback { override fun onInputChanged(isValid: Boolean) { viewBinding.payButton.isEnabled = isValid viewBinding.saveButton.isEnabled = isValid } } viewBinding.payButton.setOnClickListener { viewBinding.element.params?.let { createAndConfirmPaymentIntent("au", it) } } viewBinding.saveButton.setOnClickListener { viewBinding.element.params?.let { createAndConfirmSetupIntent("au", it) } } } private fun enableUi(enabled: Boolean) { viewBinding.payButton.isEnabled = enabled viewBinding.saveButton.isEnabled = enabled } }
example/src/main/java/com/stripe/example/activity/BecsDebitPaymentMethodActivity.kt
3140468486
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.antelope.cameracontrollers import android.hardware.camera2.CameraDevice import androidx.camera.integration.antelope.CameraParams import androidx.camera.integration.antelope.MainActivity import androidx.camera.integration.antelope.TestConfig import androidx.camera.integration.antelope.TestType import androidx.camera.integration.antelope.testEnded /** * Callbacks that track the state of the camera device using the Camera 2 API. */ class Camera2DeviceStateCallback( internal var params: CameraParams, internal var activity: MainActivity, internal var testConfig: TestConfig ) : CameraDevice.StateCallback() { /** * Camera device has opened successfully, record timing and initiate the preview stream. */ override fun onOpened(cameraDevice: CameraDevice) { params.timer.openEnd = System.currentTimeMillis() MainActivity.logd( "In CameraStateCallback onOpened: " + cameraDevice.id + " current test: " + testConfig.currentRunningTest.toString() ) params.isOpen = true params.device = cameraDevice when (testConfig.currentRunningTest) { TestType.INIT -> { // Camera opened, we're done testConfig.testFinished = true closePreviewAndCamera(activity, params, testConfig) } else -> { params.timer.previewStart = System.currentTimeMillis() createCameraPreviewSession(activity, params, testConfig) } } } /** * Camera device has been closed, recording close timing. * * If this is a switch test, swizzle camera ids and move to the next step of the test. */ override fun onClosed(camera: CameraDevice) { MainActivity.logd( "In CameraStateCallback onClosed. Camera: " + params.id + " is closed. testFinished: " + testConfig.testFinished ) params.isOpen = false if (testConfig.testFinished) { params.timer.cameraCloseEnd = System.currentTimeMillis() testConfig.testFinished = false testEnded(activity, params, testConfig) return } if ((testConfig.currentRunningTest == TestType.SWITCH_CAMERA) || (testConfig.currentRunningTest == TestType.MULTI_SWITCH) ) { // First camera closed, now start the second if (testConfig.switchTestCurrentCamera == testConfig.switchTestCameras.get(0)) { testConfig.switchTestCurrentCamera = testConfig.switchTestCameras.get(1) camera2OpenCamera(activity, params, testConfig) } // Second camera closed, now start the first else if (testConfig.switchTestCurrentCamera == testConfig.switchTestCameras.get(1)) { testConfig.switchTestCurrentCamera = testConfig.switchTestCameras.get(0) testConfig.testFinished = true camera2OpenCamera(activity, params, testConfig) } } super.onClosed(camera) } /** * Camera has been disconnected. Whatever was happening, it won't work now. */ override fun onDisconnected(cameraDevice: CameraDevice) { MainActivity.logd("In CameraStateCallback onDisconnected: " + params.id) if (!params.isOpen) { return } testConfig.testFinished = false // Whatever we are doing will fail now, try to exit closePreviewAndCamera(activity, params, testConfig) } /** * Camera device has thrown an error. Try to recover or fail gracefully. */ override fun onError(cameraDevice: CameraDevice, error: Int) { MainActivity.logd("In CameraStateCallback onError: " + cameraDevice.id + " error: " + error) if (!params.isOpen) { return } when (error) { CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE -> { // Let's try to close an open camera and re-open this one MainActivity.logd("In CameraStateCallback too many cameras open, closing one...") closeACamera(activity, testConfig) camera2OpenCamera(activity, params, testConfig) } CameraDevice.StateCallback.ERROR_CAMERA_DEVICE -> { MainActivity.logd("Fatal camera error, close and try to re-initialize...") closePreviewAndCamera(activity, params, testConfig) camera2OpenCamera(activity, params, testConfig) } CameraDevice.StateCallback.ERROR_CAMERA_IN_USE -> { MainActivity.logd("This camera is already open... doing nothing") } else -> { testConfig.testFinished = false // Whatever we are doing will fail, just try to exit closePreviewAndCamera(activity, params, testConfig) } } } }
camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/cameracontrollers/Camera2DeviceStateCallback.kt
2726100609
package expo.modules.kotlin.exception internal inline fun <T> exceptionDecorator(decoratorBlock: (e: CodedException) -> Throwable, block: () -> T): T { return try { block() } catch (e: CodedException) { throw decoratorBlock(e) } catch (e: Throwable) { throw decoratorBlock(UnexpectedException(e)) } }
packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/exception/ExceptionDecorator.kt
3274564936
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.paging import androidx.paging.LoadType.APPEND import androidx.paging.LoadType.PREPEND import androidx.paging.LoadType.REFRESH import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.take import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @OptIn(ExperimentalCoroutinesApi::class) class HintHandlerTest { private val hintHandler = HintHandler() @Test fun initialState() { assertThat(hintHandler.lastAccessHint).isNull() assertThat(hintHandler.currentValue(APPEND)).isNull() assertThat(hintHandler.currentValue(PREPEND)).isNull() } @Test fun noStateForRefresh() = runTest(UnconfinedTestDispatcher()) { val refreshHints = kotlin.runCatching { hintHandler.hintFor(REFRESH) } assertThat(refreshHints.exceptionOrNull()).isInstanceOf( IllegalArgumentException::class.java ) } @Test fun expandChecks() { val initialHint = ViewportHint.Initial( presentedItemsAfter = 0, presentedItemsBefore = 0, originalPageOffsetFirst = 0, originalPageOffsetLast = 0 ).also(hintHandler::processHint) hintHandler.assertValues( prepend = initialHint, append = initialHint, lastAccessHint = null ) // both hints get updated w/ access hint val accessHint1 = ViewportHint.Access( pageOffset = 0, indexInPage = 1, presentedItemsBefore = 100, presentedItemsAfter = 100, originalPageOffsetLast = 0, originalPageOffsetFirst = 0 ).also(hintHandler::processHint) hintHandler.assertValues( prepend = accessHint1, append = accessHint1, lastAccessHint = accessHint1 ) // new access that only affects prepend val accessHintPrepend = accessHint1.copy( presentedItemsBefore = 70, presentedItemsAfter = 110 ).also(hintHandler::processHint) hintHandler.assertValues( prepend = accessHintPrepend, append = accessHint1, lastAccessHint = accessHintPrepend ) // new access hints that should be ignored val ignoredPrependHint = accessHintPrepend.copy( presentedItemsBefore = 90, ).also(hintHandler::processHint) hintHandler.assertValues( prepend = accessHintPrepend, append = accessHint1, lastAccessHint = ignoredPrependHint ) val accessHintAppend = accessHintPrepend.copy( presentedItemsAfter = 80, ).also(hintHandler::processHint) hintHandler.assertValues( prepend = accessHintPrepend, append = accessHintAppend, lastAccessHint = accessHintAppend ) // more ignored access hints hintHandler.processHint( accessHint1 ) hintHandler.assertValues( prepend = accessHintPrepend, append = accessHintAppend, lastAccessHint = accessHint1 ) hintHandler.processHint( initialHint ) hintHandler.assertValues( prepend = accessHintPrepend, append = accessHintAppend, lastAccessHint = accessHint1 ) // try changing original page offsets val newFirstOffset = accessHintPrepend.copy( originalPageOffsetFirst = 2 ).also(hintHandler::processHint) hintHandler.assertValues( prepend = newFirstOffset, append = newFirstOffset, lastAccessHint = newFirstOffset ) val newLastOffset = newFirstOffset.copy( originalPageOffsetLast = 5 ).also(hintHandler::processHint) hintHandler.assertValues( prepend = newLastOffset, append = newLastOffset, lastAccessHint = newLastOffset ) } @Test fun reset() { val initial = ViewportHint.Access( pageOffset = 0, indexInPage = 3, presentedItemsBefore = 10, presentedItemsAfter = 10, originalPageOffsetFirst = 0, originalPageOffsetLast = 0 ) hintHandler.processHint(initial) val appendReset = initial.copy( presentedItemsBefore = 20, presentedItemsAfter = 5 ) hintHandler.forceSetHint( APPEND, appendReset ) hintHandler.assertValues( prepend = initial, append = appendReset, lastAccessHint = initial ) val prependReset = initial.copy( presentedItemsBefore = 4, presentedItemsAfter = 19 ) hintHandler.forceSetHint( PREPEND, prependReset ) hintHandler.assertValues( prepend = prependReset, append = appendReset, lastAccessHint = initial ) } @Test fun resetCanReSendSameValues() = runTest(UnconfinedTestDispatcher()) { val hint = ViewportHint.Access( pageOffset = 0, indexInPage = 1, presentedItemsAfter = 10, presentedItemsBefore = 10, originalPageOffsetFirst = 0, originalPageOffsetLast = 0, ) val prependHints = collectAsync( hintHandler.hintFor(PREPEND) ) val appendHints = collectAsync( hintHandler.hintFor(APPEND) ) runCurrent() assertThat(prependHints.values).isEmpty() assertThat(appendHints.values).isEmpty() hintHandler.processHint(hint) runCurrent() assertThat(prependHints.values).containsExactly(hint) assertThat(appendHints.values).containsExactly(hint) // send same hint twice, it should not get dispatched hintHandler.processHint(hint.copy()) runCurrent() assertThat(prependHints.values).containsExactly(hint) assertThat(appendHints.values).containsExactly(hint) // how send that hint as reset, now it should get dispatched hintHandler.forceSetHint(PREPEND, hint) runCurrent() assertThat(prependHints.values).containsExactly(hint, hint) assertThat(appendHints.values).containsExactly(hint) hintHandler.forceSetHint(APPEND, hint) runCurrent() assertThat(prependHints.values).containsExactly(hint, hint) assertThat(appendHints.values).containsExactly(hint, hint) } private fun HintHandler.assertValues( prepend: ViewportHint, append: ViewportHint, lastAccessHint: ViewportHint.Access? ) { assertThat(currentValue(PREPEND)).isEqualTo(prepend) assertThat(currentValue(APPEND)).isEqualTo(append) assertThat(hintHandler.lastAccessHint).isEqualTo(lastAccessHint) } private fun HintHandler.currentValue( loadType: LoadType ): ViewportHint? { var value: ViewportHint? = null runTest(UnconfinedTestDispatcher()) { val job = launch { [email protected](loadType).take(1).collect { value = it } } runCurrent() job.cancel() } return value } private suspend fun CoroutineScope.collectAsync( flow: Flow<ViewportHint> ): TestCollection { val impl = TestCollectionImpl() async(context = impl.job) { flow.collect { impl.values.add(it) } } return impl } private interface TestCollection { val values: List<ViewportHint> fun stop() val latest: ViewportHint? get() = values.lastOrNull() } private class TestCollectionImpl : TestCollection { val job = Job() override val values = mutableListOf<ViewportHint>() override fun stop() { job.cancel() } } private fun ViewportHint.Access.copy( pageOffset: Int = [email protected], indexInPage: Int = [email protected], presentedItemsBefore: Int = [email protected], presentedItemsAfter: Int = [email protected], originalPageOffsetFirst: Int = [email protected], originalPageOffsetLast: Int = [email protected] ) = ViewportHint.Access( pageOffset = pageOffset, indexInPage = indexInPage, presentedItemsBefore = presentedItemsBefore, presentedItemsAfter = presentedItemsAfter, originalPageOffsetFirst = originalPageOffsetFirst, originalPageOffsetLast = originalPageOffsetLast ) }
paging/paging-common/src/test/kotlin/androidx/paging/HintHandlerTest.kt
794640708
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room /** * Marks a class as an auto migration spec that will be provided to Room at runtime. * * An instance of a class annotated with this annotation has to be provided to Room using * `Room.databaseBuilder.addAutoMigrationSpec(AutoMigrationSpec)`. Room will verify that * the spec is provided in the builder configuration and if not, an [IllegalArgumentException] * will be thrown. */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) public annotation class ProvidedAutoMigrationSpec
room/room-common/src/main/java/androidx/room/ProvidedAutoMigrationSpec.kt
3329359313
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ class Hil(public val o: Object) { fun crashInfer(nums : List<Long>) { val foldedNums = nums.fold(1) { _, _ -> 2 } val checked = checkNotNull(o) { "Boom" } val v = foldedNums.toLong() } }
infer/tests/codetoanalyze/kotlin/racerd/Hil.kt
2925189320
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeHighlighting.TextEditorHighlightingPassFactoryRegistrar import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar import com.intellij.openapi.project.Project class RsHighlightingPassFactoryRegistrar : TextEditorHighlightingPassFactoryRegistrar { override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) { RsExternalLinterPassFactory(project, registrar) RsMacroExpansionHighlightingPassFactory(project, registrar) } }
src/main/kotlin/org/rust/ide/annotator/RsHighlightingPassFactoryRegistrar.kt
1103664080
package solutions.day12 import solutions.AbstractDayTest class Day12Test: AbstractDayTest(Day12()) { override fun getPart1Data(): List<TestData> = listOf( TestData(listOf("0 <-> 2", "1 <-> 1", "2 <-> 0, 3, 4", "3 <-> 2, 4", "4 <-> 2, 3, 6", "5 <-> 6", "6 <-> 4, 5"), "6") ) override fun getPart2Data(): List<TestData> = listOf( TestData(listOf("0 <-> 2", "1 <-> 1", "2 <-> 0, 3, 4", "3 <-> 2, 4", "4 <-> 2, 3, 6", "5 <-> 6", "6 <-> 4, 5"), "2") ) }
src/test/kotlin/solutions/day12/Day12Test.kt
2458967007
package org.jetbrains.dokka import java.util.function.BiConsumer interface DokkaBootstrap { fun configure(logger: BiConsumer<String, String>, serializedConfigurationJSON: String) fun generate() }
integration/src/main/kotlin/org/jetbrains/dokka/DokkaBootstrap.kt
2878711504
package org.tsdes.advanced.rest.newsrestv2.api import io.restassured.RestAssured.delete import io.restassured.RestAssured.given import org.hamcrest.CoreMatchers.equalTo import org.junit.jupiter.api.Test import org.tsdes.advanced.rest.newsrestv2.dto.NewsDto /** * Created by arcuri82 on 01-Aug-17. */ class V2NewRestApiTest : NRTestBase() { @Test fun testCreateAndGetWithNewFormat() { val author = "author" val text = "someText" val country = "Norway" val dto = NewsDto(null, author, text, country, null) //no news given().accept(V2_NEWS_JSON) .get() .then() .statusCode(200) .body("size()", equalTo(0)) //create a news val id = given().contentType(V2_NEWS_JSON) .body(dto) .post() .then() .statusCode(201) .extract().asString() //should be 1 news now given().accept(V2_NEWS_JSON) .get() .then() .statusCode(200) .body("size()", equalTo(1)) //1 news with same data as the POST given().accept(V2_NEWS_JSON) .pathParam("id", id) .get("/{id}") .then() .statusCode(200) .body("newsId", equalTo(id)) .body("authorId", equalTo(author)) .body("text", equalTo(text)) .body("country", equalTo(country)) } @Test fun testDoubleDelete() { val dto = NewsDto(null, "author", "text", "Norway", null) //create a news val id = given().contentType(V2_NEWS_JSON) .body(dto) .post() .then() .statusCode(201) .extract().asString() delete("/$id").then().statusCode(204) //delete again delete("/$id").then().statusCode(404) //note the change from 204 to 404 } }
old/old_news-rest-v2/src/test/kotlin/org/tsdes/advanced/rest/newsrestv2/api/V2NewRestApiTest.kt
1116326671
package org.tsdes.spring.soap.nasdaqwiremock import com.github.tomakehurst.wiremock.WireMockServer import com.github.tomakehurst.wiremock.client.WireMock.* import com.github.tomakehurst.wiremock.common.ConsoleNotifier import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig import org.junit.After import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test /** * Created by arcuri82 on 04-Aug-17. */ class MainTest { private val wiremockPort = 8099 private val server: WireMockServer = WireMockServer( wireMockConfig().port(wiremockPort).notifier(ConsoleNotifier(true)) ) @Before fun initWiremock() { server.start() val body = MainTest::class.java.getResource("/body-v1-NASDAQQuotes.asmx.xml").readText() server.stubFor( post(urlMatching("/v1/NASDAQQuotes.asmx")) .withRequestBody(matching(".*ListMarketCenters.*")) .willReturn(aResponse() .withHeader("Content-Type", "text/xml;charset=utf-8") .withHeader("Content-Length", "${body.length}") .withBody(body) )) } @After fun tearDown() { server.stop() } @Test fun test() { System.setProperty("nasdaqAddress", "localhost:$wiremockPort") assertTrue(Main.names!!.contains("The NASDAQ Stock Market LLC")) assertTrue(Main.names!!.contains("A Mocked Name")) } }
old/old_soap/nasdaq-wiremock/src/test/kotlin/org/tsdes/spring/soap/nasdaqwiremock/MainTest.kt
3927499529
package tornadofx import javafx.beans.InvalidationListener import javafx.beans.property.* import javafx.beans.value.* import javafx.collections.* import javafx.collections.transformation.FilteredList import javafx.collections.transformation.SortedList import javafx.geometry.Insets import javafx.scene.control.ListView import javafx.scene.control.TableView import javafx.scene.input.Clipboard import javafx.scene.input.ClipboardContent import javafx.scene.input.DataFormat import java.io.File import java.util.function.Predicate /** * A wrapper for an observable list of items that can be bound to a list control like TableView, ListView etc. * * The wrapper makes the data sortable and filterable. Configure a filter by setting the * predicate property or by calling filterWhen to automatically update the predicate when * an observable value changes. * ** Usage: * * ```kotlin * val table = TableView<Person>() * val data = SortedFilteredList(persons).bindTo(table) * ``` * * Items can be updated by calling `data.items.setAll` or `data.items.addAll` at a later time. */ @Suppress("UNCHECKED_CAST") class SortedFilteredList<T>( val items: ObservableList<T> = FXCollections.observableArrayList(), initialPredicate: (T) -> Boolean = { true }, val filteredItems: FilteredList<T> = FilteredList(items, initialPredicate), val sortedItems: SortedList<T> = SortedList(filteredItems)) : ObservableList<T> { init { items.onChange { refilter() } } // Should setAll be forwarded to the underlying list? This might be needed for full editing capabilities, // but will affect the ordering of the underlying list var setAllPassThrough = false override val size: Int get() = sortedItems.size override fun contains(element: T) = element in sortedItems override fun containsAll(elements: Collection<T>) = sortedItems.containsAll(elements) override fun get(index: Int) = sortedItems[index] override fun indexOf(element: T) = sortedItems.indexOf(element) override fun isEmpty() = sortedItems.isEmpty() override fun iterator() = sortedItems.iterator() override fun lastIndexOf(element: T) = sortedItems.lastIndexOf(element) override fun add(element: T) = items.add(element) override fun add(index: Int, element: T) { val item = sortedItems[index] val backingIndex = items.indexOf(item) if (backingIndex > -1) { items.add(backingIndex, element) } } override fun addAll(index: Int, elements: Collection<T>): Boolean { val item = sortedItems[index] val backingIndex = items.indexOf(item) if (backingIndex > -1) { return items.addAll(backingIndex, elements) } return false } override fun addAll(elements: Collection<T>) = items.addAll(elements) override fun clear() = items.clear() override fun listIterator() = sortedItems.listIterator() override fun listIterator(index: Int) = sortedItems.listIterator(index) override fun remove(element: T) = items.remove(element) override fun removeAll(elements: Collection<T>) = items.removeAll(elements) override fun removeAt(index: Int): T? { val item = sortedItems[index] val backingIndex = items.indexOf(item) return if (backingIndex > -1) { items.removeAt(backingIndex) } else { null } } override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> { val item = sortedItems[fromIndex] val backingFromIndex = items.indexOf(item) if (backingFromIndex > -1) { return items.subList(backingFromIndex, items.indexOf(sortedItems[toIndex])) } return mutableListOf() } override fun removeAll(vararg elements: T) = items.removeAll(elements) override fun addAll(vararg elements: T) = items.addAll(elements) override fun remove(from: Int, to: Int) { val item = sortedItems[from] val backingFromIndex = items.indexOf(item) if (backingFromIndex > -1) { items.remove(backingFromIndex, items.indexOf(sortedItems[to])) } } override fun retainAll(vararg elements: T) = items.retainAll(elements) override fun retainAll(elements: Collection<T>) = items.retainAll(elements) override fun removeListener(listener: ListChangeListener<in T>?) { sortedItems.removeListener(listener) } override fun removeListener(listener: InvalidationListener?) { sortedItems.removeListener(listener) } override fun addListener(listener: ListChangeListener<in T>?) { sortedItems.addListener(listener) } override fun addListener(listener: InvalidationListener?) { sortedItems.addListener(listener) } override fun setAll(col: MutableCollection<out T>?) = if (setAllPassThrough) items.setAll(col) else false override fun setAll(vararg elements: T) = items.setAll(*elements) /** * Support editing of the sorted/filtered list. Useful to support editing support in ListView/TableView etc */ override fun set(index: Int, element: T): T { val item = sortedItems[index] val backingIndex = items.indexOf(item) if (backingIndex > -1) { items[backingIndex] = element } return item } /** * Force the filtered list to refilter it's items based on the current predicate without having to configure a new predicate. * Avoid reassigning the property value as that would impede binding. */ fun refilter() { val p = predicate if (p != null) { filteredItems.predicate = Predicate { p(it) } } } val predicateProperty: ObjectProperty<(T) -> Boolean> = object : SimpleObjectProperty<(T) -> Boolean>() { override fun set(newValue: ((T) -> Boolean)) { super.set(newValue) filteredItems.predicate = Predicate { newValue(it) } } } var predicate by predicateProperty /** * Bind this data object to the given TableView. * * The `tableView.items` is set to the underlying sortedItems. * * The underlying sortedItems.comparatorProperty` is automatically bound to `tableView.comparatorProperty`. */ fun bindTo(tableView: TableView<T>): SortedFilteredList<T> = apply { tableView.items = this sortedItems.comparatorProperty().bind(tableView.comparatorProperty()) } /** * Bind this data object to the given ListView. * * The `listView.items` is set to the underlying sortedItems. * */ fun bindTo(listView: ListView<T>): SortedFilteredList<T> = apply { listView.items = this } /** * Update the filter predicate whenever the given observable changes. The filter expression * receives both the observable value and the current list item to evaluate. * * Convenient for filtering based on a TextField: * * <pre> * textfield { * promptText = "Filtrering" * data.filterWhen(textProperty(), { query, item -> item.matches(query) } ) * } * </pre> */ fun <Q> filterWhen(observable: ObservableValue<Q>, filterExpr: (Q, T) -> Boolean) { observable.addListener { observableValue, oldValue, newValue -> predicate = { filterExpr(newValue, it) } } } } fun <T> List<T>.observable(): ObservableList<T> = FXCollections.observableList(this) fun <T> Set<T>.observable(): ObservableSet<T> = FXCollections.observableSet(this) fun <K, V> Map<K, V>.observable(): ObservableMap<K, V> = FXCollections.observableMap(this) fun Clipboard.setContent(op: ClipboardContent.() -> Unit) { val content = ClipboardContent() op(content) setContent(content) } fun Clipboard.putString(value: String) = setContent { putString(value) } fun Clipboard.putFiles(files: MutableList<File>) = setContent { putFiles(files) } fun Clipboard.put(dataFormat: DataFormat, value: Any) = setContent { put(dataFormat, value) } inline fun <T> ChangeListener(crossinline listener: (observable: ObservableValue<out T>?, oldValue: T, newValue: T) -> Unit): ChangeListener<T> = javafx.beans.value.ChangeListener<T> { observable, oldValue, newValue -> listener(observable, oldValue, newValue) } /** * Listen for changes to this observable. Optionally only listen x times. * The lambda receives the changed value when the change occurs, which may be null, */ fun <T> ObservableValue<T>.onChangeTimes(times: Int, op: (T?) -> Unit) { var counter = 0 val listener = object : ChangeListener<T> { override fun changed(observable: ObservableValue<out T>?, oldValue: T, newValue: T) { if (++counter == times) { removeListener(this) } op(newValue) } } addListener(listener) } fun <T> ObservableValue<T>.onChangeOnce(op: (T?) -> Unit) = onChangeTimes(1, op) fun <T> ObservableValue<T>.onChange(op: (T?) -> Unit) = apply { addListener { o, oldValue, newValue -> op(newValue) } } fun ObservableBooleanValue.onChange(op: (Boolean) -> Unit) = apply { addListener { o, old, new -> op(new ?: false) } } fun ObservableIntegerValue.onChange(op: (Int) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0).toInt()) } } fun ObservableLongValue.onChange(op: (Long) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0L).toLong()) } } fun ObservableFloatValue.onChange(op: (Float) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0f).toFloat()) } } fun ObservableDoubleValue.onChange(op: (Double) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0.0).toDouble()) } } fun <T> ObservableList<T>.onChange(op: (ListChangeListener.Change<out T>) -> Unit) = apply { addListener(ListChangeListener { op(it) }) } /** * Create a proxy property backed by calculated data based on a specific property. The setter * must return the new value for the backed property. * The scope of the getter and setter will be the receiver property */ fun <R, T> proxyprop(receiver: Property<R>, getter: Property<R>.() -> T, setter: Property<R>.(T) -> R): ObjectProperty<T> = object : SimpleObjectProperty<T>() { init { receiver.onChange { fireValueChangedEvent() } } override fun invalidated() { receiver.value = setter(receiver, super.get()) } override fun get() = getter.invoke(receiver) override fun set(v: T) { receiver.value = setter(receiver, v) super.set(v) } } /** * Create a proxy double property backed by calculated data based on a specific property. The setter * must return the new value for the backed property. * The scope of the getter and setter will be the receiver property */ fun <R> proxypropDouble(receiver: Property<R>, getter: Property<R>.() -> Double, setter: Property<R>.(Double) -> R): DoubleProperty = object : SimpleDoubleProperty() { init { receiver.onChange { fireValueChangedEvent() } } override fun invalidated() { receiver.value = setter(receiver, super.get()) } override fun get() = getter.invoke(receiver) override fun set(v: Double) { receiver.value = setter(receiver, v) super.set(v) } } fun insets(all: Number) = Insets(all.toDouble(), all.toDouble(), all.toDouble(), all.toDouble()) fun insets(horizontal: Number? = null, vertical: Number? = null) = Insets( vertical?.toDouble() ?: 0.0, horizontal?.toDouble() ?: 0.0, vertical?.toDouble() ?: 0.0, horizontal?.toDouble() ?: 0.0 ) fun insets( top: Number? = null, right: Number? = null, bottom: Number? = null, left: Number? = null ) = Insets( top?.toDouble() ?: 0.0, right?.toDouble() ?: 0.0, bottom?.toDouble() ?: 0.0, left?.toDouble() ?: 0.0 ) fun Insets.copy( top: Number? = null, right: Number? = null, bottom: Number? = null, left: Number? = null ) = Insets( top?.toDouble() ?: this.top, right?.toDouble() ?: this.right, bottom?.toDouble() ?: this.bottom, left?.toDouble() ?: this.left ) fun Insets.copy( horizontal: Number? = null, vertical: Number? = null ) = Insets( vertical?.toDouble() ?: this.top, horizontal?.toDouble() ?: this.right, vertical?.toDouble() ?: this.bottom, horizontal?.toDouble() ?: this.left ) val Insets.horizontal get() = (left + right) / 2 val Insets.vertical get() = (top + bottom) / 2 val Insets.all get() = (left + right + top + bottom) / 4 fun String.isLong() = toLongOrNull() != null fun String.isInt() = toIntOrNull() != null fun String.isDouble() = toDoubleOrNull() != null fun String.isFloat() = toFloatOrNull() != null /** * [forEach] with Map.Entree as receiver. */ inline fun <K, V> Map<K, V>.withEach(action: Map.Entry<K, V>.() -> Unit) = forEach(action) /** * [forEach] with the element as receiver. */ inline fun <T> Iterable<T>.withEach(action: T.() -> Unit) = forEach(action) /** * [forEach] with the element as receiver. */ inline fun <T> Sequence<T>.withEach(action: T.() -> Unit) = forEach(action) /** * [forEach] with the element as receiver. */ inline fun <T> Array<T>.withEach(action: T.() -> Unit) = forEach(action) /** * [map] with Map.Entree as receiver. */ inline fun <K, V, R> Map<K, V>.mapEach(action: Map.Entry<K, V>.() -> R) = map(action) /** * [map] with the element as receiver. */ inline fun <T, R> Iterable<T>.mapEach(action: T.() -> R) = map(action) /** * [map] with the element as receiver. */ fun <T, R> Sequence<T>.mapEach(action: T.() -> R) = map(action) /** * [map] with the element as receiver. */ inline fun <T, R> Array<T>.mapEach(action: T.() -> R) = map(action) /** * [mapTo] with Map.Entree as receiver. */ inline fun <K, V, R, C : MutableCollection<in R>> Map<K, V>.mapEachTo(destination: C, action: Map.Entry<K, V>.() -> R) = mapTo(destination, action) /** * [mapTo] with the element as receiver. */ inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapEachTo(destination: C, action: T.() -> R) = mapTo(destination, action) /** * [mapTo] with the element as receiver. */ fun <T, R, C : MutableCollection<in R>> Sequence<T>.mapEachTo(destination: C, action: T.() -> R) = mapTo(destination, action) /** * [mapTo] with the element as receiver. */ fun <T, R, C : MutableCollection<in R>> Array<T>.mapEachTo(destination: C, action: T.() -> R) = mapTo(destination, action)
src/main/java/tornadofx/Lib.kt
282311373
/* * 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.debugger import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import com.intellij.xdebugger.frame.XValueGroup import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.done import org.jetbrains.debugger.values.FunctionValue import org.jetbrains.rpc.LOG import java.util.* internal class FunctionScopesValueGroup(private val functionValue: FunctionValue, private val variableContext: VariableContext) : XValueGroup("Function scopes") { override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) functionValue.resolve() .done(node) { val scopes = it.scopes if (scopes == null || scopes.size == 0) { node.addChildren(XValueChildrenList.EMPTY, true) } else { createAndAddScopeList(node, Arrays.asList(*scopes), variableContext, null) } } .rejected { Promise.logError(LOG, it) node.setErrorMessage(it.message!!) } } }
platform/script-debugger/debugger-ui/src/FunctionScopesValueGroup.kt
1768021575
/* * Copyright 2021, The Querydsl Team (http://www.querydsl.com/team) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.querydsl.kotlin.codegen import com.querydsl.codegen.CodegenModule import com.querydsl.codegen.EntityType import com.querydsl.codegen.GeneratedAnnotationResolver import com.querydsl.codegen.ProjectionSerializer import com.querydsl.codegen.SerializerConfig import com.querydsl.codegen.TypeMappings import com.querydsl.codegen.utils.CodeWriter import com.querydsl.codegen.utils.model.Type import com.querydsl.core.types.ConstructorExpression import com.querydsl.core.types.Expression import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.joinToCode import javax.inject.Inject import javax.inject.Named open class KotlinProjectionSerializer @Inject constructor( private val mappings: TypeMappings, @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) private val generatedAnnotationClass: Class<out Annotation> = GeneratedAnnotationResolver.resolveDefault() ) : ProjectionSerializer { protected open fun intro(model: EntityType): TypeSpec.Builder { val queryType = mappings.getPathClassName(model, model) return TypeSpec.classBuilder(queryType) .superclass(ConstructorExpression::class.parameterizedBy(model)) .addKdoc("${queryType.canonicalName} is a Querydsl Projection type for ${model.simpleName}") .addAnnotation(AnnotationSpec.builder(generatedAnnotationClass).addMember("%S", javaClass.name).build()) .addType(introCompanion(model)) } protected open fun introCompanion(model: EntityType): TypeSpec { return TypeSpec.companionObjectBuilder() .addProperty(PropertySpec.builder("serialVersionUID", Long::class, KModifier.CONST, KModifier.PRIVATE).initializer("%L", model.hashCode()).build()) .build() } protected open fun TypeSpec.Builder.outro(type: EntityType, writer: CodeWriter) { val queryType: Type = mappings.getPathType(type, type, false) FileSpec.builder(queryType.packageName, queryType.simpleName) .addType(build()) .build() .writeTo(writer) } override fun serialize(model: EntityType, serializerConfig: SerializerConfig, writer: CodeWriter) { val builder = intro(model) val sizes: MutableSet<Int> = mutableSetOf() for (c in model.constructors) { val asExpr = sizes.add(c.parameters.size) builder.addFunction( FunSpec.constructorBuilder() .addParameters(c.parameters.map { ParameterSpec.builder( it.name, when { !asExpr -> mappings.getExprType(it.type, model, false, false, true).asTypeName() it.type.isFinal -> Expression::class.parameterizedBy(it.type.asTypeName()) else -> Expression::class.asClassName().parameterizedBy(WildcardTypeName.producerOf(it.type.asTypeName())) } ).build() }) .callSuperConstructor(model.asClassNameStatement(), c.parameters.map { it.type.asClassNameStatement() }.joinToCode(", ", "arrayOf(", ")"), *c.parameters.map { CodeBlock.of("%L", it.name) }.toTypedArray() ) .build() ) } builder.outro(model, writer) } }
querydsl-kotlin-codegen/src/main/kotlin/com/querydsl/kotlin/codegen/KotlinProjectionSerializer.kt
1723554962
package mbc.network.message import org.spongycastle.asn1.* /** * HELLO消息, */ class HelloMessage(val version: Int, val clientId: String, val listenPort: Int, val nodeId: String) : Message { override fun code(): Byte = MessageCodes.HELLO.code override fun encode(): ByteArray { val v = ASN1EncodableVector() v.add(ASN1Integer(version.toLong())) v.add(DERUTF8String(clientId)) v.add(ASN1Integer(listenPort.toLong())) v.add(DERUTF8String(nodeId)) return DERSequence(v).encoded } companion object { fun decode(bytes: ByteArray): HelloMessage? { val v = ASN1InputStream(bytes).readObject() if (v != null) { val seq = ASN1Sequence.getInstance(v) val version = ASN1Integer.getInstance(seq.getObjectAt(0))?.value?.toInt() val clientId = DERUTF8String.getInstance(seq.getObjectAt(1))?.string val listenPort = ASN1Integer.getInstance(seq.getObjectAt(2))?.value?.toInt() val nodeId = DERUTF8String.getInstance(seq.getObjectAt(3))?.string if (version != null && clientId != null && listenPort != null && nodeId != null) { return HelloMessage(version, clientId, listenPort, nodeId) } } return null } } }
src/main/kotlin/mbc/network/message/HelloMessage.kt
715507168
package eu.kanade.tachiyomi.extension.ru.mangaclub import android.net.Uri import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class Mangaclub : ParsedHttpSource() { // Info override val name: String = "MangaClub" override val baseUrl: String = "https://mangaclub.ru" override val lang: String = "ru" override val supportsLatest: Boolean = false override val client: OkHttpClient = network.cloudflareClient // Popular override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/page/$page/", headers) override fun popularMangaNextPageSelector(): String = "a i.icon-right-open" override fun popularMangaSelector(): String = "div.shortstory" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { thumbnail_url = element.select("img").attr("abs:src") element.select(".title > a").apply { title = this.text().substringBefore("/").trim() setUrlWithoutDomain(this.attr("abs:href")) } } // Latest override fun latestUpdatesRequest(page: Int): Request = popularMangaRequest(page) override fun latestUpdatesNextPageSelector(): String = popularMangaNextPageSelector() override fun latestUpdatesSelector(): String = popularMangaSelector() override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) // Search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { if (query.isNotBlank()) { val formBody = FormBody.Builder() .add("do", "search") .add("subaction", "search") .add("search_start", page.toString()) .add("full_search", "0") .add("result_from", ((page - 1) * 8 + 1).toString()) .add("story", query) .build() val searchHeaders = headers.newBuilder().add("Content-Type", "application/x-www-form-urlencoded").build() return POST("$baseUrl/index.php?do=search", searchHeaders, formBody) } val uri = Uri.parse(baseUrl).buildUpon() for (filter in filters) { if (filter is Tag && filter.values[filter.state].isNotEmpty()) { uri.appendEncodedPath("tags/${filter.values[filter.state]}") } } uri.appendPath("page").appendPath(page.toString()) return GET(uri.toString(), headers) } override fun searchMangaNextPageSelector(): String = popularMangaNextPageSelector() override fun searchMangaSelector(): String = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) // Details override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { thumbnail_url = document.select("div.image img").attr("abs:src") title = document.select(".title").text().substringBefore("/").trim() author = document.select("a[href*=author]").text().trim() artist = author status = when (document.select("a[href*=status_translation]")?.first()?.text()) { "Продолжается" -> SManga.ONGOING "Завершен" -> SManga.COMPLETED else -> SManga.UNKNOWN } description = document.select("div.description").text().trim() genre = document.select("div.info a[href*=tags]").joinToString(", ") { it.text() } } // Chapters override fun chapterListSelector(): String = ".chapter-item" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { val link = element.select("a") name = link.text().trim() chapter_number = name.substringAfter("Глава").replace(",", ".").trim().toFloat() setUrlWithoutDomain(link.attr("abs:href")) date_upload = parseDate(element.select(".date").text().trim()) } private fun parseDate(date: String): Long { return SimpleDateFormat("dd.MM.yyyy", Locale.US).parse(date)?.time ?: 0 } // Pages override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply { document.select(".manga-lines-page a").forEach { add(Page(it.attr("data-p").toInt(), "", baseUrl.replace("//", "//img.") + "/" + it.attr("data-i"))) } } override fun imageUrlParse(document: Document): String = throw Exception("imageUrlParse Not Used") // Filters private class Categories(values: Array<Pair<String, String>>) : Filter.Select<String>("Категории", values.map { it.first }.toTypedArray()) private class Tag(values: Array<String>) : Filter.Select<String>("Жанр", values) private class Sort(values: List<Pair<String, String>>) : Filter.Sort( "Сортировать результат поиска", values.map { it.first }.toTypedArray(), Selection(2, false) ) private class Status : Filter.Select<String>( "Статус", arrayOf("", "Завершен", "Продолжается", "Заморожено/Заброшено") ) override fun getFilterList() = FilterList( Filter.Header("NOTE: Filters are ignored if using text search."), Tag(tag) ) private val categoriesArray = arrayOf( Pair("", ""), Pair("Манга", "1"), Pair("Манхва", "2"), Pair("Маньхуа", "3"), Pair("Веб-манхва", "6") ) private val tag = arrayOf( "", "Боевые искусства", "Боевик", "Вампиры", "Гарем", "Гендерная интрига", "Героическое фэнтези", "Додзинси", "Дзёсэй", "Драма", "Детектив", "Игра", "История", "Киберпанк", "Комедия", "Мистика", "Меха", "Махо-сёдзё", "Научная фантастика", "Повседневность", "Приключения", "Психология", "Романтика", "Самурайский боевик", "Сверхъестественное", "Сёдзё", "Сёдзё для взрослых", "Сёдзё-ай", "Сёнэн", "Сёнэн-ай", "Спокон", "Сэйнэн", "Спорт", "Трагедия", "Триллер", "Ужасы", "Фантастика", "Фэнтези", "Школа", "Эротика", "Этти", "Юри", "Яой" ) private val sortables = listOf( Pair("По заголовку", "title"), Pair("По количеству комментариев", "comm_num"), Pair("По количеству просмотров", "news_read"), Pair("По имени автора", "autor"), Pair("По рейтингу", "rating") ) }
src/ru/mangaclub/src/eu/kanade/tachiyomi/extension/ru/mangaclub/Mangaclub.kt
3384585292
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.log /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ internal object Param { const val ACHIEVEMENT_ID = "achievement_id" const val CHARACTER = "character" const val TRAVEL_CLASS = "travel_class" const val CONTENT_TYPE = "content_type" const val CURRENCY = "currency" const val COUPON = "coupon" const val START_DATE = "start_date" const val END_DATE = "end_date" const val FLIGHT_NUMBER = "flight_number" const val GROUP_ID = "group_id" const val ITEM_CATEGORY = "item_category" const val ITEM_ID = "item_id" const val ITEM_LOCATION_ID = "item_location_id" const val ITEM_NAME = "item_name" const val LOCATION = "location" const val LEVEL = "level" const val LEVEL_NAME = "level_name" const val METHOD = "method" const val NUMBER_OF_NIGHTS = "number_of_nights" const val NUMBER_OF_PASSENGERS = "number_of_passengers" const val NUMBER_OF_ROOMS = "number_of_rooms" const val DESTINATION = "destination" const val ORIGIN = "origin" const val PRICE = "price" const val QUANTITY = "quantity" const val SCORE = "score" const val SHIPPING = "shipping" const val TRANSACTION_ID = "transaction_id" const val SEARCH_TERM = "search_term" const val SUCCESS = "success" const val TAX = "tax" const val VALUE = "value" const val VIRTUAL_CURRENCY_NAME = "virtual_currency_name" const val CAMPAIGN = "campaign" const val SOURCE = "source" const val MEDIUM = "medium" const val TERM = "term" const val CONTENT = "content" const val ACLID = "aclid" const val CP1 = "cp1" const val ITEM_BRAND = "item_brand" const val ITEM_VARIANT = "item_variant" const val ITEM_LIST = "item_list" const val CHECKOUT_STEP = "checkout_step" const val CHECKOUT_OPTION = "checkout_option" const val CREATIVE_NAME = "creative_name" const val CREATIVE_SLOT = "creative_slot" const val AFFILIATION = "affiliation" const val INDEX = "index" }
mobile/src/main/java/net/mm2d/dmsexplorer/log/Param.kt
2038544390
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016 Vimeo * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vimeo.stag.processor.dummy class DummyMapClass : MutableMap<Any, Any> { override val size: Int get() = 0 override fun containsKey(key: Any) = false override fun containsValue(value: Any) = false override fun get(key: Any): Any? = null override fun isEmpty() = true override val entries: MutableSet<MutableMap.MutableEntry<Any, Any>> get() = mutableSetOf() override val keys: MutableSet<Any> get() = mutableSetOf() override val values: MutableCollection<Any> get() = mutableListOf() override fun clear() {} override fun put(key: Any, value: Any): Nothing? = null override fun putAll(from: Map<out Any, Any>) {} override fun remove(key: Any): Nothing? = null }
stag-library-compiler/src/test/java/com/vimeo/stag/processor/dummy/DummyMapClass.kt
20407343
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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.sonar.plsqlopen.symbols import com.felipebz.flr.api.AstNode import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.symbols.Scope import org.sonar.plugins.plsqlopen.api.symbols.Symbol import java.util.* class ScopeImpl(private val outer: Scope?, private val node: AstNode, override val isAutonomousTransaction: Boolean = false, private val hasExceptionHandler: Boolean = false, override val isOverridingMember: Boolean = false) : Scope { private var identifier: String? = null override val symbols = mutableListOf<Symbol>() override fun tree() = node override fun outer() = outer override fun identifier(): String? { if (identifier == null) { identifier = "" val identifierNode = node.getFirstChildOrNull(PlSqlGrammar.IDENTIFIER_NAME, PlSqlGrammar.UNIT_NAME) if (identifierNode != null) { this.identifier = identifierNode.tokenOriginalValue } } return identifier } override fun hasExceptionHandler() = hasExceptionHandler /** * @param kind of the symbols to look for * @return the symbols corresponding to the given kind */ override fun getSymbols(kind: Symbol.Kind) = symbols.filter { it.`is`(kind) }.toList() override fun getSymbolsAcessibleInScope(name: String, vararg kinds: Symbol.Kind): Deque<Symbol> { val result = ArrayDeque<Symbol>() var scope: Scope? = this while (scope != null) { scope.symbols.filterTo(result) { it.called(name) && (kinds.isEmpty() || kinds.contains(it.kind())) } scope = scope.outer() } return result } override fun addSymbol(symbol: Symbol) { symbols.add(symbol) } override fun getSymbol(name: String, vararg kinds: Symbol.Kind): Symbol? { var scope: Scope? = this while (scope != null) { for (s in scope.symbols) { if (s.called(name) && (kinds.isEmpty() || kinds.contains(s.kind()))) { return s } } scope = scope.outer() } return null } }
zpa-core/src/main/kotlin/org/sonar/plsqlopen/symbols/ScopeImpl.kt
3517191583
/* * Copyright 2016 Shinya Mochida * * Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.runner import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.util.* import java.util.jar.JarFile interface ClassPath { fun listClasses(): List<ClassFile> } data class FileClassPath(val path: String): ClassPath { override fun listClasses(): List<ClassFile> { val path = Paths.get(path) if (Files.exists(path) == false) return emptyList() Files.walkFileTree(path, visitor) return visitor.list().map { it.toString() } .map { RealClassFile(path, it) } } interface DirectoryScanner: FileVisitor<Path> { fun list(): List<Path> } val visitor: DirectoryScanner = object: SimpleFileVisitor<Path>(), DirectoryScanner { val list = mutableListOf<Path>() override fun list(): List<Path> { return list.toList() } override fun visitFile(file: Path?, attrs: BasicFileAttributes?): FileVisitResult? { if (file != null) list.add(file) return FileVisitResult.CONTINUE } } } data class JarClassPath(val path: String): ClassPath { companion object { val KOTLIN = listOf("/kotlin-stdlib/", "/kotlin-runtime/", "/kotlin-reflect/") } override fun listClasses(): List<ClassFile> { val kotlinLib = KOTLIN.filter { path.contains(it) }.size > 0 if (kotlinLib) return emptyList() val jarFile = JarFile(path) return Collections.list(jarFile.entries()).filter { !it.isDirectory } .filter { it.name.startsWith("META-INF") == false } .map{ it.name } .map(::ZipClassFile) } }
core/src/main/kotlin/org/mikeneck/kuickcheck/runner/ClassPath.kt
3738077860