content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package util.undo import util.Entity interface UndoProvider { suspend fun <T : Entity<T>, F> undoableSave(original: T?, replacementWithID: T, function: suspend () -> F): F { val isUpdate = original?.id != null val pastTenseDescription = if (isUpdate) "Updated $original" else "Added $replacementWithID" val undoPastTenseDescription = if (isUpdate) "Reverted $original" else "Deleted $replacementWithID" return undoable(pastTenseDescription, undoPastTenseDescription, function) } suspend fun <T> undoable(pastTenseDescription: String, undoPastTenseDescription: String, function: suspend () -> T): T suspend fun <T> notUndoable(function: suspend () -> T): T companion object { val empty: UndoProvider = object : UndoProvider { override suspend fun <T> undoable(pastTenseDescription: String, undoPastTenseDescription: String, function: suspend () -> T): T { return function() } override suspend fun <T> notUndoable(function: suspend () -> T): T { return function() } } } }
src/commonMain/kotlin/util/undo/UndoProvider.kt
1854123971
/* * Copyright (C) 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 com.example.android.trackr.ui.edit import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment import androidx.hilt.navigation.fragment.hiltNavGraphViewModels import com.example.android.trackr.R import com.google.android.material.dialog.MaterialAlertDialogBuilder class UserSelectionDialogFragment : DialogFragment() { private val viewModel: TaskEditViewModel by hiltNavGraphViewModels(R.id.nav_task_edit_graph) override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val users = viewModel.users return MaterialAlertDialogBuilder(requireContext()) .setItems(users.map { it.username }.toTypedArray()) { _, which -> viewModel.updateOwner(users[which]) } .create() } }
app/src/main/java/com/example/android/trackr/ui/edit/UserSelectionDialogFragment.kt
255879032
package be.vergauwen.simon.androidretaindata.core.rx import rx.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class RxTransformers : Transformers { override fun <T> applyComputationSchedulers(): Observable.Transformer<T, T> = Observable.Transformer<T, T> { it.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) } override fun <T> applyIOSchedulers(): Observable.Transformer<T, T> = Observable.Transformer<T, T> { it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun <T> applyIOSingleSchedulers(): Single.Transformer<T, T> = Single.Transformer<T, T> { it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun <T> applyComputationSingleSchedulers(): Single.Transformer<T, T> = Single.Transformer<T, T> { it.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) } override fun applyIOCompletableSchedulers(): Completable.CompletableTransformer = Completable.CompletableTransformer { it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun applyComputationCompletableSchedulers(): Completable.CompletableTransformer = Completable.CompletableTransformer { it.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) } }
sample/app/src/main/kotlin/be/vergauwen/simon/androidretaindata/core/rx/RxTransformers.kt
1552173869
package fr.corenting.edcompanion.fragments import androidx.fragment.app.activityViewModels import fr.corenting.edcompanion.adapters.CommanderFleetAdapter import fr.corenting.edcompanion.models.exceptions.DataNotInitializedException import fr.corenting.edcompanion.models.exceptions.FrontierAuthNeededException import fr.corenting.edcompanion.utils.NotificationsUtils import fr.corenting.edcompanion.view_models.CommanderViewModel class CommanderFleetFragment : AbstractListFragment<CommanderFleetAdapter>() { private val viewModel: CommanderViewModel by activityViewModels() override fun getNewRecyclerViewAdapter(): CommanderFleetAdapter { return CommanderFleetAdapter(context) } override fun getData() { viewModel.getFleet().observe(viewLifecycleOwner, { result -> endLoading(false) if (result?.data == null || result.error != null) { // For frontier auth error there will be a popup displayed by the other fragment anyway if (result.error !is FrontierAuthNeededException && result.error !is DataNotInitializedException) { NotificationsUtils.displayGenericDownloadErrorSnackbar(activity) } } else { recyclerViewAdapter.submitList(result.data.ships) } }) viewModel.fetchFleet() } override fun needEventBus(): Boolean { return false } companion object { const val COMMANDER_FLEET_FRAGMENT_TAG = "commander_fleet_fragment" } }
app/src/main/java/fr/corenting/edcompanion/fragments/CommanderFleetFragment.kt
2699765097
package net.serverpeon.twitcharchiver.hls import com.google.common.collect.ImmutableList import java.math.BigInteger import java.net.URI import java.time.Duration import java.time.ZonedDateTime import java.util.concurrent.TimeUnit /** * [http://tools.ietf.org/html/draft-pantos-http-live-streaming-08] */ object OfficialTags { /** * An Extended M3U file is distinguished from a basic M3U file by its * first line, which MUST be the tag #EXTM3U. */ val EXTM3U: HlsTag<Nothing> = HlsTag( "EXTM3U", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, hasAttributes = false, required = true, unique = true ) /** * The EXTINF tag specifies the duration of a media segment. It applies * only to the media URI that follows it. Each media segment URI MUST * be preceded by an EXTINF tag. Its format is: * * #EXTINF:<duration>,<title> * * "duration" is an integer or floating-point number in decimal * positional notation that specifies the duration of the media segment * in seconds. Durations that are reported as integers SHOULD be * rounded to the nearest integer. Durations MUST be integers if the * protocol version of the Playlist file is less than 3. The remainder * of the line following the comma is an optional human-readable * informative title of the media segment. */ val EXTINF: HlsTag<SegmentInformation> = HlsTag( "EXTINF", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, required = true, unique = true ) { rawData -> val data = rawData.split(',', limit = 2) SegmentInformation(data[0].toDuration(), if (data.size == 2) data[1] else "") } /** * The EXT-X-BYTERANGE tag indicates that a media segment is a sub-range * of the resource identified by its media URI. It applies only to the * next media URI that follows it in the Playlist. Its format is: * * #EXT-X-BYTERANGE:<n>[@o] * * where n is a decimal-integer indicating the length of the sub-range * in bytes. If present, o is a decimal-integer indicating the start of * the sub-range, as a byte offset from the beginning of the resource. * If o is not present, the sub-range begins at the next byte following * the sub-range of the previous media segment. * * If o is not present, a previous media segment MUST appear in the * Playlist file and MUST be a sub-range of the same media resource. * * A media URI with no EXT-X-BYTERANGE tag applied to it specifies a * media segment that consists of the entire resource. * * The EXT-X-BYTERANGE tag appeared in version 4 of the protocol. */ val EXT_X_BYTERANGE: HlsTag<SourceSubrange> = HlsTag( "EXT-X-BYTERANGE", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, unique = true ) { rawData -> val data = rawData.split('@', limit = 2) SourceSubrange(data[0].toLong(), if (data.size == 2) data[1].toLong() else 0) } /** * The EXT-X-TARGETDURATION tag specifies the maximum media segment * duration. The EXTINF duration of each media segment in the Playlist * file MUST be less than or equal to the target duration. This tag * MUST appear once in the Playlist file. It applies to the entire * Playlist file. Its format is: * * #EXT-X-TARGETDURATION:<s> * * where s is an integer indicating the target duration in seconds. */ val EXT_X_TARGETDURATION: HlsTag<Duration> = HlsTag( "EXT-X-TARGETDURATION", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, required = true, unique = true ) { rawData -> Duration.ofSeconds(rawData.toLong()) } /** * Each media URI in a Playlist has a unique integer sequence number. * The sequence number of a URI is equal to the sequence number of the * URI that preceded it plus one. The EXT-X-MEDIA-SEQUENCE tag * indicates the sequence number of the first URI that appears in a * Playlist file. Its format is: * * #EXT-X-MEDIA-SEQUENCE:<number> * * A Playlist file MUST NOT contain more than one EXT-X-MEDIA-SEQUENCE * tag. If the Playlist file does not contain an EXT-X-MEDIA-SEQUENCE * tag then the sequence number of the first URI in the playlist SHALL * be considered to be 0. * * A media URI is not required to contain its sequence number. * * See Section 6.3.2 and Section 6.3.5 for information on handling the * EXT-X-MEDIA-SEQUENCE tag. */ val EXT_X_MEDIA_SEQUENCE: HlsTag<Int> = HlsTag( "EXT-X-MEDIA-SEQUENCE", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, unique = true ) { rawData -> rawData.toInt() } /** * Media segments MAY be encrypted. The EXT-X-KEY tag specifies how to * decrypt them. It applies to every media URI that appears between it * and the next EXT-X-KEY tag in the Playlist file (if any). Its format * is: * * #EXT-X-KEY:<attribute-list> * * The following attributes are defined: * * The METHOD attribute specifies the encryption method. It is of type * enumerated-string. Each EXT-X-KEY tag MUST contain a METHOD * attribute. * * Two methods are defined: NONE and AES-128. * * An encryption method of NONE means that media segments are not * encrypted. If the encryption method is NONE, the URI and the IV * attributes MUST NOT be present. * * An encryption method of AES-128 means that media segments are * encrypted using the Advanced Encryption Standard [AES_128] with a * 128-bit key and PKCS7 padding [RFC5652]. If the encryption method is * AES-128, the URI attribute MUST be present. The IV attribute MAY be * present; see Section 5.2. * * The URI attribute specifies how to obtain the key. Its value is a * quoted-string that contains a URI [RFC3986] for the key. * * The IV attribute, if present, specifies the Initialization Vector to * be used with the key. Its value is a hexadecimal-integer. The IV * attribute appeared in protocol version 2. * * If the Playlist file does not contain an EXT-X-KEY tag then media * segments are not encrypted. * * See Section 5 for the format of the key file, and Section 5.2, * Section 6.2.3 and Section 6.3.6 for additional information on media * segment encryption. */ val EXT_X_KEY: HlsTag<EncryptionKey?> = HlsTag( "EXT-X-KEY", appliesTo = HlsTag.AppliesTo.FOLLOWING_SEGMENTS ) { rawData -> val parser = AttributeListParser(rawData) var uri: URI? = null var iv: BigInteger? = null var method: String = "NONE" while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "URI" -> uri = URI.create(parser.readQuotedString()) "IV" -> iv = parser.readHexadecimalInt() "METHOD" -> method = parser.readEnumeratedString() } } if (!"NONE".equals(method)) EncryptionKey(method, uri!!, iv) else null } /** * The EXT-X-PROGRAM-DATE-TIME tag associates the first sample of a * media segment with an absolute date and/or time. It applies only to * the next media URI. * * The date/time representation is ISO/IEC 8601:2004 [ISO_8601] and * SHOULD indicate a time zone: * * #EXT-X-PROGRAM-DATE-TIME:<YYYY-MM-DDThh:mm:ssZ> * * For example: * * #EXT-X-PROGRAM-DATE-TIME:2010-02-19T14:54:23.031+08:00 * * See Section 6.2.1 and Section 6.3.3 for more information on the EXT- * X-PROGRAM-DATE-TIME tag. */ val EXT_X_PROGRAM_DATE_TIME: HlsTag<ZonedDateTime> = HlsTag( "EXT-X-PROGRAM-DATE-TIME", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, unique = true ) { rawData -> ZonedDateTime.parse(rawData) } /** * The EXT-X-ALLOW-CACHE tag indicates whether the client MAY or MUST * NOT cache downloaded media segments for later replay. It MAY occur * anywhere in the Playlist file; it MUST NOT occur more than once. The * EXT-X-ALLOW-CACHE tag applies to all segments in the playlist. Its * format is: * * #EXT-X-ALLOW-CACHE:<YES|NO> * * See Section 6.3.3 for more information on the EXT-X-ALLOW-CACHE tag. */ val EXT_X_ALLOW_CACHE: HlsTag<Boolean> = HlsTag( "EXT-X-ALLOW-CACHE", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, unique = true ) { rawData -> readYesNo(rawData) } /** * The EXT-X-PLAYLIST-TYPE tag provides mutability information about the * Playlist file. It applies to the entire Playlist file. It is * optional. Its format is: * * #EXT-X-PLAYLIST-TYPE:<EVENT|VOD> * * Section 6.2.1 defines the implications of the EXT-X-PLAYLIST-TYPE * tag. */ val EXT_X_PLAYLIST_TYPE: HlsTag<PlaylistType> = HlsTag( "EXT-X-PLAYLIST-TYPE", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, unique = true ) { rawData -> when (rawData) { "EVENT" -> PlaylistType.EVENT "VOD" -> PlaylistType.VOD else -> throw IllegalArgumentException("Invalid value for EXT-X-PLAYLIST-TYPE: $rawData") } } /** * The EXT-X-ENDLIST tag indicates that no more media segments will be * added to the Playlist file. It MAY occur anywhere in the Playlist * file; it MUST NOT occur more than once. Its format is: * * #EXT-X-ENDLIST */ val EXT_X_ENDLIST: HlsTag<Nothing> = HlsTag( "EXT-X-ENDLIST", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, hasAttributes = false, unique = true ) /** * The EXT-X-MEDIA tag is used to relate Playlists that contain * alternative renditions of the same content. For example, three EXT- * X-MEDIA tags can be used to identify audio-only Playlists that * contain English, French and Spanish renditions of the same * presentation. Or two EXT-X-MEDIA tags can be used to identify video- * only Playlists that show two different camera angles. * * The EXT-X-MEDIA tag stands alone, in that it does not apply to a * particular URI in the Playlist. Its format is: * * #EXT-X-MEDIA:<attribute-list> * * The following attributes are defined: * * URI * * The value is a quoted-string containing a URI that identifies the * Playlist file. This attribute is optional; see Section 3.4.10.1. * * TYPE * * The value is enumerated-string; valid strings are AUDIO and VIDEO. * If the value is AUDIO, the Playlist described by the tag MUST contain * audio media. If the value is VIDEO, the Playlist MUST contain video * media. * * GROUP-ID * * The value is a quoted-string identifying a mutually-exclusive group * of renditions. The presence of this attribute signals membership in * the group. See Section 3.4.9.1. * * LANGUAGE * * The value is a quoted-string containing an RFC 5646 [RFC5646] * language tag that identifies the primary language used in the * rendition. This attribute is optional. * * NAME * * The value is a quoted-string containing a human-readable description * of the rendition. If the LANGUAGE attribute is present then this * description SHOULD be in that language. * * DEFAULT * * The value is enumerated-string; valid strings are YES and NO. If the * value is YES, then the client SHOULD play this rendition of the * content in the absence of information from the user indicating a * different choice. This attribute is optional. Its absence indicates * an implicit value of NO. * * AUTOSELECT * * The value is enumerated-string; valid strings are YES and NO. This * attribute is optional. Its absence indicates an implicit value of * NO. If the value is YES, then the client MAY choose to play this * rendition in the absence of explicit user preference because it * matches the current playback environment, such as chosen system * language. * * The EXT-X-MEDIA tag appeared in version 4 of the protocol. */ val EXT_X_MEDIA: HlsTag<MediaRendition> = HlsTag( "EXT-X-MEDIA", appliesTo = HlsTag.AppliesTo.ADDITIONAL_DATA ) { rawData -> val parser = AttributeListParser(rawData) var type: String? = null var uri: URI? = null var group: String? = null var language: String? = null var name: String? = null var default: Boolean = false var autoSelect: Boolean = false while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "URI" -> uri = URI.create(parser.readQuotedString()) "TYPE" -> type = parser.readEnumeratedString() "GROUP-ID" -> group = parser.readQuotedString() "LANGUAGE" -> language = parser.readQuotedString() "NAME" -> name = parser.readQuotedString() "DEFAULT" -> default = readYesNo(parser.readEnumeratedString()) "AUTOSELECT" -> autoSelect = readYesNo(parser.readEnumeratedString()) } } MediaRendition(when (type) { "VIDEO" -> MediaType.VIDEO "AUDIO" -> MediaType.AUDIO else -> throw IllegalStateException("invalid MediaType: $type") }, uri, group, language, name, default, autoSelect) } /** * The EXT-X-STREAM-INF tag identifies a media URI as a Playlist file * containing a multimedia presentation and provides information about * that presentation. It applies only to the URI that follows it. Its * format is: * * #EXT-X-STREAM-INF:<attribute-list> * <URI> * * The following attributes are defined: * * BANDWIDTH * * The value is a decimal-integer of bits per second. It MUST be an * upper bound of the overall bitrate of each media segment (calculated * to include container overhead) that appears or will appear in the * Playlist. * * Every EXT-X-STREAM-INF tag MUST include the BANDWIDTH attribute. * * PROGRAM-ID * * The value is a decimal-integer that uniquely identifies a particular * presentation within the scope of the Playlist file. * A Playlist file MAY contain multiple EXT-X-STREAM-INF tags with the * same PROGRAM-ID to identify different encodings of the same * presentation. These variant playlists MAY contain additional EXT-X- * STREAM-INF tags. * * CODECS * * The value is a quoted-string containing a comma-separated list of * formats, where each format specifies a media sample type that is * present in a media segment in the Playlist file. Valid format * identifiers are those in the ISO File Format Name Space defined by * RFC 6381 [RFC6381]. * * Every EXT-X-STREAM-INF tag SHOULD include a CODECS attribute. * * RESOLUTION * * The value is a decimal-resolution describing the approximate encoded * horizontal and vertical resolution of video within the presentation. * * AUDIO * * The value is a quoted-string. It MUST match the value of the * GROUP-ID attribute of an EXT-X-MEDIA tag elsewhere in the Playlist * whose TYPE attribute is AUDIO. It indicates the set of audio * renditions that MAY be used when playing the presentation. See * Section 3.4.10.1. * * VIDEO * * The value is a quoted-string. It MUST match the value of the * GROUP-ID attribute of an EXT-X-MEDIA tag elsewhere in the Playlist * whose TYPE attribute is VIDEO. It indicates the set of video * renditions that MAY be used when playing the presentation. See * Section 3.4.10.1. */ val EXT_X_STREAM_INF: HlsTag<StreamInformation> = HlsTag( "EXT-X-STREAM-INF", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, unique = true ) { rawData -> val parser = AttributeListParser(rawData) var bandwidth: Long? = null var programId: Long? = null var codecs: String? = null var resolution: AttributeListParser.Resolution? = null var audio: String? = null var video: String? = null while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "BANDWIDTH" -> bandwidth = parser.readDecimalInt() "PROGRAM-ID" -> programId = parser.readDecimalInt() "CODECS" -> codecs = parser.readQuotedString() "RESOLUTION" -> resolution = parser.readResolution() "AUDIO" -> audio = parser.readQuotedString() "VIDEO" -> video = parser.readQuotedString() } } StreamInformation( bandwidth!!, programId, codecs?.let { ImmutableList.copyOf(it.split(',')) } ?: ImmutableList.of(), resolution, audio, video ) } /** * The EXT-X-DISCONTINUITY tag indicates an encoding discontinuity * between the media segment that follows it and the one that preceded * it. The set of characteristics that MAY change is: * * o file format * * o number and type of tracks * * o encoding parameters * * o encoding sequence * * o timestamp sequence * * Its format is: * * #EXT-X-DISCONTINUITY * * See Section 4, Section 6.2.1, and Section 6.3.3 for more information * about the EXT-X-DISCONTINUITY tag. */ val EXT_X_DISCONTINUITY: HlsTag<Nothing> = HlsTag( "EXT-X-DISCONTINUITY", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, hasAttributes = false ) /** * The EXT-X-I-FRAMES-ONLY tag indicates that each media segment in the * Playlist describes a single I-frame. I-frames (or Intra frames) are * encoded video frames whose encoding does not depend on any other * frame. * * The EXT-X-I-FRAMES-ONLY tag applies to the entire Playlist. Its * format is: * * #EXT-X-I-FRAMES-ONLY * * In a Playlist with the EXT-X-I-FRAMES-ONLY tag, the media segment * duration (EXTINF tag value) is the time between the presentation time * of the I-frame in the media segment and the presentation time of the * next I-frame in the Playlist, or the end of the presentation if it is * the last I-frame in the Playlist. * * Media resources containing I-frame segments MUST begin with a * Transport Stream PAT/PMT. The byte range of an I-frame segment with * an EXT-X-BYTERANGE tag applied to it (Section 3.4.1) MUST NOT include * a PAT/PMT. * * The EXT-X-I-FRAMES-ONLY tag appeared in version 4 of the protocol. */ val EXT_X_I_FRAMES_ONLY: HlsTag<Nothing> = HlsTag( "EXT-X-I-FRAMES-ONLY", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, hasAttributes = false ) /** * The EXT-X-I-FRAME-STREAM-INF tag identifies a Playlist file * containing the I-frames of a multimedia presentation. It stands * alone, in that it does not apply to a particular URI in the Playlist. * Its format is: * * #EXT-X-I-FRAME-STREAM-INF:<attribute-list> * * All attributes defined for the EXT-X-STREAM-INF tag (Section 3.4.10) * are also defined for the EXT-X-I-FRAME-STREAM-INF tag, except for the * AUDIO attribute. In addition, the following attribute is defined: * * URI * * The value is a quoted-string containing a URI that identifies the * I-frame Playlist file. * * Every EXT-X-I-FRAME-STREAM-INF tag MUST include a BANDWIDTH attribute * and a URI attribute. * * The provisions in Section 3.4.10.1 also apply to EXT-X-I-FRAME- * STREAM-INF tags with a VIDEO attribute. * * A Playlist that specifies alternative VIDEO renditions and I-frame * Playlists SHOULD include an alternative I-frame VIDEO rendition for * each regular VIDEO rendition, with the same NAME and LANGUAGE * attributes. * * The EXT-X-I-FRAME-STREAM-INF tag appeared in version 4 of the * protocol. Clients that do not implement protocol version 4 or higher * MUST ignore it. */ val EXT_X_I_FRAME_STREAM_INF: HlsTag<Any> = HlsTag( "EXT-X-I-FRAME-STREAM-INF", appliesTo = HlsTag.AppliesTo.ADDITIONAL_DATA ) { rawData -> val parser = AttributeListParser(rawData) var bandwidth: Long? = null var programId: Long? = null var codecs: String? = null var resolution: AttributeListParser.Resolution? = null var video: String? = null var uri: URI? = null while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "BANDWIDTH" -> bandwidth = parser.readDecimalInt() "PROGRAM-ID" -> programId = parser.readDecimalInt() "CODECS" -> codecs = parser.readQuotedString() "RESOLUTION" -> resolution = parser.readResolution() "VIDEO" -> video = parser.readQuotedString() "URI" -> uri = URI.create(parser.readQuotedString()) } } IFrameStreamInformation( bandwidth!!, programId, codecs?.let { ImmutableList.copyOf(it.split(',')) } ?: ImmutableList.of(), resolution, video, uri!! ) } /** * The EXT-X-VERSION tag indicates the compatibility version of the * Playlist file. The Playlist file, its associated media, and its * server MUST comply with all provisions of the most-recent version of * this document describing the protocol version indicated by the tag * value. * * The EXT-X-VERSION tag applies to the entire Playlist file. Its * format is: * * #EXT-X-VERSION:<n> * * where n is an integer indicating the protocol version. * * A Playlist file MUST NOT contain more than one EXT-X-VERSION tag. A * Playlist file that does not contain an EXT-X-VERSION tag MUST comply * with version 1 of this protocol. */ val EXT_X_VERSION: HlsTag<Int> = HlsTag( "EXT-X-VERSION", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, required = true, unique = false ) { rawData -> rawData.toInt() } data class SegmentInformation(val duration: Duration, val title: String) data class SourceSubrange(val length: Long, val offset: Long) data class EncryptionKey(val method: String, val uri: URI, val iv: BigInteger?) data class MediaRendition( val type: MediaType, val uri: URI?, val group: String?, val language: String?, val name: String?, val default: Boolean, val autoSelect: Boolean ) data class StreamInformation( val bandwidth: Long, val programId: Long?, val codecs: List<String>, val resolution: AttributeListParser.Resolution?, val audio: String?, val video: String? ) data class IFrameStreamInformation( val bandwidth: Long, val programId: Long?, val codecs: List<String>, val resolution: AttributeListParser.Resolution?, val video: String?, val uri: URI ) enum class PlaylistType { EVENT, VOD } enum class MediaType { VIDEO, AUDIO, } private fun readYesNo(input: String): Boolean { return when (input) { "YES" -> true "NO" -> false else -> throw IllegalArgumentException("Invalid value for YES/NO: $input") } } fun CharSequence.toDuration(): Duration { val parts = this.split('.', limit = 2) return Duration.ofSeconds(parts[0].toLong(), if (parts.size == 2) TimeUnit.MILLISECONDS.toNanos(parts[1].toLong()) else 0) } }
hls-parser/src/main/kotlin/net/serverpeon/twitcharchiver/hls/OfficialTags.kt
3994237607
package org.wordpress.android.fluxc.model import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.FRIDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.MONDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.SATURDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.SUNDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.THURSDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.TUESDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.WEDNESDAY import org.wordpress.android.fluxc.persistence.BloggingRemindersDao.BloggingReminders import javax.inject.Inject class BloggingRemindersMapper @Inject constructor() { fun toDatabaseModel(domainModel: BloggingRemindersModel): BloggingReminders = with(domainModel) { return BloggingReminders( localSiteId = this.siteId, monday = enabledDays.contains(MONDAY), tuesday = enabledDays.contains(TUESDAY), wednesday = enabledDays.contains(WEDNESDAY), thursday = enabledDays.contains(THURSDAY), friday = enabledDays.contains(FRIDAY), saturday = enabledDays.contains(SATURDAY), sunday = enabledDays.contains(SUNDAY), hour = this.hour, minute = this.minute, isPromptRemindersOptedIn = domainModel.isPromptIncluded ) } fun toDomainModel(databaseModel: BloggingReminders): BloggingRemindersModel = with(databaseModel) { return BloggingRemindersModel( siteId = localSiteId, enabledDays = mutableSetOf<Day>().let { list -> if (monday) list.add(MONDAY) if (tuesday) list.add(TUESDAY) if (wednesday) list.add(WEDNESDAY) if (thursday) list.add(THURSDAY) if (friday) list.add(FRIDAY) if (saturday) list.add(SATURDAY) if (sunday) list.add(SUNDAY) list }, hour = hour, minute = minute, isPromptIncluded = isPromptRemindersOptedIn ) } }
fluxc/src/main/java/org/wordpress/android/fluxc/model/BloggingRemindersMapper.kt
3769398874
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.containers.ContainerUtil abstract class ScriptManagerBaseEx<SCRIPT : ScriptBase> : ScriptManagerBase<SCRIPT>() { protected val idToScript = ContainerUtil.newConcurrentMap<String, SCRIPT>() override final fun forEachScript(scriptProcessor: (Script) -> Boolean) { for (script in idToScript.values) { if (!scriptProcessor(script)) { return } } } override final fun findScriptById(id: String) = idToScript[id] fun clear(listener: DebugEventListener) { idToScript.clear() listener.scriptsCleared() } override final fun findScriptByUrl(rawUrl: String) = findScriptByUrl(rawUrlToOurUrl(rawUrl)) override final fun findScriptByUrl(url: Url): SCRIPT? { for (script in idToScript.values) { if (url.equalsIgnoreParameters(script.url)) { return script } } return null } open fun rawUrlToOurUrl(rawUrl: String) = Urls.parseEncoded(rawUrl)!! }
platform/script-debugger/backend/src/debugger/ScriptManagerBaseEx.kt
3417104256
/* * Copyright 2020 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.artifact.view import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.longClick import androidx.test.espresso.action.ViewActions.scrollTo import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.intent.Intents.intended import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction import androidx.test.espresso.intent.matcher.IntentMatchers.hasData import androidx.test.espresso.intent.matcher.IntentMatchers.hasType import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withParent import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.GrantPermissionRule import com.azimolabs.conditionwatcher.ConditionWatcher import com.azimolabs.conditionwatcher.Instruction import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.TeamCityApplication import com.github.vase4kin.teamcityapp.api.TeamCityService import com.github.vase4kin.teamcityapp.artifact.api.File import com.github.vase4kin.teamcityapp.artifact.api.Files import com.github.vase4kin.teamcityapp.base.extractor.BundleExtractorValues import com.github.vase4kin.teamcityapp.build_details.view.BuildDetailsActivity import com.github.vase4kin.teamcityapp.buildlist.api.Build import com.github.vase4kin.teamcityapp.dagger.components.AppComponent import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent import com.github.vase4kin.teamcityapp.dagger.modules.AppModule import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl import com.github.vase4kin.teamcityapp.dagger.modules.Mocks import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule import com.github.vase4kin.teamcityapp.helper.CustomIntentsTestRule import com.github.vase4kin.teamcityapp.helper.RecyclerViewMatcher.Companion.withRecyclerView import com.github.vase4kin.teamcityapp.helper.TestUtils import com.github.vase4kin.teamcityapp.helper.TestUtils.Companion.hasItemsCount import io.reactivex.Single import it.cosenonjaviste.daggermock.DaggerMockRule import okhttp3.ResponseBody import org.hamcrest.core.AllOf.allOf import org.junit.Before import org.junit.BeforeClass import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Matchers.anyString import org.mockito.Mockito.`when` import org.mockito.Spy import java.util.ArrayList private const val BUILD_TYPE_NAME = "name" private const val TIMEOUT = 5000 /** * Tests for [ArtifactListFragment] */ @RunWith(AndroidJUnit4::class) class ArtifactListFragmentTest { @JvmField @Rule val restComponentDaggerRule: DaggerMockRule<RestApiComponent> = DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL)) .addComponentDependency( AppComponent::class.java, AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication) ) .set { restApiComponent -> val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.setRestApiInjector(restApiComponent) } @JvmField @Rule val activityRule: CustomIntentsTestRule<BuildDetailsActivity> = CustomIntentsTestRule(BuildDetailsActivity::class.java) @JvmField @Rule val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant("android.permission.WRITE_EXTERNAL_STORAGE") @Spy private val teamCityService: TeamCityService = FakeTeamCityServiceImpl() @Spy private val build: Build = Mocks.successBuild() companion object { @JvmStatic @BeforeClass fun disableOnboarding() { TestUtils.disableOnboarding() } } @Before fun setUp() { val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.restApiInjector.sharedUserStorage().clearAll() app.restApiInjector.sharedUserStorage() .saveGuestUserAccountAndSetItAsActive(Mocks.URL, false) ConditionWatcher.setTimeoutLimit(TIMEOUT) } @Test fun testUserCanSeeArtifacts() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking artifacts onView(withId(R.id.artifact_recycler_view)).check(hasItemsCount(3)) onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ).check(matches(withText("res"))) onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 1, R.id.title ) ).check(matches(withText("AndroidManifest.xml"))) val sizeText = if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.N) { "7.77 kB" } else { "7.59 KB" } onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 1, R.id.subTitle ) ).check(matches(withText(sizeText))) onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 2, R.id.title ) ).check(matches(withText("index.html"))) val sizeText2 = if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.N) { "698 kB" } else { "681 KB" } onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 2, R.id.subTitle ) ).check(matches(withText(sizeText2))) } @Test fun testUserCanSeeArtifactsEmptyMessageIfArtifactsAreEmpty() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`( teamCityService.listArtifacts( anyString(), anyString() ) ).thenReturn(Single.just(Files(emptyList()))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking message onView(withText(R.string.empty_list_message_artifacts)).check(matches(isDisplayed())) } @Test fun testUserCanSeeArtifactsErrorMessageIfSmthBadHappens() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`(teamCityService.listArtifacts(anyString(), anyString())).thenReturn( Single.error( RuntimeException("Fake error happened!") ) ) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking error onView( allOf( withText(R.string.error_view_error_text), withParent(isDisplayed()) ) ).check( matches(isDisplayed()) ) } @Test @Throws(Exception::class) fun testUserCanOpenArtifactWithChildren() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) val folderOne = File( "res", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderTwo = File( "res_level_deeper1", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderThree = File( "res_level_deeper2", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val deeperArtifacts = ArrayList<File>() deeperArtifacts.add(folderTwo) deeperArtifacts.add(folderThree) `when`(teamCityService.listArtifacts(anyString(), anyString())) .thenReturn(Single.just(Files(listOf(folderOne)))) .thenReturn(Single.just(Files(deeperArtifacts))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking first level artifacts onView(withId(R.id.artifact_recycler_view)).check(hasItemsCount(1)) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't find artifact with name res" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .check(matches(withText("res"))) true } catch (ignored: Exception) { false } } }) // Clicking first level artifacts ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't click on artifact at position 0" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .perform(click()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact page is not loaded" } override fun checkCondition(): Boolean { var isResFolderClicked = false try { onView(withText("res_level_deeper1")).check(matches(isDisplayed())) isResFolderClicked = true } catch (ignored: Exception) { onView(withRecyclerView(R.id.artifact_recycler_view).atPosition(0)) .perform(click()) } return isResFolderClicked } }) // In case of the same recycler view ids onView(withText("res_level_deeper1")).check(matches(isDisplayed())) onView(withText("res_level_deeper2")).check(matches(isDisplayed())) } @Test @Throws(Exception::class) fun testUserCanOpenArtifactWithChildrenByLongTap() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) val folderOne = File( "res", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderTwo = File( "res_level_deeper1", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderThree = File( "res_level_deeper2", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val deeperArtifacts = ArrayList<File>() deeperArtifacts.add(folderTwo) deeperArtifacts.add(folderThree) `when`(teamCityService.listArtifacts(anyString(), anyString())) .thenReturn(Single.just(Files(listOf(folderOne)))) .thenReturn(Single.just(Files(deeperArtifacts))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking first level artifacts onView(withId(R.id.artifact_recycler_view)).check(hasItemsCount(1)) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't find artifact with name res" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .check(matches(withText("res"))) true } catch (ignored: Exception) { false } } }) // Long click on first level artifacts ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't do long click on artifact at 0 position" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .perform(longClick()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact menu is not opened" } override fun checkCondition(): Boolean { var isMenuOpened = false try { onView(withText(R.string.artifact_open)) .check(matches(isDisplayed())) isMenuOpened = true } catch (ignored: Exception) { // Clicking first level artifacts onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .perform(longClick()) } return isMenuOpened } }) // Click on open option onView(withText(R.string.artifact_open)) .perform(click()) // In case of the same recycler view ids onView(withText("res_level_deeper1")).check(matches(isDisplayed())) onView(withText("res_level_deeper2")).check(matches(isDisplayed())) } @Ignore @Test fun testUserCanDownloadArtifact() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`(teamCityService.downloadFile(anyString())).thenReturn( Single.just( ResponseBody.create( null, "text" ) ) ) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Clicking on artifact to download onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(1, R.id.title) ) .check(matches(withText("AndroidManifest.xml"))) .perform(click()) // Click on download option onView(withText(R.string.artifact_download)) .perform(click()) // Check filter builds activity is opened intended( allOf( hasAction(Intent.ACTION_VIEW), hasType("*/*") ) ) } @Ignore("Test opens chrome and gets stuck") @Test fun testUserCanOpenHtmlFileInBrowser() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Clicking on artifact onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(2, R.id.title) ) .check(matches(withText("index.html"))) .perform(click()) // Click on download option onView(withText(R.string.artifact_open_in_browser)) .perform(click()) // Check filter builds activity is opened intended( allOf( hasData(Uri.parse("https://teamcity.server.com/repository/download/Checkstyle_IdeaInspectionsPullRequest/null:id/TCity.apk!/index.html?guest=1")), hasAction(Intent.ACTION_VIEW) ) ) } @Test @Throws(Exception::class) fun testUserSeeSnackBarWithErrorMessageIfArtifactWasNotDownloaded() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`(teamCityService.downloadFile(anyString())).thenReturn(Single.error(RuntimeException("ERROR!"))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking artifact title and clicking on it val artifactName = "AndroidManifest.xml" ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't click on artifact with name $artifactName" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(1, R.id.title) ) .check(matches(withText(artifactName))) .perform(click()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact menu is not opened" } override fun checkCondition(): Boolean { var isMenuOpened = false try { onView(withText(R.string.artifact_download)) .check(matches(isDisplayed())) isMenuOpened = true } catch (ignored: Exception) { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(1, R.id.title) ) .perform(click()) } return isMenuOpened } }) // Click on download option onView(withText(R.string.artifact_download)) .perform(click()) // Checking error snack bar message onView(withText(R.string.download_artifact_retry_snack_bar_text)) .check(matches(isDisplayed())) } @SdkSuppress(minSdkVersion = android.os.Build.VERSION_CODES.O) @Test fun testUserBeingAskedToGrantAllowInstallPackagesPermissions() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) val files = ArrayList<File>() files.add( File( "my-fancy-app.apk", 697840, File.Content("/guestAuth/app/rest/builds/id:92912/artifacts/content/TCity.apk!/my-fancy-app.apk"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/my-fancy-app.apk" ) ) val filesMock = Files(files) `when`(teamCityService.listArtifacts(anyString(), anyString())).thenReturn( Single.just( filesMock ) ) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Clicking on apk to download val artifactName = "my-fancy-app.apk" ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't click on artifact with name $artifactName" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(0, R.id.title) ) .check(matches(withText(artifactName))) .perform(click()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact menu is not opened" } override fun checkCondition(): Boolean { var isMenuOpened = false try { onView(withText(R.string.artifact_download)) .check(matches(isDisplayed())) isMenuOpened = true } catch (ignored: Exception) { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(0, R.id.title) ) .perform(click()) } return isMenuOpened } }) // Click on download option onView(withText(R.string.artifact_download)) .perform(click()) // Check dialog text onView(withText(R.string.permissions_install_packages_dialog_content)).check( matches( isDisplayed() ) ) /*// Confirm dialog onView(withText(R.string.dialog_ok_title)).perform(click()); // Check filter builds activity is opened intended(allOf( hasAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES), hasData("package:com.github.vase4kin.teamcityapp.mock.debug")));*/ } }
app/src/androidTest/java/com/github/vase4kin/teamcityapp/artifact/view/ArtifactListFragmentTest.kt
4193997731
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.elasticsearch.aws import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.netflix.spectator.api.Registry import com.netflix.spinnaker.cats.agent.Agent import com.netflix.spinnaker.cats.agent.AgentProvider import com.netflix.spinnaker.clouddriver.aws.provider.AwsProvider import com.netflix.spinnaker.clouddriver.aws.security.AmazonClientProvider import com.netflix.spinnaker.clouddriver.aws.security.NetflixAmazonCredentials import com.netflix.spinnaker.clouddriver.elasticsearch.ElasticSearchClient import com.netflix.spinnaker.clouddriver.security.AccountCredentialsProvider import com.netflix.spinnaker.kork.core.RetrySupport import io.searchbox.client.JestClient open class ElasticSearchAmazonCachingAgentProvider( private val objectMapper: ObjectMapper, private val jestClient: JestClient, private val retrySupport: RetrySupport, private val registry: Registry, private val amazonClientProvider: AmazonClientProvider, private val accountCredentialsProvider: AccountCredentialsProvider ) : AgentProvider { override fun supports(providerName: String): Boolean { return providerName.equals(AwsProvider.PROVIDER_NAME, ignoreCase = true) } override fun agents(): Collection<Agent> { val credentials = accountCredentialsProvider .all .filter { NetflixAmazonCredentials::class.java.isInstance(it) } .map { c -> c as NetflixAmazonCredentials } val elasticSearchClient = ElasticSearchClient( objectMapper.copy().enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS), jestClient ) return listOf( ElasticSearchAmazonServerGroupCachingAgent( retrySupport, registry, amazonClientProvider, credentials, elasticSearchClient ), ElasticSearchAmazonInstanceCachingAgent( retrySupport, registry, amazonClientProvider, credentials, elasticSearchClient ) ) } }
clouddriver-elasticsearch-aws/src/main/kotlin/com/netflix/spinnaker/clouddriver/elasticsearch/aws/ElasticSearchAmazonCachingAgentProvider.kt
3112270934
package com.google.devtools.ksp.processor import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSAnnotated class GetSymbolsFromAnnotationProcessor : AbstractTestProcessor() { val result = mutableListOf<String>() override fun toResult(): List<String> = result override fun process(resolver: Resolver): List<KSAnnotated> { result.add("==== Anno superficial====") resolver.getSymbolsWithAnnotation("Anno").forEach { result.add(toString(it)) } result.add("==== Anno in depth ====") resolver.getSymbolsWithAnnotation("Anno", true).forEach { result.add(toString(it)) } result.add("==== Bnno superficial====") resolver.getSymbolsWithAnnotation("Bnno").forEach { result.add(toString(it)) } result.add("==== Bnno in depth ====") resolver.getSymbolsWithAnnotation("Bnno", true).forEach { result.add(toString(it)) } result.add("==== A1 superficial====") resolver.getSymbolsWithAnnotation("A1").forEach { result.add(toString(it)) } result.add("==== A1 in depth ====") resolver.getSymbolsWithAnnotation("A1", true).forEach { result.add(toString(it)) } result.add("==== A2 superficial====") resolver.getSymbolsWithAnnotation("A2").forEach { result.add(toString(it)) } result.add("==== A2 in depth ====") resolver.getSymbolsWithAnnotation("A2", true).forEach { result.add(toString(it)) } result.add("==== Cnno in depth ====") resolver.getSymbolsWithAnnotation("Cnno", true).forEach { result.add(toString(it)) } return emptyList() } fun toString(annotated: KSAnnotated): String { return "$annotated:${annotated::class.supertypes.first().classifier.toString().substringAfterLast('.')}" } }
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/GetSymbolsFromAnnotationProcessor.kt
3061095771
package com.davinci42.androidutils import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.davinci42.androidutils", appContext.packageName) } }
app/src/androidTest/java/com/davinci42/androidutils/ExampleInstrumentedTest.kt
398035252
package siilinkari.lexer import siilinkari.objects.Value /** * Tokens are the indivisible building blocks of source code. * * [Lexer] analyzes the source string to return tokens to be consumed by the parser. * * Some tokens are singleton values: e.g. when encountering `if` in the source code, * the lexer will return simply [Token.Keyword.If]. Other tokens contain information about * the value read: e.g. for source code `123`, the lexer will return [Token.Literal], * with its `value` set to integer `123`. * * @see TokenInfo */ sealed class Token { /** * Identifier such as variable, method or class name. */ class Identifier(val name: String): Token() { override fun toString() = "[Identifier $name]" override fun equals(other: Any?) = other is Identifier && name == other.name override fun hashCode(): Int = name.hashCode() } /** * Literal value, e.g. `42`, `"foo"`, or `true`. */ class Literal(val value: Value) : Token() { override fun toString() = "[Literal ${value.repr()}]" override fun equals(other: Any?) = other is Literal && value == other.value override fun hashCode(): Int = value.hashCode() } /** * Reserved word in the language. */ sealed class Keyword(private val name: String) : Token() { override fun toString() = name object Else : Keyword("else") object Fun : Keyword("fun") object If : Keyword("if") object Var : Keyword("var") object Val : Keyword("val") object While : Keyword("while") } /** * Operators. */ sealed class Operator(private val name: String) : Token() { override fun toString() = name object Plus : Operator("+") object Minus : Operator("-") object Multiply : Operator("*") object Divide : Operator("/") object EqualEqual : Operator("==") object NotEqual : Operator("!=") object Not : Operator("!") object LessThan : Operator("<") object GreaterThan : Operator(">") object LessThanOrEqual : Operator("<=") object GreaterThanOrEqual : Operator(">=") object And : Operator("&&") object Or : Operator("&&") } /** * General punctuation. */ sealed class Punctuation(private val name: String) : Token() { override fun toString() = "'$name'" object LeftParen : Punctuation("(") object RightParen : Punctuation(")") object LeftBrace : Punctuation("{") object RightBrace : Punctuation("}") object Equal : Punctuation("=") object Colon : Punctuation(":") object Semicolon : Punctuation(";") object Comma : Punctuation(",") } }
src/main/kotlin/siilinkari/lexer/Token.kt
3052598854
package ma.sdop.weatherapp.domain.commands import ma.sdop.weatherapp.domain.datasource.ForecastProvider import ma.sdop.weatherapp.domain.model.Forecast /** * Created by parkjoosung on 2017. 4. 27.. */ class RequestDayForecastCommand( val id: Long, val forecastProvider: ForecastProvider = ForecastProvider()): Command<Forecast> { override fun execute(): Forecast = forecastProvider.requestDayForecast(id) }
app/src/main/java/ma/sdop/weatherapp/domain/commands/RequestDayForecastCommand.kt
2571784092
package com.philsoft.metrotripper.app.nextrip import android.support.v7.widget.RecyclerView import android.view.View import com.philsoft.metrotripper.R import com.philsoft.metrotripper.app.nextrip.constants.Direction import com.philsoft.metrotripper.model.Trip import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.trip_item.* class TripViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun render(trip: Trip) { timeUnit.visibility = View.VISIBLE route.text = trip.route + trip.terminal description.text = trip.description routeDirection.setImageResource(getTripDirectionResource(trip)) val timeAndText = trip.departureText.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() timeNumber.text = timeAndText[0] if (timeAndText.size > 1) { timeUnit.setText(R.string.minutes) } else { timeUnit.visibility = View.GONE } } private fun getTripDirectionResource(trip: Trip): Int { val direction = Direction.valueOf(trip.routeDirection) return when (direction) { Direction.NORTHBOUND -> R.drawable.ic_up_arrow Direction.SOUTHBOUND -> R.drawable.ic_down_arrow Direction.EASTBOUND -> R.drawable.ic_right_arrow Direction.WESTBOUND -> R.drawable.ic_left_arrow else -> 0 } } private fun setColors(mainColorResId: Int, topLineColorResId: Int, bottomLineColorResId: Int) { mainLayout.setBackgroundResource(mainColorResId) lineTop.setBackgroundResource(topLineColorResId) lineBottom.setBackgroundResource(bottomLineColorResId) } }
app/src/main/java/com/philsoft/metrotripper/app/nextrip/TripViewHolder.kt
3885334519
/* * 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.Pass import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.util.FunctionUtil import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.parentOfType import java.util.* /** * Line marker provider that annotates recursive funciton and method calls with * an icon on the gutter. */ class RsRecursiveCallLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement) = null override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) { val lines = HashSet<Int>() // To prevent several markers on one line for (el in elements.filter { it.isRecursive }) { val doc = PsiDocumentManager.getInstance(el.project).getDocument(el.containingFile) ?: continue val lineNumber = doc.getLineNumber(el.textOffset) if (lineNumber !in lines) { lines.add(lineNumber) result.add(LineMarkerInfo( el, el.textRange, RsIcons.RECURSIVE_CALL, Pass.LINE_MARKERS, FunctionUtil.constant("Recursive call"), null, GutterIconRenderer.Alignment.RIGHT)) } } } private val RsCallExpr.pathExpr: RsPathExpr? get() = expr as? RsPathExpr private val PsiElement.isRecursive: Boolean get() { val def = when (this) { is RsCallExpr -> pathExpr?.path?.reference?.resolve() is RsMethodCall -> reference.resolve() else -> null } ?: return false return parentOfType<RsFunction>() == def } }
src/main/kotlin/org/rust/ide/annotator/RsRecursiveCallLineMarkerProvider.kt
2528533436
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.impl import com.intellij.formatting.ASTBlock import com.intellij.formatting.Block import com.intellij.formatting.Spacing import com.intellij.formatting.Spacing.createSpacing import com.intellij.formatting.SpacingBuilder import com.intellij.lang.ASTNode import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.codeStyle.CommonCodeStyleSettings import com.intellij.psi.impl.source.tree.TreeUtil import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.rust.ide.formatter.RsFmtContext import org.rust.ide.formatter.settings.RsCodeStyleSettings import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.ext.RsItemElement import org.rust.lang.core.psi.ext.RsNamedElement import org.rust.lang.core.psi.ext.getNextNonCommentSibling import org.rust.lang.core.psi.ext.getPrevNonCommentSibling import com.intellij.psi.tree.TokenSet.create as ts fun createSpacingBuilder(commonSettings: CommonCodeStyleSettings, rustSettings: RsCodeStyleSettings): SpacingBuilder { // Use `sbX` temporaries to work around // https://youtrack.jetbrains.com/issue/KT-12239 val sb1 = SpacingBuilder(commonSettings) // Rules defined earlier have higher priority. // Beware of comments between blocks! //== some special operators // FIXME(mkaput): Doesn't work well with comments .afterInside(COMMA, ts(BLOCK_FIELDS, ENUM_BODY)).parentDependentLFSpacing(1, 1, true, 1) .afterInside(COMMA, ts(BLOCK_FIELDS, STRUCT_LITERAL_BODY)).parentDependentLFSpacing(1, 1, true, 1) .after(COMMA).spacing(1, 1, 0, true, 0) .before(COMMA).spaceIf(false) .after(COLON).spaceIf(true) .before(COLON).spaceIf(false) .after(SEMICOLON).spaceIf(true) .before(SEMICOLON).spaceIf(false) .afterInside(AND, ts(REF_LIKE_TYPE, SELF_PARAMETER, PAT_REF, VALUE_PARAMETER)).spaces(0) .beforeInside(Q, TRY_EXPR).spaces(0) .afterInside(UNARY_OPS, UNARY_EXPR).spaces(0) // `use ::{bar}` .between(USE, COLONCOLON).spaces(1) //== attributes .aroundInside(ts(SHA, EXCL, LBRACK, RBRACK), ATTRS).spaces(0) .aroundInside(ts(LPAREN, RPAREN), META_ITEM_ARGS).spaces(0) .around(META_ITEM_ARGS).spaces(0) //== empty parens .between(LPAREN, RPAREN).spacing(0, 0, 0, false, 0) .between(LBRACK, RBRACK).spacing(0, 0, 0, false, 0) .between(LBRACE, RBRACE).spacing(0, 0, 0, false, 0) .betweenInside(OR, OR, LAMBDA_EXPR).spacing(0, 0, 0, false, 0) //== paren delimited lists // withinPairInside does not accept TokenSet as parent node set :( // and we cannot create our own, because RuleCondition stuff is private .afterInside(LPAREN, PAREN_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(RPAREN, PAREN_LISTS).spacing(0, 0, 0, true, 0) .afterInside(LBRACK, BRACK_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(RBRACK, BRACK_LISTS).spacing(0, 0, 0, true, 0) .afterInside(LBRACE, BRACE_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(RBRACE, BRACE_LISTS).spacing(0, 0, 0, true, 0) .afterInside(LT, ANGLE_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(GT, ANGLE_LISTS).spacing(0, 0, 0, true, 0) .aroundInside(OR, VALUE_PARAMETER_LIST).spacing(0, 0, 0, false, 0) val sb2 = sb1 //== items .between(VALUE_PARAMETER_LIST, RET_TYPE).spacing(1, 1, 0, true, 0) .before(WHERE_CLAUSE).spacing(1, 1, 0, true, 0) .beforeInside(LBRACE, FLAT_BRACE_BLOCKS).spaces(1) .between(ts(IDENTIFIER, FN), VALUE_PARAMETER_LIST).spaceIf(false) .between(IDENTIFIER, TUPLE_FIELDS).spaces(0) .between(IDENTIFIER, TYPE_PARAMETER_LIST).spaceIf(false) .between(IDENTIFIER, TYPE_ARGUMENT_LIST).spaceIf(false) .between(IDENTIFIER, VALUE_ARGUMENT_LIST).spaceIf(false) .between(TYPE_PARAMETER_LIST, VALUE_PARAMETER_LIST).spaceIf(false) .before(VALUE_ARGUMENT_LIST).spaceIf(false) .between(BINDING_MODE, IDENTIFIER).spaces(1) .between(IMPL, TYPE_PARAMETER_LIST).spaces(0) .afterInside(TYPE_PARAMETER_LIST, IMPL_ITEM).spaces(1) .betweenInside(ts(TYPE_PARAMETER_LIST), TYPES, IMPL_ITEM).spaces(1) // Handling blocks is pretty complicated. Do not tamper with // them too much and let rustfmt do all the pesky work. // Some basic transformation from in-line block to multi-line block // is also performed; see doc of #blockMustBeMultiLine() for details. .afterInside(LBRACE, BLOCK_LIKE).parentDependentLFSpacing(1, 1, true, 0) .beforeInside(RBRACE, BLOCK_LIKE).parentDependentLFSpacing(1, 1, true, 0) .afterInside(LBRACE, FLAT_BRACE_BLOCKS).parentDependentLFSpacing(1, 1, true, 0) .beforeInside(RBRACE, FLAT_BRACE_BLOCKS).parentDependentLFSpacing(1, 1, true, 0) .withinPairInside(LBRACE, RBRACE, PAT_STRUCT).spacing(1, 1, 0, true, 0) .betweenInside(IDENTIFIER, ALIAS, EXTERN_CRATE_ITEM).spaces(1) .betweenInside(IDENTIFIER, TUPLE_FIELDS, ENUM_VARIANT).spaces(0) .betweenInside(IDENTIFIER, VARIANT_DISCRIMINANT, ENUM_VARIANT).spaces(1) return sb2 //== types .afterInside(LIFETIME, REF_LIKE_TYPE).spaceIf(true) .betweenInside(ts(MUL), ts(CONST, MUT), REF_LIKE_TYPE).spaces(0) .before(TYPE_PARAM_BOUNDS).spaces(0) .beforeInside(LPAREN, PATH).spaces(0) .after(TYPE_QUAL).spaces(0) .betweenInside(FOR, LT, FOR_LIFETIMES).spacing(0, 0, 0, true, 0) .around(FOR_LIFETIMES).spacing(1, 1, 0, true, 0) .aroundInside(EQ, ASSOC_TYPE_BINDING).spaces(0) //== expressions .beforeInside(LPAREN, PAT_ENUM).spaces(0) .beforeInside(LBRACK, INDEX_EXPR).spaces(0) .afterInside(VALUE_PARAMETER_LIST, LAMBDA_EXPR).spacing(1, 1, 0, true, 1) .between(MATCH_ARM, MATCH_ARM).spacing(1, 1, if (rustSettings.ALLOW_ONE_LINE_MATCH) 0 else 1, true, 1) .before(ELSE_BRANCH).spacing(1, 1, 0, false, 0) .betweenInside(ELSE, BLOCK, ELSE_BRANCH).spacing(1, 1, 0, false, 0) //== macros .beforeInside(EXCL, MACRO_CALL).spaces(0) .beforeInside(EXCL, MACRO_DEFINITION).spaces(0) .afterInside(EXCL, MACRO_DEFINITION).spaces(1) .betweenInside(IDENTIFIER, MACRO_DEFINITION_BODY, MACRO_DEFINITION).spaces(1) //== rules with very large area of application .around(NO_SPACE_AROUND_OPS).spaces(0) .around(SPACE_AROUND_OPS).spaces(1) .around(RS_KEYWORDS).spaces(1) .applyForEach(BLOCK_LIKE) { before(it).spaces(1) } } fun Block.computeSpacing(child1: Block?, child2: Block, ctx: RsFmtContext): Spacing? { if (child1 is ASTBlock && child2 is ASTBlock) SpacingContext.create(child1, child2, ctx).apply { when { // #[attr]\n<comment>\n => #[attr] <comment>\n etc. psi1 is RsOuterAttr && psi2 is PsiComment -> return createSpacing(1, 1, 0, true, 0) // Determine spacing between macro invocation and it's arguments parentPsi is RsMacroCall && elementType1 == EXCL -> return if (node2.chars.first() == '{' || elementType2 == IDENTIFIER) { createSpacing(1, 1, 0, false, 0) } else { createSpacing(0, 0, 0, false, 0) } // Ensure that each attribute is in separate line; comment aware psi1 is RsOuterAttr && (psi2 is RsOuterAttr || psi1.parent is RsItemElement) || psi1 is PsiComment && (psi2 is RsOuterAttr || psi1.getPrevNonCommentSibling() is RsOuterAttr) -> return lineBreak(keepBlankLines = 0) // Format blank lines between statements (or return expression) ncPsi1 is RsStmt && ncPsi2.isStmtOrExpr -> return lineBreak( keepLineBreaks = ctx.commonSettings.KEEP_LINE_BREAKS, keepBlankLines = ctx.commonSettings.KEEP_BLANK_LINES_IN_CODE) // Format blank lines between impl & trait members parentPsi is RsMembers && ncPsi1 is RsNamedElement && ncPsi2 is RsNamedElement -> return lineBreak( keepLineBreaks = ctx.commonSettings.KEEP_LINE_BREAKS, keepBlankLines = ctx.commonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS) // Format blank lines between top level items ncPsi1.isTopLevelItem && ncPsi2.isTopLevelItem -> return lineBreak( minLineFeeds = 1 + if (!needsBlankLineBetweenItems()) 0 else ctx.rustSettings.MIN_NUMBER_OF_BLANKS_BETWEEN_ITEMS, keepLineBreaks = ctx.commonSettings.KEEP_LINE_BREAKS, keepBlankLines = ctx.commonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS) } } return ctx.spacingBuilder.getSpacing(this, child1, child2) } private data class SpacingContext(val node1: ASTNode, val node2: ASTNode, val psi1: PsiElement, val psi2: PsiElement, val elementType1: IElementType, val elementType2: IElementType, val parentType: IElementType?, val parentPsi: PsiElement?, val ncPsi1: PsiElement, val ncPsi2: PsiElement, val ctx: RsFmtContext) { companion object { fun create(child1: ASTBlock, child2: ASTBlock, ctx: RsFmtContext): SpacingContext { val node1 = child1.node val node2 = child2.node val psi1 = node1.psi val psi2 = node2.psi val elementType1 = psi1.node.elementType val elementType2 = psi2.node.elementType val parentType = node1.treeParent.elementType val parentPsi = psi1.parent val (ncPsi1, ncPsi2) = omitCommentBlocks(node1, psi1, node2, psi2) return SpacingContext(node1, node2, psi1, psi2, elementType1, elementType2, parentType, parentPsi, ncPsi1, ncPsi2, ctx) } /** * Handle blocks of comments to get proper spacing between items and statements */ private fun omitCommentBlocks(node1: ASTNode, psi1: PsiElement, node2: ASTNode, psi2: PsiElement): Pair<PsiElement, PsiElement> = Pair( if (psi1 is PsiComment && node1.hasLineBreakAfterInSameParent()) { psi1.getPrevNonCommentSibling() ?: psi1 } else { psi1 }, if (psi2 is PsiComment && node2.hasLineBreakBeforeInSameParent()) { psi2.getNextNonCommentSibling() ?: psi2 } else { psi2 } ) } } private inline fun SpacingBuilder.applyForEach( tokenSet: TokenSet, block: SpacingBuilder.(IElementType) -> SpacingBuilder): SpacingBuilder { var self = this for (tt in tokenSet.types) { self = block(this, tt) } return self } private fun lineBreak(minLineFeeds: Int = 1, keepLineBreaks: Boolean = true, keepBlankLines: Int = 1): Spacing = createSpacing(0, Int.MAX_VALUE, minLineFeeds, keepLineBreaks, keepBlankLines) private fun ASTNode.hasLineBreakAfterInSameParent(): Boolean = treeNext != null && TreeUtil.findFirstLeaf(treeNext).isWhiteSpaceWithLineBreak() private fun ASTNode.hasLineBreakBeforeInSameParent(): Boolean = treePrev != null && TreeUtil.findLastLeaf(treePrev).isWhiteSpaceWithLineBreak() private fun ASTNode?.isWhiteSpaceWithLineBreak(): Boolean = this != null && elementType == WHITE_SPACE && textContains('\n') private fun SpacingContext.needsBlankLineBetweenItems(): Boolean { if (elementType1 in RS_COMMENTS || elementType2 in RS_COMMENTS) return false // Allow to keep consecutive runs of `use`, `const` or other "one line" items without blank lines if (elementType1 == elementType2 && elementType1 in ONE_LINE_ITEMS) return false // #![deny(missing_docs) // extern crate regex; if (elementType1 == INNER_ATTR && elementType2 == EXTERN_CRATE_ITEM) return false return true }
src/main/kotlin/org/rust/ide/formatter/impl/spacing.kt
2046108980
package edu.cs4730.callbacksitemviewdemo_kt import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.util.Log import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.DefaultItemAnimator import android.widget.Toast import androidx.fragment.app.Fragment import java.lang.ClassCastException import java.util.* /** * A simple fragment that displays a recyclerview and has a callback * plus creates the listener needed in the adapter. */ class MainFragment : Fragment() { private var mCallback: OntransInteractionCallback? = null private lateinit var mRecyclerView: RecyclerView private lateinit var mAdapter: myAdapter private val TAG = "MainFragment" private val mList: List<String> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val myView = inflater.inflate(R.layout.fragment_main, container, false) mRecyclerView = myView.findViewById(R.id.listtrans) mRecyclerView.layoutManager = LinearLayoutManager(requireActivity()) mRecyclerView.itemAnimator = DefaultItemAnimator() mAdapter = myAdapter(mList, R.layout.row_layout, requireActivity()) // mAdapter.setOnItemClickListener { view, id -> // String name = users.get(position).name; // Log.v(TAG, "Listener at $TAG") // Toast.makeText(context, "MainFragment: $id was clicked!", Toast.LENGTH_SHORT).show() // //we could just send the id or in this case get the name as something more useful here. // val name = mAdapter.myList[id.toInt()] // mCallback!!.ontransInteraction(name) // } mAdapter.setOnItemClickListener(object : myAdapter.OnItemClickListener { override fun onItemClick(itemView: View, id: String) { // String name = users.get(position).name; Log.v(TAG, "Listener at $TAG") Toast.makeText(context, "MainFragment: $id was clicked!", Toast.LENGTH_SHORT).show() //we could just send the id or in this case get the name as something more useful here. val name = mAdapter.myList?.get(id.toInt()) if (name != null) { mCallback!!.ontransInteraction(name) } else { //this else should never happen, but kotlin got weird about a null check you don't do in java. mCallback!!.ontransInteraction(id) } } }) //add the adapter to the recyclerview mRecyclerView.adapter = mAdapter return myView } //use this one instead of the one above. Note it's the parameter, context instead of activity. override fun onAttach(context: Context) { super.onAttach(context) mCallback = try { requireActivity() as OntransInteractionCallback } catch (e: ClassCastException) { throw ClassCastException( requireActivity() .toString() + " must implement OnFragmentInteractionListener" ) } } override fun onDetach() { super.onDetach() mCallback = null } //The interface for the call back code that needs to be implemented. interface OntransInteractionCallback { fun ontransInteraction(item: String) } init { mList = Arrays.asList( "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" ) } }
RecyclerViews/CallBacksItemViewDemo_kt/app/src/main/java/edu/cs4730/callbacksitemviewdemo_kt/MainFragment.kt
3636022228
/* * Copyright (C) 2020. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at support@openlattice.com * * */ package com.openlattice.users.export import com.auth0.json.mgmt.jobs.Job import com.dataloom.mappers.ObjectMappers import okhttp3.* import org.slf4j.LoggerFactory private const val JOBS_PATH = "api/v2/jobs" private const val CONTENT_TYPE_APPLICATION_JSON = "application/json" class UserExportEntity(private val client: OkHttpClient, private val baseUrl: HttpUrl, private val apiToken: String) { private val mapper = ObjectMappers.getJsonMapper() companion object { private val logger = LoggerFactory.getLogger(UserExportJobRequest::class.java) } /** * Submits a user export job to auth0. */ fun submitExportJob(exportJob: UserExportJobRequest): Job { val url = baseUrl .newBuilder() .addPathSegments("$JOBS_PATH/users-exports") .build() .toString() val body = RequestBody.create( MediaType.parse(CONTENT_TYPE_APPLICATION_JSON), mapper.writeValueAsBytes(exportJob) ) val request = Request.Builder() .url(url) .addHeader("Authorization", "Bearer $apiToken") .addHeader("Content-Type", CONTENT_TYPE_APPLICATION_JSON) .post(body) .build() try { val response = client.newCall(request).execute() return mapper.readValue(response.body()?.bytes(), Job::class.java) } catch (ex: Exception) { logger.info("Encountered exception $ex when submitting export job $exportJob.") throw ex } } /** * Retrieves a job result from auth0 by [jobId]. */ fun getJob(jobId: String): UserExportJobResult { val url = baseUrl .newBuilder() .addPathSegments("$JOBS_PATH/$jobId") .build() .toString() val request = Request.Builder() .url(url) .addHeader("Authorization", "Bearer $apiToken") .addHeader("Content-Type", CONTENT_TYPE_APPLICATION_JSON) .get() .build() try { val response = client.newCall(request).execute() return mapper.readValue(response.body()?.bytes(), UserExportJobResult::class.java) } catch (ex: Exception) { logger.info("Encountered exception $ex when trying to get export job $jobId.") throw ex } } }
src/main/kotlin/com/openlattice/users/export/UserExportEntity.kt
2730291637
/* * 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.callbacks import com.sdibt.korm.core.db.DataSourceType import com.sdibt.korm.core.db.KormSqlSession import com.sdibt.korm.core.entity.EntityFieldsCache import java.time.LocalDateTime class CallBackBatchInsert(db: KormSqlSession) { val defaultCallBack = DefaultCallBack.instance.getCallBack(db) fun init() { defaultCallBack.batchInsert().reg("batchSetSqlParam") { batchSetSqlParamCallback(it) } defaultCallBack.batchInsert().reg("beforeBatchInsert") { beforeBatchInsertCallback(it) } defaultCallBack.batchInsert().reg("batchInsertDateTime") { batchInsertDateTimeCallback(it) } defaultCallBack.batchInsert().reg("batchInsertOperator") { batchInsertOperatorCallback(it) } defaultCallBack.batchInsert().reg("batchInsert") { batchInsertCallback(it) } defaultCallBack.batchInsert().reg("sqlProcess") { CallBackCommon().sqlProcess(it) } defaultCallBack.batchInsert().reg("setDataSource") { CallBackCommon().setDataSoure(it) } defaultCallBack.batchInsert().reg("exec") { execCallback(it) } defaultCallBack.batchInsert().reg("afterBatchInsert") { afterBatchInsertCallback(it) } } fun beforeBatchInsertCallback(scope: Scope): Scope { var execScope = scope if (!execScope.hasError) { execScope = scope.callMethod("beforeSave") } if (!execScope.hasError) { execScope = scope.callMethod("beforeInsert") } return execScope } fun afterBatchInsertCallback(scope: Scope): Scope { var execScope = scope if (!execScope.hasError) { execScope = scope.callMethod("afterInsert") } if (!execScope.hasError) { execScope = scope.callMethod("afterSave") } return execScope } fun batchSetSqlParamCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope //单独拿出来作为一个操作 scope.batchEntitys?.forEach { entity -> scope.batchSqlParam.put(entity, entity.sqlParams().toMutableMap()) } return scope } fun batchInsertOperatorCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope val item = EntityFieldsCache.item(scope.entity!!) item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.createdBy}", scope.callMethodGetOperator("getOperator")) } } item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.updatedBy}", scope.callMethodGetOperator("getOperator")) } } return scope } fun batchInsertDateTimeCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope val item = EntityFieldsCache.item(scope.entity!!) val time = LocalDateTime.now() item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.createdAt}", time) } } item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.updatedAt}", time) } } return scope } fun batchInsertCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope when (scope.actionType) { ActionType.Entity -> return scope.batchInsertEntity() } return scope } fun execCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope if (scope.db.Error == null) { val (rowsAffected, generatedKeys) = scope.db.executeBatchUpdate( scope.sqlString, scope.batchSqlParam, dsName = scope.dsName, dsType = DataSourceType.WRITE ) scope.rowsAffected = rowsAffected scope.generatedKeys = generatedKeys scope.result = rowsAffected } return scope } }
src/main/kotlin/com/sdibt/korm/core/callbacks/CallBackBatchInsert.kt
2221597555
package org.http4k.lens interface LensInjector<in IN, in OUT> { /** * Lens operation to set the value into the target */ operator fun <R : OUT> invoke(value: IN, target: R): R /** * Lens operation to set the value into the target. Synomym for invoke(IN, OUT) */ fun <R : OUT> inject(value: IN, target: R): R = invoke(value, target) /** * Lens operation to set the value into the target. Synomym for invoke(IN, OUT) */ operator fun <R : OUT> set(target: R, value: IN) = inject(value, target) /** * Bind this Lens to a value, so we can set it into a target */ infix fun <R : OUT> of(value: IN): (R) -> R = { invoke(value, it) } /** * Restrict the type that this Lens can inject into */ fun <NEXT : OUT> restrictInto(): LensInjector<IN, NEXT> = this } interface LensExtractor<in IN, out OUT> : (IN) -> OUT { /** * Lens operation to get the value from the target * @throws LensFailure if the value could not be retrieved from the target (missing/invalid etc) */ @Throws(LensFailure::class) override operator fun invoke(target: IN): OUT /** * Lens operation to get the value from the target. Synonym for invoke(IN) * @throws LensFailure if the value could not be retrieved from the target (missing/invalid etc) */ @Throws(LensFailure::class) fun extract(target: IN): OUT = invoke(target) /** * Lens operation to get the value from the target. Synonym for invoke(IN) */ operator fun <R : IN> get(target: R) = extract(target) /** * Restrict the type that this Lens can extract from */ fun <NEXT : IN> restrictFrom(): LensExtractor<NEXT, OUT> = this } interface LensInjectorExtractor<IN, OUT> : LensExtractor<IN, OUT>, LensInjector<OUT, IN>
http4k-core/src/main/kotlin/org/http4k/lens/extractInject.kt
2989315352
package com.geckour.egret.view.fragment import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import com.geckour.egret.R import com.geckour.egret.api.MastodonClient import com.geckour.egret.api.model.Account import com.geckour.egret.databinding.FragmentBlockAccountBinding import com.geckour.egret.util.Common import com.geckour.egret.view.activity.MainActivity import com.geckour.egret.view.adapter.BlockAccountAdapter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber class AccountBlockFragment: BaseFragment() { lateinit private var binding: FragmentBlockAccountBinding private val adapter: BlockAccountAdapter by lazy { BlockAccountAdapter() } private val preItems: ArrayList<Account> = ArrayList() private var onTop = true private var inTouch = false private var maxId: Long = -1 private var sinceId: Long = -1 companion object { val TAG: String = this::class.java.simpleName fun newInstance(): AccountBlockFragment = AccountBlockFragment().apply { } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_block_account, container, false) return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val helper = Common.getSwipeToDismissTouchHelperForBlockAccount(adapter) helper.attachToRecyclerView(binding.recyclerView) binding.recyclerView.addItemDecoration(helper) binding.recyclerView.adapter = adapter binding.recyclerView.setOnTouchListener { _, event -> when (event.action) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { inTouch = true } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { inTouch = false } } false } binding.recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val scrollY: Int = recyclerView?.computeVerticalScrollOffset() ?: -1 onTop = scrollY == 0 || onTop && !(inTouch && scrollY > 0) if (!onTop) { val y = scrollY + (recyclerView?.height ?: -1) val h = recyclerView?.computeVerticalScrollRange() ?: -1 if (y == h) { bindAccounts(true) } } } }) binding.swipeRefreshLayout.apply { setColorSchemeResources(R.color.colorAccent) setOnRefreshListener { bindAccounts() } } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) bindAccounts() } override fun onResume() { super.onResume() if (activity is MainActivity) ((activity as MainActivity).findViewById(R.id.fab) as FloatingActionButton?)?.hide() } override fun onPause() { super.onPause() removeAccounts(adapter.getItems()) } fun bindAccounts(loadNext: Boolean = false) { if (loadNext && maxId == -1L) return Common.resetAuthInfo()?.let { domain -> MastodonClient(domain).getBlockedUsersWithHeaders(maxId = if (loadNext) maxId else null, sinceId = if (!loadNext && sinceId != -1L) sinceId else null) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ it.response()?.let { adapter.addAllItems(it.body()) preItems.addAll(it.body()) it.headers().get("Link")?.let { maxId = Common.getMaxIdFromLinkString(it) sinceId = Common.getSinceIdFromLinkString(it) } toggleRefreshIndicatorState(false) } }, { throwable -> throwable.printStackTrace() toggleRefreshIndicatorState(false) }) } } fun removeAccounts(items: List<Account>) { val shouldRemoveItems = preItems.filter { items.none { item -> it.id == item.id } } Common.resetAuthInfo()?.let { domain -> shouldRemoveItems.forEach { MastodonClient(domain).unBlockAccount(it.id) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Timber.d("unblocked account: ${it.accountId}") }, Throwable::printStackTrace) } // Snackbar.make(binding.root, "hoge", Snackbar.LENGTH_SHORT).show() } } fun toggleRefreshIndicatorState(show: Boolean) = Common.toggleRefreshIndicatorState(binding.swipeRefreshLayout, show) }
app/src/main/java/com/geckour/egret/view/fragment/AccountBlockFragment.kt
4075181516
package com.binarymonks.jj.core import com.badlogic.gdx.physics.box2d.BodyDef import com.binarymonks.jj.core.api.* import com.binarymonks.jj.core.assets.Assets import com.binarymonks.jj.core.async.Tasks import com.binarymonks.jj.core.audio.Audio import com.binarymonks.jj.core.debug.Controls import com.binarymonks.jj.core.events.EventBus import com.binarymonks.jj.core.input.mapping.InputMapper import com.binarymonks.jj.core.layers.GameRenderingLayer import com.binarymonks.jj.core.layers.InputLayer import com.binarymonks.jj.core.layers.LayerStack import com.binarymonks.jj.core.physics.PhysicsWorld import com.binarymonks.jj.core.pools.Pools import com.binarymonks.jj.core.render.RenderWorld import com.binarymonks.jj.core.scenes.Scenes import com.binarymonks.jj.core.specs.SceneSpec import com.binarymonks.jj.core.specs.params import com.binarymonks.jj.core.time.ClockControls /** * The front end global api. * * Provides access to the commonly used interfaces and operations for interacting * with the engine. For complete interfaces have a look at [JJ.B] * */ object JJ { private var initialised = false lateinit var scenes: ScenesAPI lateinit var assets: AssetsAPI lateinit var layers: LayersAPI lateinit var pools: PoolsAPI lateinit var clock: ClockAPI lateinit var physics: PhysicsAPI lateinit var render: RenderAPI lateinit var tasks: TasksAPI lateinit var input: InputAPI lateinit var events: EventsAPI lateinit var B: Backend internal fun initialise(config: JJConfig, game: JJGame) { if (initialised) { throw Exception("Already initialised") } initialised = true B = Backend() B.game = game B.config = config B.clock = ClockControls() B.scenes = Scenes() B.layers = LayerStack(config.gameView.clearColor) B.physicsWorld = PhysicsWorld() B.renderWorld = RenderWorld() B.pools = Pools() B.assets = Assets() B.audio = Audio() B.defaultGameRenderingLayer = GameRenderingLayer(config.gameView) B.input = InputMapper() B.defaultGameRenderingLayer.inputMultiplexer.addProcessor(B.input) B.layers.push(B.defaultGameRenderingLayer) B.tasks = Tasks() if(config.debugStep){ B.clock.setTimeFunction(ClockControls.TimeFunction.FIXED_TIME) B.layers.push(InputLayer(Controls())) } scenes = B.scenes layers = B.layers pools = B.pools clock = B.clock physics = B.physicsWorld assets = B.assets render = B.renderWorld tasks = B.tasks input = B.input events = EventBus() val rootScene = JJ.B.scenes.masterFactory.createScene( SceneSpec { physics { bodyType = BodyDef.BodyType.StaticBody } }, params { }, null ) B.scenes.rootScene = rootScene rootScene.onAddToWorld() } }
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/JJ.kt
4038820343
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui.artist import tm.alashow.datmusic.domain.entities.Artist import tm.alashow.domain.models.Async import tm.alashow.domain.models.Uninitialized data class ArtistDetailViewState( val artist: Artist? = null, val artistDetails: Async<Artist> = Uninitialized ) { companion object { val Empty = ArtistDetailViewState() } }
modules/ui-artist/src/main/java/tm/alashow/datmusic/ui/artist/ArtistDetailViewState.kt
706709070
package com.github.czyzby.setup.data.platforms import com.github.czyzby.setup.data.files.CopiedFile import com.github.czyzby.setup.data.files.SourceFile import com.github.czyzby.setup.data.files.path import com.github.czyzby.setup.data.gradle.GradleFile import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.GdxPlatform /** * Represents iOS backend. * @author MJ */ @GdxPlatform class iOS : Platform { companion object { const val ID = "ios" } override val id = ID override fun createGradleFile(project: Project): GradleFile = iOSGradleFile(project) override fun initiate(project: Project) { project.rootGradle.buildDependencies.add("\"com.mobidevelop.robovm:robovm-gradle-plugin:\$robovmVersion\"") project.properties["robovmVersion"] = project.advanced.robovmVersion // Including RoboVM config files: project.files.add(CopiedFile(projectName = ID, path = "Info.plist.xml", original = path("generator", "ios", "Info.plist.xml"))) project.files.add(SourceFile(projectName = ID, fileName = "robovm.properties", content = """app.version=${project.advanced.version} app.id=${project.basic.rootPackage} app.mainclass=${project.basic.rootPackage}.ios.IOSLauncher app.executable=IOSLauncher app.build=1 app.name=${project.basic.name}""")) project.files.add(SourceFile(projectName = ID, fileName = "robovm.xml", content = """<config> <executableName>${'$'}{app.executable}</executableName> <mainClass>${'$'}{app.mainclass}</mainClass> <os>ios</os> <arch>thumbv7</arch> <target>ios</target> <iosInfoPList>Info.plist.xml</iosInfoPList> <resources> <resource> <directory>../assets</directory> <includes> <include>**</include> </includes> <skipPngCrush>true</skipPngCrush> </resource> <resource> <directory>data</directory> </resource> </resources> <forceLinkClasses> <pattern>com.badlogic.gdx.scenes.scene2d.ui.*</pattern> <pattern>com.badlogic.gdx.graphics.g3d.particles.**</pattern> <pattern>com.android.okhttp.HttpHandler</pattern> <pattern>com.android.okhttp.HttpsHandler</pattern> <pattern>com.android.org.conscrypt.**</pattern> <pattern>com.android.org.bouncycastle.jce.provider.BouncyCastleProvider</pattern> <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.BC${'$'}Mappings</pattern> <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi</pattern> <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi${'$'}Std</pattern> <pattern>com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi</pattern> <pattern>com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL</pattern> <pattern>org.apache.harmony.security.provider.cert.DRLCertFactory</pattern> <pattern>org.apache.harmony.security.provider.crypto.CryptoProvider</pattern> </forceLinkClasses> <libs> <lib>z</lib> </libs> <frameworks> <framework>UIKit</framework> <framework>OpenGLES</framework> <framework>QuartzCore</framework> <framework>CoreGraphics</framework> <framework>OpenAL</framework> <framework>AudioToolbox</framework> <framework>AVFoundation</framework> </frameworks> </config>""")) // Copying data images: arrayOf("Default.png", "Default@2x.png", "Default@2x~ipad.png", "Default-375w-667h@2x.png", "Default-414w-736h@3x.png", "Default-568h@2x.png", "Default-1024w-1366h@2x~ipad.png", "Default~ipad.png", "Icon.png", "Icon@2x.png", "Icon-72.png", "Icon-72@2x.png").forEach { project.files.add(CopiedFile(projectName = ID, path = path("data", it), original = path("generator", "ios", "data", it))) } // Including reflected classes: if (project.reflectedClasses.isNotEmpty() || project.reflectedPackages.isNotEmpty()) { project.files.add(SourceFile(projectName = ID, sourceFolderPath = path("src", "main", "resources"), packageName = "META-INF.robovm.ios", fileName = "robovm.xml", content = """<config> <forceLinkClasses> ${project.reflectedPackages.joinToString(separator = "\n") { " <pattern>${it}.**</pattern>" }} ${project.reflectedClasses.joinToString(separator = "\n") { " <pattern>${it}</pattern>" }} </forceLinkClasses> </config>""")) } } } class iOSGradleFile(val project: Project) : GradleFile(iOS.ID) { init { dependencies.add("project(':${Core.ID}')") addDependency("com.mobidevelop.robovm:robovm-rt:\$robovmVersion") addDependency("com.mobidevelop.robovm:robovm-cocoatouch:\$robovmVersion") addDependency("com.badlogicgames.gdx:gdx-backend-robovm:\$gdxVersion") addDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-ios") } override fun getContent() = """apply plugin: 'robovm' [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' ext { mainClassName = "${project.basic.rootPackage}.ios.IOSLauncher" } launchIPhoneSimulator.dependsOn build launchIPadSimulator.dependsOn build launchIOSDevice.dependsOn build createIPA.dependsOn build eclipse.project { name = appName + "-ios" natures 'org.robovm.eclipse.RoboVMNature' } dependencies { ${joinDependencies(dependencies)}} """ }
src/main/kotlin/com/github/czyzby/setup/data/platforms/iOS.kt
579885962
package com.infinum.dbinspector.ui.shared.delegates import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import com.infinum.dbinspector.ui.Presentation import com.infinum.dbinspector.ui.shared.base.lifecycle.LifecycleConnection import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty internal class LifecycleConnectionDelegate( private val owner: LifecycleOwner, val lifecycleConnectionFactory: (Bundle?) -> LifecycleConnection ) : ReadOnlyProperty<LifecycleOwner, LifecycleConnection>, LifecycleObserver { private var connection: LifecycleConnection? = null override fun getValue(thisRef: LifecycleOwner, property: KProperty<*>): LifecycleConnection { val existingConnection = connection return when { existingConnection != null -> existingConnection else -> { if ( owner .lifecycle .currentState .isAtLeast(Lifecycle.State.INITIALIZED).not() ) { error("Owner has not passed created yet.") } val extras = when (thisRef) { is Fragment -> (thisRef as? Fragment)?.activity?.intent?.extras is AppCompatActivity -> thisRef.intent?.extras else -> null } lifecycleConnectionFactory(extras).also { this.connection = it } } } } } internal fun LifecycleOwner.lifecycleConnection( lifecycleConnectionFactory: (Bundle?) -> LifecycleConnection = { LifecycleConnection( databaseName = it?.getString(Presentation.Constants.Keys.DATABASE_NAME), databasePath = it?.getString(Presentation.Constants.Keys.DATABASE_PATH), schemaName = it?.getString(Presentation.Constants.Keys.SCHEMA_NAME) ) } ) = LifecycleConnectionDelegate(this, lifecycleConnectionFactory)
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/delegates/LifecycleConnectionDelegate.kt
2205829858
package fi.evident.apina.java.reader import fi.evident.apina.java.model.JavaClass interface ClassDataLoader { val classNames: Set<String> fun loadClass(name: String): JavaClass? }
apina-core/src/main/kotlin/fi/evident/apina/java/reader/ClassDataLoader.kt
3397600351
package info.jdavid.ok.server import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.nio.aAccept import kotlinx.coroutines.experimental.runBlocking import java.net.InetAddress import java.net.InetSocketAddress import java.net.StandardSocketOptions import java.nio.channels.AlreadyBoundException import java.nio.channels.AsynchronousServerSocketChannel import java.nio.channels.AsynchronousSocketChannel import kotlin.concurrent.thread import info.jdavid.ok.server.Logger.logger import kotlinx.coroutines.experimental.nio.aRead import okio.BufferedSource import okio.ByteString import java.io.IOException import java.net.SocketTimeoutException import java.nio.charset.Charset import java.util.concurrent.TimeUnit class CoroutineDispatcher : Dispatcher<AsynchronousServerSocketChannel>() { override fun initSockets(insecurePort: Int, securePort: Int, https: Https?, address: InetAddress?) { if (insecurePort > 0) { val insecureSocket = AsynchronousServerSocketChannel.open() insecureSocket.setOption(StandardSocketOptions.SO_REUSEADDR, true) try { insecureSocket.bind(InetSocketAddress(address, insecurePort)) } catch (e: AlreadyBoundException) { logger.warn("Could not bind to port ${insecurePort}.", e) } this.insecureSocket = insecureSocket } if (securePort > 0 && https != null) { val secureSocket = AsynchronousServerSocketChannel.open() secureSocket.setOption(StandardSocketOptions.SO_REUSEADDR, true) try { secureSocket.bind(InetSocketAddress(address, securePort)) } catch (e: AlreadyBoundException) { logger.warn("Could not bind to port ${securePort}.", e) } this.secureSocket = secureSocket } } override fun start() {} override fun shutdown() {} override fun loop(socket: AsynchronousServerSocketChannel?, secure: Boolean, insecureOnly: Boolean, https: Https?, hostname: String?, maxRequestSize: Long, keepAliveStrategy: KeepAliveStrategy, requestHandler: RequestHandler) { thread { if (socket != null) { runBlocking { socket.use { while (true) { try { val channel = socket.aAccept() launch(context) { channel.use { Request(channel, secure, insecureOnly, https, hostname, maxRequestSize, keepAliveStrategy, requestHandler).serve() } } } catch (e: IOException) { if (!socket.isOpen()) break logger.warn(secure.ifElse("HTTPS", "HTTP"), e) } } } } } }.start() } private fun <T> Boolean.ifElse(ifValue: T, elseValue: T): T { return if (this) ifValue else elseValue } private class Request(private val channel: AsynchronousSocketChannel, private val secure: Boolean, private val insecureOnly: Boolean, private val https: Https?, private val hostname: String?, private val maxRequestSize: Long, private val keepAliveStrategy: KeepAliveStrategy, private val requestHandler: RequestHandler) { suspend fun serve() { if (secure) { assert(https != null) } else { serveHttp1(channel, false, insecureOnly) } } private fun useSocket(reuse: Int, strategy: KeepAliveStrategy): Boolean { val timeout = strategy.timeout(reuse) if (timeout <= 0) { return reuse == 0 } else { return true } } suspend fun serveHttp1(channel: AsynchronousSocketChannel, secure: Boolean, insecureOnly: Boolean) { try { val clientIp = (channel.remoteAddress as InetSocketAddress).address.hostAddress var reuseCounter = 0 while (useSocket(reuseCounter++, keepAliveStrategy)) { var availableRequestSize = maxRequestSize // todo } } catch (ignore: SocketTimeoutException) {} catch (e: Exception) { logger.warn(e.message, e) } } } private val ASCII = Charset.forName("ASCII") private fun crlf(input: BufferedSource, limit: Long): Long { var index: Long = 0L while (true) { index = input.indexOf('\r'.toByte(), index, limit) if (index == -1L) return -1L if (input.indexOf('\n'.toByte(), index + 1L, index + 2L) != -1L) return index ++index } } @Throws(IOException::class) private fun readRequestLine(input: BufferedSource): ByteString? { val index = crlf(input, 4096) if (index == -1L) return null val requestLine = input.readByteString(index) input.skip(2L) return requestLine } }
src/coroutines/kotlin/info/jdavid/ok/server/CoroutineDispatcher.kt
2142257965
package io.gitlab.arturbosch.detekt.formatting import com.pinterest.ktlint.core.EditorConfig import com.pinterest.ktlint.core.KtLint import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.CorrectableCodeSmell import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Location import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.SingleAssign import io.gitlab.arturbosch.detekt.api.SourceLocation import io.gitlab.arturbosch.detekt.api.TextLocation import io.gitlab.arturbosch.detekt.api.internal.absolutePath import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.lang.FileASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.endOffset /** * Rule to detect formatting violations. */ abstract class FormattingRule(config: Config) : Rule(config) { abstract val wrapping: com.pinterest.ktlint.core.Rule protected fun issueFor(description: String) = Issue(javaClass.simpleName, Severity.Style, description, Debt.FIVE_MINS) /** * Should the android style guide be enforced? * This property is read from the ruleSet config. */ protected val isAndroid get() = ruleSetConfig.valueOrDefault("android", false) private var positionByOffset: (offset: Int) -> Pair<Int, Int> by SingleAssign() private var root: KtFile by SingleAssign() override fun visit(root: KtFile) { this.root = root root.node.putUserData(KtLint.ANDROID_USER_DATA_KEY, isAndroid) positionByOffset = calculateLineColByOffset(normalizeText(root.text)) editorConfigUpdater()?.let { updateFunc -> val oldEditorConfig = root.node.getUserData(KtLint.EDITOR_CONFIG_USER_DATA_KEY) root.node.putUserData(KtLint.EDITOR_CONFIG_USER_DATA_KEY, updateFunc(oldEditorConfig)) } root.node.putUserData(KtLint.FILE_PATH_USER_DATA_KEY, root.absolutePath()) } open fun editorConfigUpdater(): ((oldEditorConfig: EditorConfig?) -> EditorConfig)? = null fun apply(node: ASTNode) { if (ruleShouldOnlyRunOnFileNode(node)) { return } wrapping.visit(node, autoCorrect) { offset, message, _ -> val (line, column) = positionByOffset(offset) val location = Location( SourceLocation(line, column), TextLocation(node.startOffset, node.psi.endOffset), "($line, $column)", root.originalFilePath() ?: root.containingFile.name ) // Nodes reported by 'NoConsecutiveBlankLines' are dangling whitespace nodes which means they have // no direct parent which we can use to get the containing file needed to baseline or suppress findings. // For these reasons we do not report a KtElement which may lead to crashes when postprocessing it // e.g. reports (html), baseline etc. val packageName = root.packageFqName.asString() .takeIf { it.isNotEmpty() } ?.plus(".") ?: "" val entity = Entity("", "", "$packageName${root.name}:$line", location, root) report(CorrectableCodeSmell(issue, entity, message, autoCorrectEnabled = autoCorrect)) } } private fun ruleShouldOnlyRunOnFileNode(node: ASTNode) = wrapping is com.pinterest.ktlint.core.Rule.Modifier.RestrictToRoot && node !is FileASTNode private fun PsiElement.originalFilePath() = (this.containingFile.viewProvider.virtualFile as? LightVirtualFile)?.originalFile?.name }
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/FormattingRule.kt
3335589115
/* * Copyright 2020 Alex Almeida Tavella * * 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 br.com.moov.moviedetails.viewmodel import androidx.lifecycle.ViewModel import br.com.core.android.BaseViewModel import br.com.core.android.UiEvent import br.com.core.android.UiModel import br.com.core.android.ViewModelKey import br.com.moov.bookmark.movie.BookmarkMovieUseCase import br.com.moov.bookmark.movie.UnBookmarkMovieUseCase import br.com.moov.moviedetails.di.MovieDetailScope import br.com.moov.moviedetails.domain.GetMovieDetailUseCase import br.com.moov.moviedetails.domain.MovieDetail import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject private const val ERROR_MESSAGE_DEFAULT = "An error has occurred, please try again later" @ContributesMultibinding(MovieDetailScope::class, ViewModel::class) @ViewModelKey(MovieDetailViewModel::class) class MovieDetailViewModel @Inject constructor( private val getMovieDetail: GetMovieDetailUseCase, private val bookmarkMovie: BookmarkMovieUseCase, private val unBookmarkMovie: UnBookmarkMovieUseCase ) : BaseViewModel<MovieDetailUiEvent, MovieDetailUiModel>() { override suspend fun processUiEvent(uiEvent: MovieDetailUiEvent) { when (uiEvent) { is MovieDetailUiEvent.EnterScreen -> { handleEnterScreen(uiEvent) } is MovieDetailUiEvent.MovieFavoritedUiEvent -> { handleMovieFavorited(uiEvent) } } } private suspend fun handleEnterScreen(uiEvent: MovieDetailUiEvent.EnterScreen) { emitUiModel(MovieDetailUiModel(loading = true)) val result = getMovieDetail(uiEvent.movieId) emitUiModel( MovieDetailUiModel( loading = false, movie = result.getOrNull(), error = getMovieDetailsErrorMessage() ) ) } private fun getMovieDetailsErrorMessage(): Throwable { return Exception(ERROR_MESSAGE_DEFAULT) } private suspend fun handleMovieFavorited(uiEvent: MovieDetailUiEvent.MovieFavoritedUiEvent) { val result = if (uiEvent.favorited) { bookmarkMovie(uiEvent.movie.id) .map { uiEvent.movie.copy(isBookmarked = true) } .mapError { bookmarkFailErrorMessage() } } else { unBookmarkMovie(uiEvent.movie.id) .map { uiEvent.movie.copy(isBookmarked = false) } .mapError { unBookmarkFailErrorMessage() } } emitUiModel( MovieDetailUiModel( movie = result.getOrNull(), error = result.errorOrNull() ) ) } private fun bookmarkFailErrorMessage(): Throwable { return Exception(ERROR_MESSAGE_DEFAULT) } private fun unBookmarkFailErrorMessage(): Throwable { return Exception(ERROR_MESSAGE_DEFAULT) } } class MovieDetailUiModel( val loading: Boolean = false, val movie: MovieDetail? = null, error: Throwable? = null ) : UiModel(error) sealed class MovieDetailUiEvent : UiEvent() { class EnterScreen(val movieId: Int) : MovieDetailUiEvent() data class MovieFavoritedUiEvent( val movie: MovieDetail, val favorited: Boolean ) : MovieDetailUiEvent() }
feature/movie-details/impl/src/main/java/br/com/moov/moviedetails/viewmodel/MovieDetailViewModel.kt
2300448278
package com.seventh_root.guildfordgamejam.system import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import com.seventh_root.guildfordgamejam.component.RadiusComponent import com.seventh_root.guildfordgamejam.component.RadiusScalingComponent import com.seventh_root.guildfordgamejam.component.radius import com.seventh_root.guildfordgamejam.component.radiusScaling class RadiusScalingSystem: IteratingSystem(Family.all(RadiusScalingComponent::class.java, RadiusComponent::class.java).get()) { override fun processEntity(entity: Entity, deltaTime: Float) { radius.get(entity).radius += deltaTime * radiusScaling.get(entity).rate } }
core/src/main/kotlin/com/seventh_root/guildfordgamejam/system/RadiusScalingSystem.kt
2357438261
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.toshi.R import com.toshi.view.adapter.viewholder.TokenFooterViewHolder class TokenFooterAdapter : BaseCompoundableAdapter<TokenFooterViewHolder, Int>() { init { setItemList(listOf(1)) } override fun compoundableBindViewHolder(viewHolder: RecyclerView.ViewHolder, adapterIndex: Int) { val typedHolder = viewHolder as TokenFooterViewHolder onBindViewHolder(typedHolder, adapterIndex) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TokenFooterViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item__token_footer, parent, false) return TokenFooterViewHolder(view) } override fun onBindViewHolder(holder: TokenFooterViewHolder, position: Int) {} }
app/src/main/java/com/toshi/view/adapter/TokenFooterAdapter.kt
672164767
package com.recurly.androidsdk.presentation.view import android.content.Context import android.content.res.ColorStateList import android.graphics.Typeface import android.text.Editable import android.text.InputFilter import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import com.recurly.androidsdk.R import com.recurly.androidsdk.data.model.CreditCardData import com.recurly.androidsdk.databinding.RecurlyCvvCodeBinding import com.recurly.androidsdk.domain.RecurlyDataFormatter import com.recurly.androidsdk.domain.RecurlyInputValidator class RecurlyCVV @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private var textColor: Int private var errorTextColor: Int private var hintColor: Int private var boxColor: Int private var errorBoxColor: Int private var focusedBoxColor: Int private var correctCVVInput = true private val maxCVVLength: Int = 3 private var binding: RecurlyCvvCodeBinding = RecurlyCvvCodeBinding.inflate(LayoutInflater.from(context), this) /** * All the color are initialized as Int, this is to make ir easier to handle the texts colors change */ init { layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) textColor = ContextCompat.getColor(context, R.color.recurly_black) errorTextColor = ContextCompat.getColor(context, R.color.recurly_error_red) boxColor = ContextCompat.getColor(context, R.color.recurly_gray_stroke) errorBoxColor = ContextCompat.getColor(context, R.color.recurly_error_red_blur) focusedBoxColor = ContextCompat.getColor(context, R.color.recurly_focused_blue) hintColor = ContextCompat.getColor(context, R.color.recurly_gray_stroke) cvvInputValidator() } /** * This fun changes the placeholder text according to the parameter received * @param cvvPlaceholder Placeholder text for cvv code field */ fun setPlaceholder(cvvPlaceholder: String) { if (!cvvPlaceholder.trim().isEmpty()) binding.recurlyTextInputLayoutIndividualCvvCode.hint = cvvPlaceholder } /** * This fun changes the placeholder color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setPlaceholderColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) { hintColor = color var colorState: ColorStateList = RecurlyInputValidator.getColorState(color) binding.recurlyTextInputLayoutIndividualCvvCode.placeholderTextColor = colorState } } /** * This fun changes the text color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setTextColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) { textColor = color binding.recurlyTextInputEditIndividualCvvCode.setTextColor(color) } } /** * This fun changes the text color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setTextErrorColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) errorTextColor = color } /** * This fun changes the font of the input field according to the parameter received * @param newFont non null Typeface * @param style style as int */ fun setFont(newFont: Typeface, style: Int) { binding.recurlyTextInputEditIndividualCvvCode.setTypeface(newFont, style) binding.recurlyTextInputLayoutIndividualCvvCode.typeface = newFont } /** * This fun validates if the input is complete and is valid, this means it follows a cvv code digits length * @return true if the input is correctly filled, false if it is not */ fun validateData(): Boolean { correctCVVInput = binding.recurlyTextInputEditIndividualCvvCode.text.toString().length == maxCVVLength changeColors() return correctCVVInput } /** * This fun will highlight the CVV as it have an error, you can use this * for tokenization validations or if you need to highlight this field with an error */ fun setCvvError(){ correctCVVInput = false changeColors() } /** * This fun changes the text color and the field highlight according at if it is correct or not */ private fun changeColors() { if (correctCVVInput) { binding.recurlyTextInputLayoutIndividualCvvCode.error = null binding.recurlyTextInputEditIndividualCvvCode.setTextColor(textColor) } else { binding.recurlyTextInputLayoutIndividualCvvCode.error = " " binding.recurlyTextInputEditIndividualCvvCode.setTextColor( errorTextColor ) } } /** *This is an internal fun that validates the input as it is introduced, it is separated in two parts: * If it is focused or not, and if it has text changes. * * When it has text changes calls to different input validators from RecurlyInputValidator * and according to the response of the input validator it replaces the text and * changes text color according if has errors or not * * When it changes the focus of the view it validates if the field is correctly filled, and then * saves the input data */ private fun cvvInputValidator() { binding.recurlyTextInputEditIndividualCvvCode.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { binding.recurlyTextInputEditIndividualCvvCode.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(CreditCardData.getCvvLength())) binding.recurlyTextInputLayoutIndividualCvvCode.error = null binding.recurlyTextInputEditIndividualCvvCode.setTextColor(textColor) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { if (s != null) { if (s.toString().isNotEmpty()) { val oldValue = s.toString() val formattedCVV = RecurlyInputValidator.regexSpecialCharacters( s.toString(), "0-9" ) binding.recurlyTextInputEditIndividualCvvCode.removeTextChangedListener(this) s.replace(0, oldValue.length, formattedCVV) binding.recurlyTextInputEditIndividualCvvCode.addTextChangedListener(this) correctCVVInput = formattedCVV.length == CreditCardData.getCvvLength() CreditCardData.setCvvCode( RecurlyDataFormatter.getCvvCode( formattedCVV, correctCVVInput ) ) } else { correctCVVInput = true changeColors() } } } }) binding.recurlyTextInputEditIndividualCvvCode.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { CreditCardData.setCvvCode( RecurlyDataFormatter.getCvvCode( binding.recurlyTextInputEditIndividualCvvCode.text.toString(), correctCVVInput ) ) changeColors() } else { binding.recurlyTextInputEditIndividualCvvCode.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(CreditCardData.getCvvLength())) } } } }
AndroidSdk/src/main/java/com/recurly/androidsdk/presentation/view/RecurlyCVV.kt
2970670785
package de.westnordost.streetcomplete.user import android.animation.ValueAnimator import android.content.Intent import android.os.Bundle import android.view.View import android.view.animation.DecelerateInterpolator import androidx.core.animation.doOnStart import androidx.core.net.toUri import androidx.core.view.isInvisible import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType import de.westnordost.streetcomplete.data.quest.QuestType import de.westnordost.streetcomplete.databinding.FragmentQuestTypeInfoDialogBinding import de.westnordost.streetcomplete.ktx.tryStartActivity import de.westnordost.streetcomplete.ktx.viewBinding import de.westnordost.streetcomplete.view.CircularOutlineProvider import kotlin.math.min import kotlin.math.pow /** Shows the details for a certain quest type as a fake-dialog. */ class QuestTypeInfoFragment : AbstractInfoFakeDialogFragment(R.layout.fragment_quest_type_info_dialog) { private val binding by viewBinding(FragmentQuestTypeInfoDialogBinding::bind) override val dialogAndBackgroundContainer get() = binding.dialogAndBackgroundContainer override val dialogBackground get() = binding.dialogBackground override val dialogContentContainer get() = binding.dialogContentContainer override val dialogBubbleBackground get() = binding.dialogBubbleBackground override val titleView get() = binding.titleView // need to keep the animators here to be able to clear them on cancel private var counterAnimation: ValueAnimator? = null /* ---------------------------------------- Lifecycle --------------------------------------- */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.titleView.outlineProvider = CircularOutlineProvider } override fun onDestroy() { super.onDestroy() counterAnimation?.cancel() counterAnimation = null } /* ---------------------------------------- Interface --------------------------------------- */ fun show(questType: QuestType<*>, questCount: Int, questBubbleView: View) { if (!show(questBubbleView)) return binding.titleView.setImageResource(questType.icon) binding.questTitleText.text = resources.getString(questType.title, *Array(10){"…"}) binding.solvedQuestsText.text = "" val scale = (0.4 + min( questCount / 100.0, 1.0)*0.6).toFloat() binding.solvedQuestsContainer.visibility = View.INVISIBLE binding.solvedQuestsContainer.scaleX = scale binding.solvedQuestsContainer.scaleY = scale binding.solvedQuestsContainer.setOnClickListener { counterAnimation?.end() } binding.wikiLinkButton.isInvisible = questType !is OsmElementQuestType || questType.wikiLink == null if (questType is OsmElementQuestType && questType.wikiLink != null) { binding.wikiLinkButton.setOnClickListener { openUrl("https://wiki.openstreetmap.org/wiki/${questType.wikiLink}") } } counterAnimation?.cancel() val anim = ValueAnimator.ofInt(0, questCount) anim.doOnStart { binding.solvedQuestsContainer.visibility = View.VISIBLE } anim.duration = 300 + (questCount * 500.0).pow(0.6).toLong() anim.addUpdateListener { binding.solvedQuestsText.text = it.animatedValue.toString() } anim.interpolator = DecelerateInterpolator() anim.startDelay = ANIMATION_TIME_IN_MS anim.start() counterAnimation = anim } private fun openUrl(url: String): Boolean { val intent = Intent(Intent.ACTION_VIEW, url.toUri()) return tryStartActivity(intent) } }
app/src/main/java/de/westnordost/streetcomplete/user/QuestTypeInfoFragment.kt
3243424712
package org.wordpress.android.fluxc import com.google.gson.Gson object JsonLoaderUtils { fun <T> String.jsonFileAs(clazz: Class<T>) = UnitTestUtils.getStringFromResourceFile( this@JsonLoaderUtils::class.java, this )?.let { Gson().fromJson(it, clazz) } }
example/src/test/java/org/wordpress/android/fluxc/JsonLoaderUtils.kt
3231210665
package gargoyle.ct.util.resource.internal import java.io.File import java.io.IOException import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption class TempLocalResource : ClasspathResource { private constructor(loader: ClassLoader, base: ClasspathResource, location: String) : super(loader, base, location) constructor(location: String) : super(location) override fun createResource( base: VirtualResource<ClasspathResource>?, location: String ): VirtualResource<ClasspathResource> { val loader = getLoader(base) val resource: ClasspathResource = base?.let { ClasspathResource(loader, it as ClasspathResource, location) } ?: ClasspathResource(location) if (!resource.exists()) { return TempLocalResource(location) } try { resource.inputStream.use { stream -> val tempFile = File.createTempFile(baseName, ".$extension") Files.copy(stream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING) tempFile.deleteOnExit() return TempLocalResource(loader, resource, tempFile.path) } } catch (e: IOException) { throw IllegalArgumentException(location, e) } } override fun toURL(): URL = File(location).toURI().toURL() override fun exists(): Boolean = try { exists(toURL()) } catch (ex: Exception) { false } fun toFile(): File = File(toURL().path.substring(1)) }
util/src/main/kotlin/gargoyle/ct/util/resource/internal/TempLocalResource.kt
3469054097
package org.kantega.niagara.json import org.kantega.niagara.data.* data class JsonMapper<A>(val encoder:JsonEncoder<A>, val decoder: JsonDecoder<A>){ inline fun <reified B> xmap(crossinline f:(A)->B, noinline g:(B)->A):JsonMapper<B> = JsonMapper( encoder.comap(g), decoder.map(f) ) } data class ObjectMapperBuilder<OBJ,C,REST>(val encoder:JsonObjectBuilder<OBJ,REST>, val decoder: JsonDecoder<C>) fun <A> ObjectMapperBuilder<A,A,*>.build() = JsonMapper(this.encoder,this.decoder) inline fun <OBJ,reified FIRST,reified REST,TAIL:HList> ObjectMapperBuilder<OBJ,(FIRST)->REST,HCons<FIRST,TAIL>> .field(name:String,endec:JsonMapper<FIRST>):ObjectMapperBuilder<OBJ,REST,TAIL> = ObjectMapperBuilder(encoder.field(name,endec.encoder),decoder.field(name,endec.decoder)) fun <A> mapper(encoder:JsonEncoder<A>, decoder: JsonDecoder<A>) : JsonMapper<A> = JsonMapper(encoder,decoder) val mapString = JsonMapper(encodeString, decodeString) val mapInt = JsonMapper(encodeInt, decodeInt) val mapLong = JsonMapper(encodeLong, decodeLong) val mapDouble = JsonMapper(encodeDouble, decodeDouble) val mapBool = JsonMapper(encodeBool, decodeBool) fun <A> mapArray(elemEndec:JsonMapper<A>) = JsonMapper(encodeArray(elemEndec.encoder), decodeArray(elemEndec.decoder)) fun <A, B, C, D, E, F, G, H, I, J,T> mapObject(constructor: (A, B, C, D, E, F, G, H, I, J) -> T, destructor:(T)->HList10<A,B,C,D,E,F,G,H,I,J>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, D, E, F, G, H, I, T> mapObject(constructor: (A, B, C, D, E, F, G, H, I) -> T, destructor:(T)->HList9<A,B,C,D,E,F,G,H,I>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, D, E, F, G, H, T> mapObject(constructor: (A, B, C, D, E, F, G, H) -> T, destructor:(T)->HList8<A,B,C,D,E,F,G,H>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, D, E, F, G, T> mapObject(constructor: (A, B, C, D, E, F, G) -> T, destructor:(T)->HList7<A,B,C,D,E,F,G>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, D, E, F, T> mapObject(constructor: (A, B, C, D, E, F) -> T, destructor:(T)->HList6<A,B,C,D,E,F>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, D, E,T> mapObject(constructor: (A, B, C, D, E) -> T, destructor:(T)->HList5<A,B,C,D,E>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, D, T> mapObject(constructor: (A, B, C, D) -> T, destructor:(T)->HList4<A,B,C,D>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B, C, T> mapObject(constructor: (A, B, C) -> T, destructor:(T)->HList3<A,B,C>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, B,T> mapObject(constructor: (A, B) -> T, destructor:(T)->HList2<A,B>) = ObjectMapperBuilder(encode(destructor),decode(constructor.curried())) fun <A, T> mapObject(constructor: (A) -> T, destructor:(T)->HList1<A>) = ObjectMapperBuilder(encode(destructor),decode(constructor))
niagara-json/src/main/kotlin/org/kantega/niagara/json/JsonMapper.kt
1108659407
package nos2jdbc.tutorial.kotlinspring.service import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import nos2jdbc.tutorial.kotlinspring.entity.Member import nos2jdbc.tutorial.kotlinspring.gen.service.MemberServiceBase import nos2jdbc.tutorial.kotlinspring.gen.names.MemberNames.* import org.seasar.extension.jdbc.operation.Operations.* @Service @Transactional class MemberService(): MemberServiceBase() { public fun findAllWithClubs(): List<Member> { return select() .leftOuterJoin(clubMemberRelList()) .leftOuterJoin(clubMemberRelList().club()) .getResultList(); } public fun getByOrder(mo: Int): Member { return select().orderBy(asc(id())).offset(mo).limit(1).getSingleResult(); } }
nos2jdbc-tutorial-kotlin-spring/src/main/kotlin/nos2jdbc/tutorial/kotlinspring/service/MemberService.kt
4107177965
/* * 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.daemon.testing import com.google.protobuf.ByteString import com.google.protobuf.kotlin.toByteString import kotlin.random.Random import org.wfanet.measurement.common.crypto.hashSha256 import org.wfanet.measurement.internal.duchy.externalRequisitionKey import org.wfanet.measurement.internal.duchy.requisitionDetails import org.wfanet.measurement.internal.duchy.requisitionMetadata import org.wfanet.measurement.system.v1alpha.ComputationParticipantKey import org.wfanet.measurement.system.v1alpha.Requisition import org.wfanet.measurement.system.v1alpha.RequisitionKey import org.wfanet.measurement.system.v1alpha.requisition data class TestRequisition( val externalRequisitionId: String, val serializedMeasurementSpecProvider: () -> ByteString ) { val requisitionSpecHash: ByteString = Random.Default.nextBytes(32).toByteString() val nonce: Long = Random.Default.nextLong() val nonceHash = hashSha256(nonce) val requisitionFingerprint get() = hashSha256(serializedMeasurementSpecProvider().concat(requisitionSpecHash)) fun toSystemRequisition( globalId: String, state: Requisition.State, externalDuchyId: String = "" ) = requisition { name = RequisitionKey(globalId, externalRequisitionId).toName() requisitionSpecHash = this@TestRequisition.requisitionSpecHash nonceHash = this@TestRequisition.nonceHash this.state = state if (state == Requisition.State.FULFILLED) { nonce = this@TestRequisition.nonce fulfillingComputationParticipant = ComputationParticipantKey(globalId, externalDuchyId).toName() } } fun toRequisitionMetadata(state: Requisition.State, externalDuchyId: String = "") = requisitionMetadata { externalKey = externalRequisitionKey { externalRequisitionId = this@TestRequisition.externalRequisitionId requisitionFingerprint = this@TestRequisition.requisitionFingerprint } details = requisitionDetails { nonceHash = this@TestRequisition.nonceHash if (state == Requisition.State.FULFILLED) { nonce = this@TestRequisition.nonce externalFulfillingDuchyId = externalDuchyId } } } }
src/main/kotlin/org/wfanet/measurement/duchy/daemon/testing/TestRequisition.kt
3905995421
package com.esafirm.sample import android.widget.ScrollView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.intent.Intents import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.filters.LargeTest import androidx.test.rule.ActivityTestRule import androidx.test.rule.GrantPermissionRule import androidx.test.runner.AndroidJUnit4 import com.esafirm.sample.matchers.hasDrawable import com.schibsted.spain.barista.intents.BaristaIntents.mockAndroidCamera import com.schibsted.spain.barista.interaction.BaristaClickInteractions.clickOn import org.hamcrest.Matchers.allOf import org.hamcrest.core.IsInstanceOf import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class CameraOnlyTest { @Rule @JvmField var testRule = ActivityTestRule(MainActivity::class.java) @Rule @JvmField var grantPermissionRule = GrantPermissionRule.grant( "android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE" ) @Test fun cameraOnlyTestTwo() { Intents.init() mockAndroidCamera() clickOn(R.id.button_camera) Intents.release() clickOn(R.id.text_view) val imageView = onView( allOf(ViewMatchers.withParent(allOf(withId(R.id.container), ViewMatchers.withParent(IsInstanceOf.instanceOf(ScrollView::class.java)))), isDisplayed())) imageView.check(ViewAssertions.matches(isDisplayed())) imageView.check(ViewAssertions.matches(hasDrawable())) } }
sample/src/androidTest/java/com/esafirm/sample/CameraOnlyTest.kt
2987101825
package nl.hannahsten.texifyidea.run.latex.logtab import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessListener import com.intellij.execution.process.ProcessOutputType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexLogMessage import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexOutputListener import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.DUPLICATE_WHITESPACE import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.LINE_WIDTH import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.PACKAGE_WARNING_CONTINUATION import nl.hannahsten.texifyidea.run.latex.logtab.ui.LatexCompileMessageTreeView import nl.hannahsten.texifyidea.util.files.findFile import nl.hannahsten.texifyidea.util.remove import nl.hannahsten.texifyidea.util.removeAll import org.apache.commons.collections.Buffer import org.apache.commons.collections.BufferUtils import org.apache.commons.collections.buffer.CircularFifoBuffer class LatexOutputListener( val project: Project, val mainFile: VirtualFile?, val messageList: MutableList<LatexLogMessage>, val bibMessageList: MutableList<BibtexLogMessage>, val treeView: LatexCompileMessageTreeView ) : ProcessListener { // This should probably be located somewhere else companion object { /** * Returns true if firstLine is most likely the last line of the message. */ fun isLineEndOfMessage(secondLine: String, firstLine: String): Boolean { return firstLine.remove("\n").length < LINE_WIDTH - 1 && // Indent of LaTeX Warning/Error messages !secondLine.startsWith(" ") && // Package warning/error continuation. !PACKAGE_WARNING_CONTINUATION.toRegex().containsMatchIn(secondLine) && // Assume the undefined control sequence always continues on the next line !firstLine.trim().endsWith("Undefined control sequence.") && // Case of the first line pointing out something interesting on the second line !(firstLine.endsWith(":") && secondLine.startsWith(" ")) } } /** * Window of the last two log output messages. */ val window: Buffer = BufferUtils.synchronizedBuffer(CircularFifoBuffer(2)) // For latexmk, collect the bibtex/biber messages in a separate list, so // we don't lose them when resetting on each new (pdfla)tex run. private var isCollectingBib = false private val bibtexOutputListener = BibtexOutputListener(project, mainFile, bibMessageList, treeView) var isCollectingMessage = false var currentLogMessage: LatexLogMessage? = null // Stack with the filenames, where the first is the current file. private var fileStack = LatexFileStack() private var collectingOutputLine: String = "" override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { if (outputType !is ProcessOutputType) return // Latexmk outputs on stderr, which interleaves with the pdflatex/bibtex/etc output on stdout if (outputType.isStderr) return // The following code wants complete lines as input. // However, this function onTextAvailable will simply give us text when it's available, // which may be only part of a line. // Since it does always include newlines to designate linebreaks, we simply wait here until // we have the full line collected. // It looks like we never get a line ending in the middle of even.text, but not completely sure about that. if (event.text.endsWith("\n").not()) { collectingOutputLine += event.text return } else { val collectedLine = collectingOutputLine + event.text collectingOutputLine = "" // We look for specific strings in the log output for which we know it was probably an error message // (it might be that it is actually not, since anything can be typed to the LaTeX output log, but we ignore // that for now and assume the log is of reasonable format). // Standard log output is only 79 characters wide, meaning these strings might occur over two lines. // We assume the match tokens will always fit over two lines. // Therefore, we maintain a window of two log output lines to detect the error messages. // // We assume that if the first line of the error/warning is exactly the maximum line width, it will continue // on the next line. This may not be accurate, but there is no way of distinguishing this. // Newlines are important to check when message end. Keep. processNewText(collectedLine) } } fun processNewText(newText: String) { if (isCollectingBib) { // Don't chunk bibtex lines, as they don't usually break by themselves and they are often not long anyway bibtexOutputListener.processNewText(newText) } else { newText.chunked(LINE_WIDTH).forEach { processNewTextLatex(it) } } resetIfNeeded(newText) } private fun processNewTextLatex(newText: String) { window.add(newText) // No idea how we could possibly get an IndexOutOfBoundsException on the buffer, but we did val text = try { window.joinToString(separator = "") } catch (e: IndexOutOfBoundsException) { return } // Check if we are currently in the process of collecting the full message of a matched message of interest if (isCollectingMessage) { collectMessageLine(text, newText) fileStack.update(newText) } else { // Skip line if it is irrelevant. if (LatexLogMessageExtractor.skip(window.firstOrNull() as? String)) { // The first line might be irrelevant, but the new text could // contain useful information about the file stack. fileStack.update(newText) return } // Find an error message or warning in the current text. val logMessage = LatexLogMessageExtractor.findMessage(text.removeAll("\n", "\r"), newText.removeAll("\n"), fileStack.peek()) // Check for potential file opens/closes, modify the stack accordingly. fileStack.update(newText) // Finally add the message to the log, or continue collecting this message when necessary. addOrCollectMessage(text, newText, logMessage ?: return) } } private fun findProjectFileRelativeToMain(fileName: String?): VirtualFile? = mainFile?.parent?.findFile(fileName ?: mainFile.name, setOf("tex")) /** * Reset the tree view and the message list when starting a new run. (latexmk) */ private fun resetIfNeeded(newText: String) { """Latexmk: applying rule '(?<program>\w+)""".toRegex().apply { val result = find(newText) ?: return@apply if (result.groups["program"]?.value in setOf("biber", "bibtex")) { isCollectingBib = true } else { isCollectingBib = false treeView.errorViewStructure.clear() messageList.clear() // Re-add the bib messages to the tree. bibMessageList.forEach { bibtexOutputListener.addBibMessageToTree(it) } } } } /** * Keep collecting the message if necessary, otherwise add it to the log. */ private fun addOrCollectMessage(text: String, newText: String, logMessage: LatexLogMessage) { logMessage.apply { if (message.isEmpty()) return if (!isLineEndOfMessage(newText, logMessage.message) || text.removeSuffix(newText).length >= LINE_WIDTH) { // Keep on collecting output for this message currentLogMessage = logMessage isCollectingMessage = true } else { val file = findProjectFileRelativeToMain(fileName) if (messageList.isEmpty() || !messageList.contains(logMessage)) { // Use original filename, especially for tests to work (which cannot find the real file) // Trim message here instead of earlier in order to keep spaces in case we needed to continue // collecting the message and the spaces were actually relevant addMessageToLog(LatexLogMessage(message.trim(), fileName, line, type), file) } } } } /** * Add the current/new message to the log if it does not continue on the * next line. */ private fun collectMessageLine(text: String, newText: String, logMessage: LatexLogMessage? = null) { // Check if newText is interesting before appending it to the message if (currentLogMessage?.message?.endsWith(newText.trim()) == false && !isLineEndOfMessage(newText, text.removeSuffix(newText))) { // Append new text val message = logMessage ?: currentLogMessage!! // Assume that lines that end prematurely do need an extra space to be inserted, like LaTeX and package // warnings with manual newlines, unlike 80-char forced linebreaks which should not have a space inserted val newTextTrimmed = if (text.removeSuffix(newText).length < LINE_WIDTH) " ${newText.trim()}" else newText.trim() // LaTeX Warning: is replaced here because this method is also run when a message is added, // and the above check needs to return false so we can't replace this in the WarningHandler var newMessage = (message.message + newTextTrimmed).replace("LaTeX Warning: ", "") .replace(PACKAGE_WARNING_CONTINUATION.toRegex(), "") .replace(DUPLICATE_WHITESPACE.toRegex(), " ") .replace(""". l.\d+ """.toRegex(), " ") // Continuation of Undefined control sequence // The 'on input line <line>' may be a lot of lines after the 'LaTeX Warning:', thus the original regex may // not have caught it. Try to catch the line number here. var line = message.line if (line == -1) { LatexLogMagicRegex.REPORTED_ON_LINE_REGEX.find(newMessage)?.apply { line = groups["line"]?.value?.toInt() ?: -1 newMessage = newMessage.removeAll(this.value).trim() } } currentLogMessage = LatexLogMessage(newMessage, message.fileName, line, message.type) } else { isCollectingMessage = false addMessageToLog(currentLogMessage!!) currentLogMessage = null } } private fun addMessageToLog(logMessage: LatexLogMessage, givenFile: VirtualFile? = null) { // Don't log the same message twice if (!messageList.contains(logMessage)) { val file = givenFile ?: findProjectFileRelativeToMain(logMessage.fileName) val message = LatexLogMessage(logMessage.message.trim(), logMessage.fileName, logMessage.line, logMessage.type, file) messageList.add(message) treeView.applyFilters(message) } } override fun processTerminated(event: ProcessEvent) { if (event.exitCode == 0) { treeView.setProgressText("Compilation was successful.") } else { treeView.setProgressText("Compilation failed.") } } override fun processWillTerminate(event: ProcessEvent, willBeDestroyed: Boolean) { } override fun startNotified(event: ProcessEvent) { treeView.setProgressText("Compilation in progress...") } }
src/nl/hannahsten/texifyidea/run/latex/logtab/LatexOutputListener.kt
2895276967
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.lang.Language import com.intellij.lang.java.JavaLanguage import com.intellij.psi.* import org.jetbrains.uast.* import org.jetbrains.uast.java.expressions.JavaUNamedExpression import org.jetbrains.uast.java.expressions.JavaUSynchronizedExpression class JavaUastLanguagePlugin : UastLanguagePlugin { override val priority = 0 override fun isFileSupported(fileName: String) = fileName.endsWith(".java", ignoreCase = true) override val language: Language get() = JavaLanguage.INSTANCE override fun isExpressionValueUsed(element: UExpression): Boolean = when (element) { is JavaUDeclarationsExpression -> false is UnknownJavaExpression -> (element.uastParent as? UExpression)?.let { isExpressionValueUsed(it) } ?: false else -> { val statement = element.psi as? PsiStatement statement != null && statement.parent !is PsiExpressionStatement } } override fun getMethodCallExpression( element: PsiElement, containingClassFqName: String?, methodName: String ): UastLanguagePlugin.ResolvedMethod? { if (element !is PsiMethodCallExpression) return null if (element.methodExpression.referenceName != methodName) return null val uElement = convertElementWithParent(element, null) val callExpression = when (uElement) { is UCallExpression -> uElement is UQualifiedReferenceExpression -> uElement.selector as UCallExpression else -> error("Invalid element type: $uElement") } val method = callExpression.resolve() ?: return null if (containingClassFqName != null) { val containingClass = method.containingClass ?: return null if (containingClass.qualifiedName != containingClassFqName) return null } return UastLanguagePlugin.ResolvedMethod(callExpression, method) } override fun getConstructorCallExpression( element: PsiElement, fqName: String ): UastLanguagePlugin.ResolvedConstructor? { if (element !is PsiNewExpression) return null val simpleName = fqName.substringAfterLast('.') if (element.classReference?.referenceName != simpleName) return null val callExpression = convertElementWithParent(element, null) as? UCallExpression ?: return null val constructorMethod = element.resolveConstructor() ?: return null val containingClass = constructorMethod.containingClass ?: return null if (containingClass.qualifiedName != fqName) return null return UastLanguagePlugin.ResolvedConstructor(callExpression, constructorMethod, containingClass) } override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? { if (element !is PsiElement) return null val parentCallback = parent.toCallback() return convertDeclaration(element, parentCallback, requiredType) ?: JavaConverter.convertPsiElement(element, parentCallback, requiredType) } override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? { if (element !is PsiElement) return null if (element is PsiJavaFile) return requiredType.el<UFile> { JavaUFile(element, this) } JavaConverter.getCached<UElement>(element)?.let { return it } val parentCallback = fun(): UElement? { val parent = JavaConverter.unwrapElements(element.parent) ?: return null return convertElementWithParent(parent, null) ?: return null } return convertDeclaration(element, parentCallback, requiredType) ?: JavaConverter.convertPsiElement(element, parentCallback, requiredType) } private fun convertDeclaration(element: PsiElement, parentCallback: (() -> UElement?)?, requiredType: Class<out UElement>?): UElement? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? { return fun(): UElement? { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) return ctor(element as P, parent) } } if (element.isValid) element.getUserData(JAVA_CACHED_UELEMENT_KEY)?.let { ref -> ref.get()?.let { return it } } return with (requiredType) { when (element) { is PsiJavaFile -> el<UFile> { JavaUFile(element, this@JavaUastLanguagePlugin) } is UDeclaration -> el<UDeclaration> { element } is PsiClass -> el<UClass> { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) JavaUClass.create(element, parent) } is PsiMethod -> el<UMethod> { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) JavaUMethod.create(element, this@JavaUastLanguagePlugin, parent) } is PsiClassInitializer -> el<UClassInitializer>(build(::JavaUClassInitializer)) is PsiEnumConstant -> el<UEnumConstant>(build(::JavaUEnumConstant)) is PsiLocalVariable -> el<ULocalVariable>(build(::JavaULocalVariable)) is PsiParameter -> el<UParameter>(build(::JavaUParameter)) is PsiField -> el<UField>(build(::JavaUField)) is PsiVariable -> el<UVariable>(build(::JavaUVariable)) is PsiAnnotation -> el<UAnnotation>(build(::JavaUAnnotation)) else -> null }} } } internal inline fun <reified ActualT : UElement> Class<out UElement>?.el(f: () -> UElement?): UElement? { return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null } internal inline fun <reified ActualT : UElement> Class<out UElement>?.expr(f: () -> UExpression?): UExpression? { return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null } private fun UElement?.toCallback() = if (this != null) fun(): UElement? { return this } else null internal object JavaConverter { internal inline fun <reified T : UElement> getCached(element: PsiElement): T? { return null //todo } internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) { is PsiExpressionStatement -> unwrapElements(element.parent) is PsiParameterList -> unwrapElements(element.parent) is PsiAnnotationParameterList -> unwrapElements(element.parent) is PsiModifierList -> unwrapElements(element.parent) is PsiExpressionList -> unwrapElements(element.parent) else -> element } internal fun convertPsiElement(el: PsiElement, parentCallback: (() -> UElement?)?, requiredType: Class<out UElement>? = null): UElement? { getCached<UElement>(el)?.let { return it } fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? { return fun(): UElement? { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) return ctor(el as P, parent) } } return with (requiredType) { when (el) { is PsiCodeBlock -> el<UBlockExpression>(build(::JavaUCodeBlockExpression)) is PsiResourceExpression -> convertExpression(el.expression, parentCallback, requiredType) is PsiExpression -> convertExpression(el, parentCallback, requiredType) is PsiStatement -> convertStatement(el, parentCallback, requiredType) is PsiIdentifier -> el<USimpleNameReferenceExpression> { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) JavaUSimpleNameReferenceExpression(el, el.text, parent) } is PsiNameValuePair -> el<UNamedExpression>(build(::JavaUNamedExpression)) is PsiArrayInitializerMemberValue -> el<UCallExpression>(build(::JavaAnnotationArrayInitializerUCallExpression)) is PsiTypeElement -> el<UTypeReferenceExpression>(build(::JavaUTypeReferenceExpression)) is PsiJavaCodeReferenceElement -> convertReference(el, parentCallback, requiredType) else -> null }} } internal fun convertBlock(block: PsiCodeBlock, parent: UElement?): UBlockExpression = getCached(block) ?: JavaUCodeBlockExpression(block, parent) internal fun convertReference(reference: PsiJavaCodeReferenceElement, parentCallback: (() -> UElement?)?, requiredType: Class<out UElement>?): UExpression? { return with (requiredType) { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) if (reference.isQualified) { expr<UQualifiedReferenceExpression> { JavaUQualifiedReferenceExpression(reference, parent) } } else { val name = reference.referenceName ?: "<error name>" expr<USimpleNameReferenceExpression> { JavaUSimpleNameReferenceExpression(reference, name, parent, reference) } } } } internal fun convertExpression(el: PsiExpression, parentCallback: (() -> UElement?)?, requiredType: Class<out UElement>? = null): UExpression? { getCached<UExpression>(el)?.let { return it } fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { return fun(): UExpression? { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) return ctor(el as P, parent) } } return with (requiredType) { when (el) { is PsiAssignmentExpression -> expr<UBinaryExpression>(build(::JavaUAssignmentExpression)) is PsiConditionalExpression -> expr<UIfExpression>(build(::JavaUTernaryIfExpression)) is PsiNewExpression -> { if (el.anonymousClass != null) expr<UObjectLiteralExpression>(build(::JavaUObjectLiteralExpression)) else expr<UCallExpression>(build(::JavaConstructorUCallExpression)) } is PsiMethodCallExpression -> { if (el.methodExpression.qualifierExpression != null) { if (requiredType == null || requiredType.isAssignableFrom(UQualifiedReferenceExpression::class.java) || requiredType.isAssignableFrom(UCallExpression::class.java)) { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) val expr = JavaUCompositeQualifiedExpression(el, parent).apply { receiver = convertOrEmpty(el.methodExpression.qualifierExpression!!, this) selector = JavaUCallExpression(el, this) } if (requiredType?.isAssignableFrom(UCallExpression::class.java) != null) expr.selector else expr } else null } else expr<UCallExpression>(build(::JavaUCallExpression)) } is PsiArrayInitializerExpression -> expr<UCallExpression>(build(::JavaArrayInitializerUCallExpression)) is PsiBinaryExpression -> expr<UBinaryExpression>(build(::JavaUBinaryExpression)) // Should go after PsiBinaryExpression since it implements PsiPolyadicExpression is PsiPolyadicExpression -> expr<UPolyadicExpression>(build(::JavaUPolyadicExpression)) is PsiParenthesizedExpression -> expr<UParenthesizedExpression>(build(::JavaUParenthesizedExpression)) is PsiPrefixExpression -> expr<UPrefixExpression>(build(::JavaUPrefixExpression)) is PsiPostfixExpression -> expr<UPostfixExpression>(build(::JavaUPostfixExpression)) is PsiLiteralExpression -> expr<ULiteralExpression>(build(::JavaULiteralExpression)) is PsiMethodReferenceExpression -> expr<UCallableReferenceExpression>(build(::JavaUCallableReferenceExpression)) is PsiReferenceExpression -> convertReference(el, parentCallback, requiredType) is PsiThisExpression -> expr<UThisExpression>(build(::JavaUThisExpression)) is PsiSuperExpression -> expr<USuperExpression>(build(::JavaUSuperExpression)) is PsiInstanceOfExpression -> expr<UBinaryExpressionWithType>(build(::JavaUInstanceCheckExpression)) is PsiTypeCastExpression -> expr<UBinaryExpressionWithType>(build(::JavaUTypeCastExpression)) is PsiClassObjectAccessExpression -> expr<UClassLiteralExpression>(build(::JavaUClassLiteralExpression)) is PsiArrayAccessExpression -> expr<UArrayAccessExpression>(build(::JavaUArrayAccessExpression)) is PsiLambdaExpression -> expr<ULambdaExpression>(build(::JavaULambdaExpression)) else -> expr<UExpression>(build(::UnknownJavaExpression)) }} } internal fun convertStatement(el: PsiStatement, parentCallback: (() -> UElement?)?, requiredType: Class<out UElement>? = null): UExpression? { getCached<UExpression>(el)?.let { return it } fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { return fun(): UExpression? { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) return ctor(el as P, parent) } } return with (requiredType) { when (el) { is PsiDeclarationStatement -> expr<UDeclarationsExpression> { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) convertDeclarations(el.declaredElements, parent!!) } is PsiExpressionListStatement -> expr<UDeclarationsExpression> { val parent = if (parentCallback == null) null else (parentCallback() ?: return null) convertDeclarations(el.expressionList.expressions, parent!!) } is PsiBlockStatement -> expr<UBlockExpression>(build(::JavaUBlockExpression)) is PsiLabeledStatement -> expr<ULabeledExpression>(build(::JavaULabeledExpression)) is PsiExpressionStatement -> convertExpression(el.expression, parentCallback, requiredType) is PsiIfStatement -> expr<UIfExpression>(build(::JavaUIfExpression)) is PsiSwitchStatement -> expr<USwitchExpression>(build(::JavaUSwitchExpression)) is PsiWhileStatement -> expr<UWhileExpression>(build(::JavaUWhileExpression)) is PsiDoWhileStatement -> expr<UDoWhileExpression>(build(::JavaUDoWhileExpression)) is PsiForStatement -> expr<UForExpression>(build(::JavaUForExpression)) is PsiForeachStatement -> expr<UForEachExpression>(build(::JavaUForEachExpression)) is PsiBreakStatement -> expr<UBreakExpression>(build(::JavaUBreakExpression)) is PsiContinueStatement -> expr<UContinueExpression>(build(::JavaUContinueExpression)) is PsiReturnStatement -> expr<UReturnExpression>(build(::JavaUReturnExpression)) is PsiAssertStatement -> expr<UCallExpression>(build(::JavaUAssertExpression)) is PsiThrowStatement -> expr<UThrowExpression>(build(::JavaUThrowExpression)) is PsiSynchronizedStatement -> expr<UBlockExpression>(build(::JavaUSynchronizedExpression)) is PsiTryStatement -> expr<UTryExpression>(build(::JavaUTryExpression)) is PsiEmptyStatement -> expr<UExpression> { UastEmptyExpression } else -> expr<UExpression>(build(::UnknownJavaExpression)) }} } private fun convertDeclarations(elements: Array<out PsiElement>, parent: UElement): UDeclarationsExpression { return JavaUDeclarationsExpression(parent).apply { val declarations = mutableListOf<UDeclaration>() for (element in elements) { if (element is PsiVariable) { declarations += JavaUVariable.create(element, this) } else if (element is PsiClass) { declarations += JavaUClass.create(element, this) } } this.declarations = declarations } } internal fun convertOrEmpty(statement: PsiStatement?, parent: UElement?): UExpression { return statement?.let { convertStatement(it, parent.toCallback(), null) } ?: UastEmptyExpression } internal fun convertOrEmpty(expression: PsiExpression?, parent: UElement?): UExpression { return expression?.let { convertExpression(it, parent.toCallback()) } ?: UastEmptyExpression } internal fun convertOrNull(expression: PsiExpression?, parent: UElement?): UExpression? { return if (expression != null) convertExpression(expression, parent.toCallback()) else null } internal fun convertOrEmpty(block: PsiCodeBlock?, parent: UElement?): UExpression { return if (block != null) convertBlock(block, parent) else UastEmptyExpression } }
uast/uast-java/src/org/jetbrains/uast/java/JavaUastLanguagePlugin.kt
1584671765
package avalon.group import avalon.api.Flag.at import avalon.tool.XiaoIceResponder import avalon.tool.pool.Constants.Basic.LANG import avalon.util.GroupConfig import avalon.util.GroupMessage import org.apache.commons.lang3.StringUtils import java.util.* import java.util.regex.Pattern /** * Created by Eldath on 2017/10/5 0029. * * @author Eldath */ object AnswerMe : GroupMessageResponder() { override fun doPost(message: GroupMessage, groupConfig: GroupConfig) { var content = message.content.trim().toLowerCase().replace(Regex("[\\pP\\p{Punct}]"), "") var text = content val regex = responderInfo().keyWordRegex text = text.replace(regex.toRegex(), "") if ("" == text.replace(" ", "")) { message.response("${at(message)} ${LANG.getString("group.answer_me.empty_content")}") return } if (StringUtils.isAlpha(text)) if (text.length < 5) { message.response("${at(message)} ${LANG.getString("group.answer_me.short_content")}") return } else if (text.length < 3) { message.response(at(message) + " ") return } content = content.replace(regex.toRegex(), "") val responseXiaoIce = XiaoIceResponder.responseXiaoIce(content) ?: return message.response(at(message) + " " + responseXiaoIce) } override fun responderInfo(): ResponderInfo = ResponderInfo( Pair("answer me", LANG.getString("group.answer_me.help")), Pattern.compile("answer me"), availableLocale = *arrayOf(Locale.SIMPLIFIED_CHINESE) ) override fun instance() = this }
src/main/kotlin/avalon/group/AnswerMe.kt
2255186596
package io.aconite.serializers import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonParseException import io.aconite.* import io.aconite.utils.toJavaType import java.lang.reflect.Type import kotlin.reflect.KAnnotatedElement import kotlin.reflect.KType class GsonBodySerializer(val gson: Gson, val type: Type): BodySerializer { class Factory(val gson: Gson = Gson()): BodySerializer.Factory { constructor(builder: GsonBuilder): this(builder.create()) override fun create(annotations: KAnnotatedElement, type: KType) = GsonBodySerializer(gson, type.toJavaType()) } override fun serialize(obj: Any?) = BodyBuffer( content = Buffer.wrap(gson.toJson(obj, type)), contentType = "application/json" ) override fun deserialize(body: BodyBuffer): Any? { if (body.content.bytes.isEmpty()) return null if (body.contentType.toLowerCase() != "application/json") throw UnsupportedMediaTypeException("Only 'application/json' media type supported") try { return gson.fromJson(body.content.string, type) } catch (ex: JsonParseException) { throw BadRequestException("Bad JSON format. ${ex.message}") } } }
aconite-core/src/io/aconite/serializers/GsonBodySerializer.kt
3972474239
/***************************************************************************** * VideosViewModel.kt ***************************************************************************** * Copyright © 2019 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.viewmodels.mobile import android.app.Activity import android.content.Context import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.viewModelScope import kotlinx.coroutines.* import org.videolan.medialibrary.interfaces.media.Folder import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.interfaces.media.VideoGroup import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.tools.FORCE_PLAY_ALL import org.videolan.tools.Settings import org.videolan.tools.isStarted import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist import org.videolan.vlc.gui.video.VideoGridFragment import org.videolan.vlc.media.MediaUtils import org.videolan.vlc.media.getAll import org.videolan.vlc.providers.medialibrary.FoldersProvider import org.videolan.vlc.providers.medialibrary.MedialibraryProvider import org.videolan.vlc.providers.medialibrary.VideoGroupsProvider import org.videolan.vlc.providers.medialibrary.VideosProvider import org.videolan.vlc.viewmodels.MedialibraryViewModel @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class VideosViewModel(context: Context, type: VideoGroupingType, val folder: Folder?, val group: VideoGroup?) : MedialibraryViewModel(context) { var groupingType = type private set var provider = loadProvider() private set private fun loadProvider(): MedialibraryProvider<out MediaLibraryItem> = when (groupingType) { VideoGroupingType.NONE -> VideosProvider(folder, group, context, this) VideoGroupingType.FOLDER -> FoldersProvider(context, this, Folder.TYPE_FOLDER_VIDEO) VideoGroupingType.NAME -> VideoGroupsProvider(context, this) } override val providers: Array<MedialibraryProvider<out MediaLibraryItem>> = arrayOf(provider) internal fun changeGroupingType(type: VideoGroupingType) { if (groupingType == type) return groupingType = type provider = loadProvider() providers[0] = provider refresh() } init { watchMedia() watchMediaGroups() } class Factory(val context: Context, private val groupingType: VideoGroupingType, val folder: Folder? = null, val group: VideoGroup? = null) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return VideosViewModel(context.applicationContext, groupingType, folder, group) as T } } // Folders & Groups internal fun play(position: Int) = viewModelScope.launch { val item = provider.pagedList.value?.get(position) ?: return@launch withContext(Dispatchers.IO) { when (item) { is Folder -> item.getAll() is VideoGroup -> item.getAll() else -> null } }?.let { MediaUtils.openList(context, it, 0) } } internal fun append(position: Int) = viewModelScope.launch { val item = provider.pagedList.value?.get(position) ?: return@launch withContext(Dispatchers.IO) { when (item) { is Folder -> item.getAll() is VideoGroup -> item.getAll() else -> null } }?.let { MediaUtils.appendMedia(context, it) } } internal fun playFoldersSelection(selection: List<Folder>) = viewModelScope.launch { val list = selection.flatMap { it.getAll() } MediaUtils.openList(context, list, 0) } internal fun addItemToPlaylist(activity: FragmentActivity, position: Int) = viewModelScope.launch { val item = provider.pagedList.value?.get(position) ?: return@launch withContext(Dispatchers.IO) { when (item) { is Folder -> item.getAll() is VideoGroup -> item.getAll() else -> null } }?.let { if (activity.isStarted()) activity.addToPlaylist(it) } } internal fun appendFoldersSelection(selection: List<Folder>) = viewModelScope.launch { val list = selection.flatMap { it.getAll() } MediaUtils.appendMedia(context, list) } internal fun playVideo(context: Activity?, mw: MediaWrapper, position: Int, fromStart: Boolean = false) { if (context === null) return mw.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO) val settings = Settings.getInstance(context) if (settings.getBoolean(FORCE_PLAY_ALL, false)) { when(val prov = provider) { is VideosProvider -> MediaUtils.playAll(context, prov, position, false) is FoldersProvider -> MediaUtils.playAllTracks(context, prov, position, false) is VideoGroupsProvider -> MediaUtils.playAllTracks(context, prov, position, false) } } else { if (fromStart) mw.addFlags(MediaWrapper.MEDIA_FROM_START) MediaUtils.openMedia(context, mw) } } internal fun playAll(activity: FragmentActivity?, position: Int = 0) { if (activity?.isStarted() == true) when (groupingType) { VideoGroupingType.NONE -> MediaUtils.playAll(activity, provider as VideosProvider, position, false) VideoGroupingType.FOLDER -> MediaUtils.playAllTracks(activity, (provider as FoldersProvider), position, false) VideoGroupingType.NAME -> MediaUtils.playAllTracks(activity, (provider as VideoGroupsProvider), position, false) } } internal fun playAudio(activity: FragmentActivity?, media: MediaWrapper) { if (activity == null) return media.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO) MediaUtils.openMedia(activity, media) } fun renameGroup(videoGroup: VideoGroup, newName: String) = viewModelScope.launch { withContext(Dispatchers.IO) { videoGroup.rename(newName) } } fun removeFromGroup(medias: List<MediaWrapper>) = viewModelScope.launch { withContext(Dispatchers.IO) { medias.forEach { media -> group?.remove(media.id) } } } fun removeFromGroup(media: MediaWrapper) = viewModelScope.launch { withContext(Dispatchers.IO) { group?.remove(media.id) } } fun ungroup(groups: List<MediaWrapper>) = viewModelScope.launch { withContext(Dispatchers.IO) { groups.forEach { group -> if (group is VideoGroup) group.destroy() } } } fun ungroup(group: VideoGroup) = viewModelScope.launch { withContext(Dispatchers.IO) { group.destroy() } } suspend fun createGroup(medias: List<MediaWrapper>): VideoGroup? { if (medias.size < 2) return null return withContext(Dispatchers.IO) { val newGroup = medialibrary.createVideoGroup(medias.map { it.id }.toLongArray()) if (newGroup.title.isNullOrBlank()) { newGroup.rename(medias[0].title) } newGroup } } suspend fun groupSimilar(media: MediaWrapper) = withContext(Dispatchers.IO) { medialibrary.regroup(media.id) } } enum class VideoGroupingType { NONE, FOLDER, NAME } @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi internal fun VideoGridFragment.getViewModel(type: VideoGroupingType = VideoGroupingType.NONE, folder: Folder?, group: VideoGroup?) = ViewModelProviders.of(requireActivity(), VideosViewModel.Factory(requireContext(), type, folder, group)).get(VideosViewModel::class.java)
application/vlc-android/src/org/videolan/vlc/viewmodels/mobile/VideosViewModel.kt
3012680395
package com.github.salomonbrys.kotson import com.google.gson.GsonBuilder import com.google.gson.JsonArray import com.google.gson.JsonObject import com.google.gson.JsonSyntaxException import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue class RWRegistrationSpecs : Spek({ given("a non-generic stream type adapter") { val adapter = typeAdapter<Person> { write { beginArray().value(it.name).value(it.age).endArray() } read { beginArray() ; val p = Person(nextString(), nextInt()) ; endArray() ; p } } val gson = GsonBuilder() .registerTypeAdapter<Person>(adapter) .create() on("serialization") { it("should serialize accordingly") { val json = gson.toJsonTree(Person("Salomon", 29)) assertTrue(json is JsonArray) assertEquals("Salomon", json[0].string) assertEquals(29, json[1].int) } } on("deserialization") { it("should deserialize accordingly") { val person = gson.fromJson<Person>("[\"Salomon\", 29]") assertEquals(Person("Salomon", 29), person) } } } given("a specialized stream type adapter") { val gson = GsonBuilder() .registerTypeAdapter<GenericPerson<Int>> { write { beginArray().value(it.name).value(it.info).endArray() } read { beginArray() ; val p = GenericPerson(nextString(), nextInt()) ; endArray() ; p } } .create() on("serializattion") { it("should serialize specific type accordingly") { val json = gson.typedToJsonTree(GenericPerson("Salomon", 29)) assertTrue(json is JsonArray) assertEquals("Salomon", json[0].string) assertEquals(29, json[1].int) } it("should not serialize differently parameterized type accordingly") { val json = gson.typedToJsonTree(GenericPerson("Salomon", "Brys")) assertTrue(json is JsonObject) } } on("deserialization") { it("should deserialize specific type accordingly") { val person = gson.fromJson<GenericPerson<Int>>("[\"Salomon\", 29]") assertEquals(GenericPerson("Salomon", 29), person) } it("should not deserialize differently parameterized type accordingly") { assertFailsWith<JsonSyntaxException> { gson.fromJson<GenericPerson<String>>("[\"Salomon\", \"Brys\"]") } } } } given ("a bad type adapter") { on("definition of both serialize and read") { it("should throw an exception") { assertFailsWith<IllegalArgumentException> { GsonBuilder() .registerTypeAdapter<Person> { serialize { jsonArray(it.src.name, it.src.age) } read { beginArray() ; val p = Person(nextString(), nextInt()) ; endArray() ; p } } .create() } } } on("definition of only write") { it("should throw an exception") { assertFailsWith<IllegalArgumentException> { GsonBuilder() .registerTypeAdapter<Person> { write { beginArray().value(it.name).value(it.age).endArray() } } .create() } } } } })
src/test/kotlin/com/github/salomonbrys/kotson/RWRegistrationSpecs.kt
310984377
package kr.or.lightsalt.kotloid import android.widget.TextView val TextView.trim: String get() = text.toString().trim()
src/main/kotlin/kr/or/lightsalt/kotloid/widget.kt
2435884339
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge import org.eclipse.jetty.servlet.ServletHolder import org.glassfish.jersey.servlet.ServletContainer import org.ice4j.ice.harvest.MappingCandidateHarvesters import org.jitsi.cmd.CmdLine import org.jitsi.config.JitsiConfig import org.jitsi.metaconfig.MetaconfigLogger import org.jitsi.metaconfig.MetaconfigSettings import org.jitsi.rest.JettyBundleActivatorConfig import org.jitsi.rest.createServer import org.jitsi.rest.enableCors import org.jitsi.rest.isEnabled import org.jitsi.rest.servletContextHandler import org.jitsi.shutdown.ShutdownServiceImpl import org.jitsi.stats.media.Utils import org.jitsi.utils.logging2.LoggerImpl import org.jitsi.utils.queue.PacketQueue import org.jitsi.videobridge.health.JvbHealthChecker import org.jitsi.videobridge.ice.Harvesters import org.jitsi.videobridge.rest.root.Application import org.jitsi.videobridge.stats.MucStatsTransport import org.jitsi.videobridge.stats.StatsCollector import org.jitsi.videobridge.stats.VideobridgeStatistics import org.jitsi.videobridge.stats.callstats.CallstatsService import org.jitsi.videobridge.util.TaskPools import org.jitsi.videobridge.version.JvbVersionService import org.jitsi.videobridge.websocket.ColibriWebSocketService import org.jitsi.videobridge.xmpp.XmppConnection import org.jitsi.videobridge.xmpp.config.XmppClientConnectionConfig import org.jxmpp.stringprep.XmppStringPrepUtil import kotlin.concurrent.thread import org.jitsi.videobridge.octo.singleton as octoRelayService import org.jitsi.videobridge.websocket.singleton as webSocketServiceSingleton fun main(args: Array<String>) { val cmdLine = CmdLine().apply { parse(args) } val logger = LoggerImpl("org.jitsi.videobridge.Main") setupMetaconfigLogger() setSystemPropertyDefaults() // Some of our dependencies bring in slf4j, which means Jetty will default to using // slf4j as its logging backend. The version of slf4j brought in, however, is too old // for Jetty so it throws errors. We use java.util.logging so tell Jetty to use that // as its logging backend. // TODO: Instead of setting this here, we should integrate it with the infra/debian scripts // to be passed. System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog") // Before initializing the application programming interfaces (APIs) of // Jitsi Videobridge, set any System properties which they use and which // may be specified by the command-line arguments. cmdLine.getOptionValue("--apis")?.let { System.setProperty( Videobridge.REST_API_PNAME, it.contains(Videobridge.REST_API).toString() ) } // Reload the Typesafe config used by ice4j, because the original was initialized before the new system // properties were set. JitsiConfig.reloadNewConfig() val versionService = JvbVersionService().also { logger.info("Starting jitsi-videobridge version ${it.currentVersion}") } startIce4j() XmppStringPrepUtil.setMaxCacheSizes(XmppClientConnectionConfig.jidCacheSize) PacketQueue.setEnableStatisticsDefault(true) val xmppConnection = XmppConnection().apply { start() } val shutdownService = ShutdownServiceImpl() val videobridge = Videobridge(xmppConnection, shutdownService, versionService.currentVersion).apply { start() } val healthChecker = JvbHealthChecker().apply { start() } val octoRelayService = octoRelayService().get()?.apply { start() } val statsCollector = StatsCollector(VideobridgeStatistics(videobridge, octoRelayService, xmppConnection)).apply { start() addTransport(MucStatsTransport(xmppConnection), xmppConnection.config.presenceInterval.toMillis()) } val callstats = if (CallstatsService.config.enabled) { CallstatsService(videobridge.version).apply { start { statsTransport?.let { statsTransport -> statsCollector.addTransport(statsTransport, CallstatsService.config.interval.toMillis()) } ?: throw IllegalStateException("Stats transport is null after the service is started") videobridge.addEventHandler(videobridgeEventHandler) } } } else { logger.info("Not starting CallstatsService, disabled in configuration.") null } val publicServerConfig = JettyBundleActivatorConfig( "org.jitsi.videobridge.rest", "videobridge.http-servers.public" ) val publicHttpServer = if (publicServerConfig.isEnabled()) { logger.info("Starting public http server") val websocketService = ColibriWebSocketService(publicServerConfig.isTls) webSocketServiceSingleton().setColibriWebSocketService(websocketService) createServer(publicServerConfig).also { websocketService.registerServlet(it.servletContextHandler, videobridge) it.start() } } else { logger.info("Not starting public http server") null } val privateServerConfig = JettyBundleActivatorConfig( "org.jitsi.videobridge.rest.private", "videobridge.http-servers.private" ) val privateHttpServer = if (privateServerConfig.isEnabled()) { logger.info("Starting private http server") val restApp = Application( videobridge, xmppConnection, statsCollector, versionService.currentVersion, healthChecker ) createServer(privateServerConfig).also { it.servletContextHandler.addServlet( ServletHolder(ServletContainer(restApp)), "/*" ) it.servletContextHandler.enableCors() it.start() } } else { logger.info("Not starting private http server") null } // Block here until the bridge shuts down shutdownService.waitForShutdown() logger.info("Bridge shutting down") healthChecker.stop() octoRelayService?.stop() xmppConnection.stop() callstats?.let { videobridge.removeEventHandler(it.videobridgeEventHandler) it.statsTransport?.let { statsTransport -> statsCollector.removeTransport(statsTransport) } it.stop() } statsCollector.stop() try { publicHttpServer?.stop() privateHttpServer?.stop() } catch (t: Throwable) { logger.error("Error shutting down http servers", t) } videobridge.stop() stopIce4j() TaskPools.SCHEDULED_POOL.shutdownNow() TaskPools.CPU_POOL.shutdownNow() TaskPools.IO_POOL.shutdownNow() } private fun setupMetaconfigLogger() { val configLogger = LoggerImpl("org.jitsi.config") MetaconfigSettings.logger = object : MetaconfigLogger { override fun warn(block: () -> String) = configLogger.warn(block) override fun error(block: () -> String) = configLogger.error(block) override fun debug(block: () -> String) = configLogger.debug(block) } } private fun setSystemPropertyDefaults() { val defaults = getSystemPropertyDefaults() defaults.forEach { (key, value) -> if (System.getProperty(key) == null) { System.setProperty(key, value) } } } private fun getSystemPropertyDefaults(): Map<String, String> { val defaults = mutableMapOf<String, String>() Utils.getCallStatsJavaSDKSystemPropertyDefaults(defaults) // Make legacy ice4j properties system properties. val cfg = JitsiConfig.SipCommunicatorProps val ice4jPropNames = cfg.getPropertyNamesByPrefix("org.ice4j", false) ice4jPropNames?.forEach { key -> cfg.getString(key)?.let { value -> defaults.put(key, value) } } return defaults } private fun startIce4j() { // Start the initialization of the mapping candidate harvesters. // Asynchronous, because the AWS and STUN harvester may take a long // time to initialize. thread(start = true) { MappingCandidateHarvesters.initialize() } } private fun stopIce4j() { // Shut down harvesters. Harvesters.closeStaticConfiguration() }
jvb/src/main/kotlin/org/jitsi/videobridge/Main.kt
2727616207
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.exceptions import org.droidmate.device.error.DeviceException class TestDeviceException(override val exceptionSpec: IExceptionSpec) : DeviceException("Test-enforced device exception. Package name: $exceptionSpec.packageName Method name: " + "$exceptionSpec.methodName Call index: $exceptionSpec.callIndex"), ITestException { companion object { private const val serialVersionUID: Long = 1 } }
project/pcComponents/core/src/test/kotlin/org/droidmate/exceptions/TestDeviceException.kt
1837879715
package nl.sogeti.android.gpstracker.ng.features.tracklist import androidx.databinding.BindingAdapter import android.net.Uri import androidx.cardview.widget.CardView import androidx.recyclerview.widget.RecyclerView import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import nl.sogeti.android.gpstracker.ng.base.common.postMainThread import nl.sogeti.android.opengpstrack.ng.features.R import timber.log.Timber open class TracksBindingAdapters { @BindingAdapter("tracks") fun setTracks(recyclerView: androidx.recyclerview.widget.RecyclerView, tracks: List<Uri>?) { val viewAdapter: TrackListViewAdapter if (recyclerView.adapter is TrackListViewAdapter) { viewAdapter = recyclerView.adapter as TrackListViewAdapter viewAdapter.updateTracks(tracks ?: emptyList()) } else { viewAdapter = TrackListViewAdapter(recyclerView.context) viewAdapter.updateTracks(tracks ?: emptyList()) recyclerView.adapter = viewAdapter } } @BindingAdapter("selected") fun setTracks(recyclerView: androidx.recyclerview.widget.RecyclerView, track: Uri?) { val viewAdapter: TrackListViewAdapter if (recyclerView.adapter is TrackListViewAdapter) { viewAdapter = recyclerView.adapter as TrackListViewAdapter viewAdapter.selection = track } else { viewAdapter = TrackListViewAdapter(recyclerView.context) viewAdapter.selection = track recyclerView.adapter = viewAdapter } } @BindingAdapter("tracksListener") fun setListener(recyclerView: androidx.recyclerview.widget.RecyclerView, listener: TrackListAdapterListener?) { val adapter = recyclerView.adapter if (adapter != null && adapter is TrackListViewAdapter) { adapter.listener = listener } else { Timber.e("Binding listener when missing adapter, are the xml attributes out of order") } } @BindingAdapter("editMode") fun setEditMode(card: androidx.cardview.widget.CardView, editMode: Boolean) { val share = card.findViewById<View>(R.id.row_track_share) val delete = card.findViewById<View>(R.id.row_track_delete) val edit = card.findViewById<View>(R.id.row_track_edit) if (editMode) { if (share.visibility != VISIBLE) { share.alpha = 0F edit.alpha = 0F delete.alpha = 0F } share.visibility = VISIBLE edit.visibility = VISIBLE delete.visibility = VISIBLE share.animate().alpha(1.0F) edit.animate().alpha(1.0F) delete.animate().alpha(1.0F) } else if (share.visibility == VISIBLE) { share.animate().alpha(0.0F) edit.animate().alpha(0.0F) delete.animate().alpha(0.0F).withEndAction { share.visibility = GONE edit.visibility = GONE delete.visibility = GONE } } } @BindingAdapter("focusPosition") fun setFocusPosition(list: androidx.recyclerview.widget.RecyclerView, position: Int?) { if (position != null && position > 0) { postMainThread { list.layoutManager?.scrollToPosition(position) } } } }
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/tracklist/TracksBindingAdapters.kt
2574933606
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.gui import javafx.application.Platform import javafx.geometry.Orientation import javafx.scene.Scene import javafx.scene.layout.BorderPane import javafx.scene.layout.FlowPane import javafx.stage.Stage import uk.co.nickthecoder.paratask.ParaTask import uk.co.nickthecoder.paratask.Task import uk.co.nickthecoder.paratask.parameters.fields.TaskForm import uk.co.nickthecoder.paratask.util.AutoExit import uk.co.nickthecoder.paratask.util.findScrollbar abstract class AbstractTaskPrompter(val task: Task) { var root = BorderPane() var taskForm = TaskForm(task) var stage: Stage? = null val buttons = FlowPane() open protected fun close() { stage?.hide() } open fun build() { taskForm.build() with(buttons) { styleClass.add("buttons") } with(root) { styleClass.add("task-prompter") center = taskForm.scrollPane bottom = buttons } } fun placeOnStage(stage: Stage) { build() this.stage = stage stage.title = task.taskD.label val scene = Scene(root) ParaTask.style(scene) stage.scene = scene // Once the stage has been fully created, listen for when the taskForm's scroll bar appears, and // attempt to resize the stage, so that the scroll bar is no longer needed. Platform.runLater { val scrollBar = taskForm.scrollPane.findScrollbar(Orientation.VERTICAL) scrollBar?.visibleProperty()?.addListener { _, _, newValue -> if (newValue == true) { val extra = taskForm.scrollPane.prefHeight(-1.0) - taskForm.scrollPane.height if (extra > 0 && stage.height < 700) { stage.sizeToScene() Platform.runLater { taskForm.form.requestLayout() } } } } } AutoExit.show(stage) } }
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/AbstractTaskPrompter.kt
1831245025
package net.nemerosa.ontrack.kdsl.spec.extension.notifications import com.apollographql.apollo.api.Input import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.kdsl.connector.Connected import net.nemerosa.ontrack.kdsl.connector.Connector import net.nemerosa.ontrack.kdsl.connector.graphql.convert import net.nemerosa.ontrack.kdsl.connector.graphql.schema.SubscribeToEntityEventsMutation import net.nemerosa.ontrack.kdsl.connector.graphqlConnector import net.nemerosa.ontrack.kdsl.spec.ProjectEntity /** * Interface for the management of notifications in Ontrack. */ class NotificationsMgt(connector: Connector) : Connected(connector) { /** * Subscribes for notifications. * * @param channel Channel to send the notifications to * @param channelConfig Configuration of the channel * @param keywords Space-separated list of keywords to filter the events * @param events Events to listen to * @param projectEntity Entity to listen to (null for global subscriptions) */ fun subscribe( channel: String, channelConfig: Any, keywords: String?, events: List<String>, projectEntity: ProjectEntity?, ) { if (projectEntity != null) { graphqlConnector.mutate( SubscribeToEntityEventsMutation( projectEntity.type, projectEntity.id.toInt(), channel, channelConfig.asJson(), Input.optional(keywords), events ) ) { it?.subscribeToEvents()?.fragments()?.payloadUserErrors()?.convert() } } else { TODO("Global subscriptions not supported yet") } } /** * Access to the in-memory notification channel. */ val inMemory: InMemoryMgt by lazy { InMemoryMgt(connector) } }
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/notifications/NotificationsMgt.kt
4183385302
package com.fireflysource.net.http.server.impl.matcher import com.fireflysource.net.http.server.Matcher import com.fireflysource.net.http.server.Router import java.util.* class ParameterPathMatcher : AbstractMatcher<ParameterPathMatcher.ParameterRule>(), Matcher { companion object { fun isParameterPath(path: String): Boolean { val paths = split(path) return paths.any { it[0] == ':' } } fun split(path: String): List<String> { val paths: MutableList<String> = LinkedList() var start = 1 val last = path.lastIndex for (i in 1..last) { if (path[i] == '/') { paths.add(path.substring(start, i).trim()) start = i + 1 } } if (path[last] != '/') { paths.add(path.substring(start).trim()) } return paths } } inner class ParameterRule(val rule: String) { val paths = split(rule) fun match(list: List<String>): Map<String, String> { if (paths.size != list.size) return emptyMap() val param: MutableMap<String, String> = HashMap() for (i in list.indices) { val path = paths[i] val value = list[i] if (path[0] != ':') { if (path != value) { return emptyMap() } } else { param[path.substring(1)] = value } } return param } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ParameterRule return rule == other.rule } override fun hashCode(): Int { return rule.hashCode() } } override fun getMatchType(): Matcher.MatchType { return Matcher.MatchType.PATH } override fun add(rule: String, router: Router) { val parameterRule = ParameterRule(rule) routersMap.computeIfAbsent(parameterRule) { TreeSet() }.add(router) } override fun match(value: String): Matcher.MatchResult? { if (routersMap.isEmpty()) return null val routers = TreeSet<Router>() val parameters = HashMap<Router, Map<String, String>>() val paths = split(value) routersMap.forEach { (rule, routerSet) -> val param = rule.match(paths) if (param.isNotEmpty()) { routers.addAll(routerSet) routerSet.forEach { router -> parameters[router] = param } } } return if (routers.isEmpty()) null else Matcher.MatchResult(routers, parameters, matchType) } }
firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/matcher/ParameterPathMatcher.kt
1230191060
package com.iyanuadelekan.kanary.app.router import com.iyanuadelekan.kanary.app.RouteList import com.iyanuadelekan.kanary.app.RouterAction import com.iyanuadelekan.kanary.app.adapter.component.middleware.MiddlewareAdapter import com.iyanuadelekan.kanary.app.lifecycle.AppContext /** * @author Iyanu Adelekan on 18/11/2018. */ internal class RouteNode(val path: String, var action: RouterAction? = null) { private val children = RouteList() private var middleware: ArrayList<MiddlewareAdapter> = ArrayList() /** * Adds a child node to the current node. * * @param routeNode - node to be added. */ fun addChild(routeNode: RouteNode) = this.children.add(routeNode) /** * Invoked to check if a route node has a specified child node. * * @param path - path to be matched. * @return [Boolean] - true if child exists and false otherwise. */ fun hasChild(path: String): Boolean { children.forEach { if (it.path == path) { return true } } return false } /** * Gets a child node matching a specific path. * * @params path - path to be matched. * @return [RouteNode] - node if one exists and null otherwise. */ fun getChild(path: String): RouteNode? { children.forEach { if (it.path == path) { return it } } return null } /** * Gets children of given node. * * @return [RouteList] - children. */ fun getChildren(): RouteList = this.children /** * Returns number of child nodes. * * @return [Int] - number of child nodes. */ fun getChildCount(): Int = children.size /** * Invoked to add a collection of middleware to route node. * * @param middleware - middleware to be added. */ fun addMiddleware(middleware: List<MiddlewareAdapter>) { this.middleware.addAll(middleware) } fun runMiddleWare(ctx: AppContext) { middleware.forEach { it.run(ctx) } } fun executeAction(ctx: AppContext) { action?.invoke(ctx) } /** * Converts [RouteNode] to its corresponding string representation. * * @return [String] - String representation of route node. */ override fun toString(): String { val builder = StringBuilder() builder.append("$path => [") if (!children.isEmpty()) { for (i in 0 until children.size) { builder.append(children[i]) if (i != children.size - 1) { builder.append(",") } } } builder.append("]") return builder.toString() } }
src/main/com/iyanuadelekan/kanary/app/router/RouteNode.kt
3170875689
package io.github.plastix.kotlinboilerplate import javax.inject.Qualifier @Qualifier annotation class ApplicationQualifier
app/src/main/kotlin/io/github/plastix/kotlinboilerplate/ApplicationQualifier.kt
1746843250
package net.nemerosa.ontrack.it import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import net.nemerosa.ontrack.common.seconds import org.slf4j.LoggerFactory import kotlin.time.Duration import kotlin.time.ExperimentalTime /** * Waits until a given condition is met. * * @param message Activity being waited for * @param initial Initial time to wait * @param interval Interval to wait between two attemps * @param timeout Total timeout for the operatiion to complete * @param ignoreExceptions Set to `true` if exceptions do not abort the wait * @param check Must return `true` when the wait is over * @receiver Message to associate with the waiting (name of the task) */ @ExperimentalTime fun waitUntil( message: String, initial: Duration? = null, interval: Duration = 5.seconds, timeout: Duration = 60.seconds, ignoreExceptions: Boolean = false, check: () -> Boolean ) { TimeTestUtils().waitUntil(message, initial, interval, timeout, ignoreExceptions, check) } class TimeTestUtils { private val logger = LoggerFactory.getLogger(TimeTestUtils::class.java) @ExperimentalTime fun waitUntil( message: String, initial: Duration?, interval: Duration, timeout: Duration, ignoreExceptions: Boolean, check: () -> Boolean ) { runBlocking { val timeoutMs = timeout.inWholeMilliseconds val start = System.currentTimeMillis() // Logging log(message, "Starting...") // Waiting some initial time if (initial != null) { log(message, "Initial delay ($initial") delay(initial.inWholeMilliseconds) } // Checks while ((System.currentTimeMillis() - start) < timeoutMs) { // Check log(message, "Checking...") val ok = try { check() } catch (ex: Exception) { if (ignoreExceptions) { false // We don't exit because of the exception, but we still need to carry on } else { throw ex } } if (ok) { // OK log(message, "OK.") return@runBlocking } else { log(message, "Interval delay ($interval") delay(interval.inWholeMilliseconds) } } // Timeout throw IllegalStateException("$message: Timeout exceeded after $timeout") } } private fun log(message: String, info: String) { logger.info("$message: $info") } }
ontrack-it-utils/src/main/java/net/nemerosa/ontrack/it/TimeTestUtils.kt
3555350686
package co.ideaportal.srirangadigital.shankaraandroid.books.ttssettings.bindings import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import co.ideaportal.srirangadigital.shankaraandroid.R import co.ideaportal.srirangadigital.shankaraandroid.books.ttssettings.model.Settings import co.ideaportal.srirangadigital.shankaraandroid.util.AdapterClickListener class SettingsRVAdapter(private val context : Context, private val items: ArrayList<Settings>, private val mAdapterClickListener: AdapterClickListener) : RecyclerView.Adapter<SettingsViewHolder>() { var settingsList: MutableList<Settings> = items override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder = SettingsViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_settings, parent, false), mAdapterClickListener) override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) { val item = getItemAtPos(position) } override fun getItemCount(): Int = settingsList.size private fun getItemAtPos(pos: Int): Settings = settingsList[pos] }
app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/books/ttssettings/bindings/SettingsRVAdapter.kt
1899118026
fun reassigment_0(x: Int): Int { val b = x + 1 return b }
translator/src/test/kotlin/tests/reassigment_0/reassigment_0.kt
2570007747
package gg.octave.bot.entities import com.google.common.reflect.TypeToken import gg.octave.bot.utils.get import gg.octave.bot.utils.toDuration import ninja.leaping.configurate.hocon.HoconConfigurationLoader import java.io.File import java.time.Duration class Configuration(file: File) { private val loader = HoconConfigurationLoader.builder().setFile(file).build() private val config = loader.load() // +--------------+ // Command Settings // +--------------+ val prefix: String = config["commands", "prefix"].getString("_") val admins: List<Long> = config["commands", "administrators"].getList(TypeToken.of(Long::class.javaObjectType)) // +--------------+ // Bot Settings // +--------------+ val name: String = config["bot", "name"].getString("Octave") val game: String = config["bot", "game"].getString("${prefix}help | %d") val ipv6Block: String = config["bot", "ipv6block"].getString(null) val ipv6Exclude: String = config["bot", "ipv6Exclude"].getString(null) val sentryDsn: String = config["bot", "sentry"].getString(null) val bucketFactor: Int = config["bot", "bucketFactor"].getInt(8) // +--------------+ // Music Settings // +--------------+ val musicEnabled = config["music", "enabled"].getBoolean(true) val searchEnabled = config["music", "search"].getBoolean(true) val queueLimit = config["music", "queue limit"].getInt(20) val musicLimit = config["music", "limit"].getInt(500) val durationLimitText: String = config["music", "duration limit"].getString("2 hours") val durationLimit: Duration = durationLimitText.toDuration() val voteSkipCooldownText: String = config["music", "vote skip cooldown"].getString("35 seconds") val voteSkipCooldown: Duration = voteSkipCooldownText.toDuration() val voteSkipDurationText: String = config["music", "vote skip duration"].getString("20 seconds") val voteSkipDuration: Duration = voteSkipDurationText.toDuration() val votePlayCooldownText: String = config["music", "vote play cooldown"].getString("35 seconds") val votePlayCooldown: Duration = voteSkipCooldownText.toDuration() val votePlayDurationText: String = config["music", "vote play duration"].getString("20 seconds") val votePlayDuration: Duration = voteSkipDurationText.toDuration() }
src/main/kotlin/gg/octave/bot/entities/Configuration.kt
419947057
package gdlunch.parser import com.labuda.gdlunch.parser.AbstractRestaurantWebParser import com.labuda.gdlunch.parser.DailyParser import com.labuda.gdlunch.repository.entity.DailyMenu import com.labuda.gdlunch.repository.entity.MenuItem import com.labuda.gdlunch.repository.entity.Restaurant import mu.KotlinLogging import org.jsoup.Jsoup import java.time.LocalDate /** * Parses daily menu from Bistro Franz restaurant */ class BistroFranzParser(restaurant: Restaurant) : AbstractRestaurantWebParser(restaurant), DailyParser { val logger = KotlinLogging.logger { } override fun parse(): DailyMenu { val result = DailyMenu() result.restaurant = restaurant result.date = LocalDate.now() val document = Jsoup.connect(restaurant.parserUrl).get() document.select(".obedmenu .tabnab.polevka .radj .mnam").forEach { result.menu.add(MenuItem(it.ownText(), 0f)) } document.select(".obedmenu .tabnab.jidlo .radj").forEach { result.menu.add( MenuItem( it.selectFirst(".mnam").ownText(), parsePrice(it.selectFirst(".cena").ownText() ) ) ) } return result } }
src/main/kotlin/gdlunch/parser/BistroFranzParser.kt
445029523
package com.groupdocs.ui.result import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import com.groupdocs.comparison.Comparer import com.groupdocs.comparison.Document import com.groupdocs.comparison.license.License import com.groupdocs.comparison.options.CompareOptions import com.groupdocs.comparison.options.PreviewOptions import com.groupdocs.comparison.options.enums.PreviewFormats import com.groupdocs.comparison.result.FileType import com.groupdocs.ui.common.NavigationException import com.groupdocs.ui.common.Screen import com.groupdocs.ui.common.Settings import kotlinx.coroutines.* import org.apache.commons.io.FileUtils import java.io.File import java.io.FileOutputStream import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import javax.swing.JFileChooser import javax.swing.filechooser.FileNameExtensionFilter import kotlin.io.path.nameWithoutExtension class ResultViewModel(private val screen: MutableState<Screen>) { private val _state: MutableState<ResultState> = mutableStateOf(ResultState()) val state: State<ResultState> = _state private val tempDir: Path init { var resultPath = "" val sourcePath: String val targetPath: String val targetName: String tempDir = Paths.get(System.getenv("TMP")) if (screen.value is Screen.Result) { sourcePath = (screen.value as Screen.Result).source targetPath = (screen.value as Screen.Result).target targetName = Paths.get(targetPath).fileName.nameWithoutExtension } else throw NavigationException() // val licensePath = Settings.instance.licensePath if (licensePath == null || Files.exists(Paths.get(licensePath))) { CoroutineScope(Dispatchers.IO).launch { licensePath?.let { License().setLicense(it) } println("License is ${if (License.isValidLicense()) "valid" else "invalid"}") Comparer(sourcePath).use { comparison -> comparison.add(targetPath) try { val fileType = FileType.fromFileNameOrExtension(targetPath) resultPath = comparison.compare( tempDir.resolve("Result_$targetName${fileType.extension}").toString(), CompareOptions().apply { detalisationLevel = Settings.instance.detalisationLevel generateSummaryPage = Settings.instance.generateSummaryPage } ).toString() } catch (e: Exception) { _state.value = _state.value.copy( errorMessage = "Converting error: ${e.message}", isInProgress = false ) return@use } } _state.value = _state.value.copy( sourcePath = sourcePath, targetPath = targetPath, resultPath = resultPath ) displayResult(resultPath) } } else { _state.value = _state.value.copy( errorMessage = "License not found: '$licensePath'", isInProgress = false ) } } private fun displayResult(resultPath: String) { println("Comparison result temporary saved to ${state.value.resultPath}") val pageList = mutableListOf<String>() CoroutineScope(Dispatchers.IO).launch { try { val result = Document(resultPath) result.generatePreview(PreviewOptions { val pagePath = tempDir.resolve("gd_${System.currentTimeMillis()}_page_$it.png") pageList.add(pagePath.toString()) FileOutputStream(pagePath.toFile()) }.apply { previewFormat = PreviewFormats.PNG }) } catch (e: Exception) { _state.value = _state.value.copy( errorMessage = "Preview generating error: ${e.message}", isInProgress = false ) return@launch } _state.value = _state.value.copy( isInProgress = false, pageList = pageList ) } } fun onDownload() { val resultName = state.value.resultName val extension = if (resultName.contains('.')) resultName.substring(resultName.lastIndexOf('.') + 1) else null JFileChooser().apply { extension?.let { fileFilter = FileNameExtensionFilter("Pdf file", extension) } selectedFile = File(resultName) if (showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { val resultPath = state.value.resultPath val downloadPath = selectedFile.path CoroutineScope(Dispatchers.IO).launch { FileUtils.copyFile(File(resultPath), File(downloadPath)) withContext(Dispatchers.Main) { _state.value = _state.value.copy( infoMessage = "File was saved!" ) delay(2500L) _state.value = _state.value.copy( infoMessage = null ) } } } } } fun onDispose() { print("Deleting temporary files...") CoroutineScope(Dispatchers.IO).launch { state.value.pageList.toMutableList().apply { add(state.value.resultPath) forEach { path -> try { FileUtils.delete(File(path)) } catch (e: Exception) { e.printStackTrace() } } } } println("Finished") } }
Demos/Compose/src/main/kotlin/com/groupdocs/ui/result/ResultViewModel.kt
4011429205
@file:JvmName("RxView") @file:JvmMultifileClass package com.jakewharton.rxbinding3.view import android.view.View import android.view.View.OnClickListener import androidx.annotation.CheckResult import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.android.MainThreadDisposable import com.jakewharton.rxbinding3.internal.checkMainThread /** * Create an observable which emits on `view` click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnClickListener] to observe * clicks. Only one observable can be used for a view at a time. */ @CheckResult fun View.clicks(): Observable<Unit> { return ViewClickObservable(this) } private class ViewClickObservable( private val view: View ) : Observable<Unit>() { override fun subscribeActual(observer: Observer<in Unit>) { if (!checkMainThread(observer)) { return } val listener = Listener(view, observer) observer.onSubscribe(listener) view.setOnClickListener(listener) } private class Listener( private val view: View, private val observer: Observer<in Unit> ) : MainThreadDisposable(), OnClickListener { override fun onClick(v: View) { if (!isDisposed) { observer.onNext(Unit) } } override fun onDispose() { view.setOnClickListener(null) } } }
rxbinding/src/main/java/com/jakewharton/rxbinding3/view/ViewClickObservable.kt
3798471051
package de.xikolo.controllers.base import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import butterknife.ButterKnife import com.yatatsu.autobundle.AutoBundle abstract class BaseFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { // restore AutoBundle.bind(this, savedInstanceState) } else { AutoBundle.bind(this) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ButterKnife.bind(this, view) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) AutoBundle.pack(this, outState) } }
app/src/main/java/de/xikolo/controllers/base/BaseFragment.kt
1465988742
/** * 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 POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId import POGOProtos.Networking.Responses.RecycleInventoryItemResponseOuterClass import ink.abb.pogo.api.request.RecycleInventoryItem 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 java.util.concurrent.atomic.AtomicInteger class DropUselessItems : Task { override fun run(bot: Bot, ctx: Context, settings: Settings) { // ignores the items that have -1 val itemsToDrop = settings.uselessItems.filter { it.value != -1 } if (settings.groupItemsByType) dropGroupedItems(ctx, itemsToDrop, settings) else dropItems(ctx, itemsToDrop, settings) } /** * Drops the excess items by group */ fun dropGroupedItems(ctx: Context, items: Map<ItemId, Int>, settings: Settings) { // map with what items to keep in what amounts val itemsToDrop = mutableMapOf<ItemId, Int>() // adds not groupable items on map itemsToDrop.putAll(items.filter { singlesFilter.contains(it.key) }) // groups items val groupedItems = groupItems(items) // adds new items to the map val itemBag = ctx.api.inventory.items groupedItems.forEach groupedItems@ { var groupCount = 0 it.key.forEach { groupCount += itemBag.getOrPut(it, { AtomicInteger(0) }).get() } var neededToDrop = groupCount - it.value if (neededToDrop > 0) it.key.forEach { val item = itemBag.getOrPut(it, { AtomicInteger(0) }) if (neededToDrop <= item.get()) { itemsToDrop.put(it, item.get() - neededToDrop) return@groupedItems } else { neededToDrop -= item.get() itemsToDrop.put(it, 0) } } } // drops excess items dropItems(ctx, itemsToDrop, settings) } /** * Groups the items using the groupFilters * Each group contains the list of itemIds of the group and sum of all its number */ fun groupItems(items: Map<ItemId, Int>): Map<Array<ItemId>, Int> { val groupedItems = mutableMapOf<Array<ItemId>, Int>() groupFilters.forEach { val filter = it val filteredItems = items.filter { filter.contains(it.key) } groupedItems.put(filteredItems.keys.toTypedArray(), filteredItems.values.sum()) } return groupedItems } // Items that can be grouped val groupFilters = arrayOf( arrayOf(ItemId.ITEM_REVIVE, ItemId.ITEM_MAX_REVIVE), arrayOf(ItemId.ITEM_POTION, ItemId.ITEM_SUPER_POTION, ItemId.ITEM_HYPER_POTION, ItemId.ITEM_MAX_POTION), arrayOf(ItemId.ITEM_POKE_BALL, ItemId.ITEM_GREAT_BALL, ItemId.ITEM_ULTRA_BALL, ItemId.ITEM_MASTER_BALL) ) // Items that cant be grouped val singlesFilter = arrayOf(ItemId.ITEM_RAZZ_BERRY, ItemId.ITEM_LUCKY_EGG, ItemId.ITEM_INCENSE_ORDINARY, ItemId.ITEM_TROY_DISK) /** * Drops the excess items by item */ fun dropItems(ctx: Context, items: Map<ItemId, Int>, settings: Settings) { val itemBag = ctx.api.inventory.items items.forEach { val item = itemBag.getOrPut(it.key, { AtomicInteger(0) }) val count = item.get() - it.value if (count > 0) { val dropItem = it.key val drop = RecycleInventoryItem().withCount(count).withItemId(dropItem) val result = ctx.api.queueRequest(drop).toBlocking().first().response if (result.result == RecycleInventoryItemResponseOuterClass.RecycleInventoryItemResponse.Result.SUCCESS) { ctx.itemStats.second.getAndAdd(count) Log.yellow("Dropped ${count}x ${dropItem.name}") ctx.server.sendProfile() } else { Log.red("Failed to drop ${count}x ${dropItem.name}: $result") } } if (settings.itemDropDelay != (-1).toLong()) { val itemDropDelay = settings.itemDropDelay / 2 + (Math.random() * settings.itemDropDelay).toLong() Thread.sleep(itemDropDelay) } } } }
src/main/kotlin/ink/abb/pogo/scraper/tasks/DropUselessItems.kt
873206187
package com.github.mibac138.argparser.binder import com.github.mibac138.argparser.named.name import com.github.mibac138.argparser.syntax.dsl.SyntaxElementDSL import org.junit.Test import kotlin.test.assertEquals /** * Created by mibac138 on 07-07-2017. */ class NameSyntaxGeneratorTest { private val generator = NameSyntaxGenerator() @Test fun testKotlin() { val dsl = SyntaxElementDSL(Any::class.java) val param = this::kotlinFunction.parameters[0] generator.generate(dsl, param) assertEquals("name", dsl.name) } @Test fun testJava() { val dsl = SyntaxElementDSL(Any::class.java) val param = JavaClass()::javaMethod.parameters[0] generator.generate(dsl, param) assertEquals("a", dsl.name) } private fun kotlinFunction(@Name("name") string: String) { println(string) } }
binder/src/test/kotlin/com/github/mibac138/argparser/binder/NameSyntaxGeneratorTest.kt
3241389268
/* * Copyright (C) 2022 panpf <panpfpanpf@outlook.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.android import android.graphics.drawable.BitmapDrawable import android.os.Build import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.test.utils.alphaCompat import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.util.getDrawableCompat import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ResourcesTest { @Test fun testBitmapDrawableBitmap() { val context = getTestContext() val drawable1 = context.getDrawableCompat(android.R.drawable.ic_delete) as BitmapDrawable val drawable2 = context.getDrawableCompat(android.R.drawable.ic_delete) as BitmapDrawable Assert.assertNotSame(drawable1, drawable2) Assert.assertSame(drawable1.bitmap, drawable2.bitmap) drawable2.bitmap.recycle() Assert.assertTrue(drawable1.bitmap.isRecycled) val drawable3 = context.getDrawableCompat(android.R.drawable.ic_delete) as BitmapDrawable Assert.assertTrue(drawable3.bitmap.isRecycled) } @Test fun testBitmapDrawableMutate() { val context = getTestContext() val drawable1 = context.getDrawableCompat(android.R.drawable.ic_delete) as BitmapDrawable val drawable2 = context.getDrawableCompat(android.R.drawable.ic_delete) as BitmapDrawable Assert.assertNotSame(drawable1, drawable2) Assert.assertSame(drawable1.paint, drawable2.paint) if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(255, drawable1.alphaCompat) } else { Assert.assertEquals(0, drawable1.alphaCompat) } if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(255, drawable2.alphaCompat) } else { Assert.assertEquals(0, drawable2.alphaCompat) } val drawable3 = drawable1.mutate() as BitmapDrawable Assert.assertSame(drawable1, drawable3) Assert.assertSame(drawable1.paint, drawable3.paint) if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(255, drawable3.alphaCompat) } else { Assert.assertEquals(0, drawable3.alphaCompat) } drawable3.alpha = 100 if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(100, drawable1.alphaCompat) } else { Assert.assertEquals(0, drawable1.alphaCompat) } if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(255, drawable2.alphaCompat) } else { Assert.assertEquals(0, drawable2.alphaCompat) } if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(100, drawable3.alphaCompat) } else { Assert.assertEquals(0, drawable3.alphaCompat) } val drawable4 = context.getDrawableCompat(android.R.drawable.ic_delete) as BitmapDrawable if (Build.VERSION.SDK_INT >= 19) { Assert.assertEquals(255, drawable4.alphaCompat) } else { Assert.assertEquals(0, drawable4.alphaCompat) } } }
sketch/src/androidTest/java/com/github/panpf/sketch/test/android/ResourcesTest.kt
2320707132
/* * Copyright 2021 Peter Kenji Yamanaka * * 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.pyamsoft.pasterino.main import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.material.AppBarDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.accompanist.insets.statusBarsHeight import com.pyamsoft.pasterino.R @Composable @JvmOverloads internal fun MainAppBar( onHeightMeasured: (height: Int) -> Unit, modifier: Modifier = Modifier, ) { Surface( modifier = modifier, color = MaterialTheme.colors.primary, contentColor = Color.White, elevation = AppBarDefaults.TopAppBarElevation, ) { Column { Box(modifier = Modifier.statusBarsHeight()) TopAppBar( modifier = Modifier.onSizeChanged { onHeightMeasured(it.height) }, elevation = 0.dp, backgroundColor = MaterialTheme.colors.primary, title = { Text(text = stringResource(R.string.app_name)) }, ) } } } @Preview @Composable private fun PreviewMainAppBar() { MainAppBar( onHeightMeasured = {}, ) }
app/src/main/java/com/pyamsoft/pasterino/main/MainAppBar.kt
927292092
package org.pixelndice.table.pixelclient.connection.lobby.client import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ds.File import org.pixelndice.table.pixelprotocol.Protobuf import java.io.FileOutputStream import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Path private val logger = LogManager.getLogger(StateRunning06File::class.java) class StateRunning06File: State { private val tmpPath: Path = FileSystems.getDefault().getPath("tmp") init { try{ Files.createDirectories(tmpPath) }catch (e: FileAlreadyExistsException){ logger.trace("tmp directory already exists. It is all ok, nothing to do") } } override fun process(ctx: Context) { val packet = ctx.channel.packet if( packet != null ){ if( packet.payloadCase == Protobuf.Packet.PayloadCase.FILE){ val path = tmpPath.resolve(packet.file.name) val out = FileOutputStream(path.toFile()) out.write(packet.file.data.toByteArray()) out.close() File.addFile(path) path.toFile().delete() logger.debug("Received file ${packet.file.name}") }else{ logger.error("Expecting ShareFile, instead received: $packet. IP: ${ctx.channel.address}") } ctx.state = StateRunning() } } }
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning06File.kt
1443693066
/* * Copyright (C) 2010 ZXing 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 com.tamsiree.rxfeature.scaner.decoding import android.app.Activity import android.content.DialogInterface /** * Simple listener used to exit the app in a few cases. * @author tamsiree */ class FinishListener(private val activityToFinish: Activity) : DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable { override fun onCancel(dialogInterface: DialogInterface) { run() } override fun onClick(dialogInterface: DialogInterface, i: Int) { run() } override fun run() { activityToFinish.finish() } }
RxFeature/src/main/java/com/tamsiree/rxfeature/scaner/decoding/FinishListener.kt
1230692567
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <mail@vanit.as> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.activity import android.app.Activity import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.support.annotation.DrawableRes import android.support.annotation.XmlRes import android.support.v4.app.Fragment import android.support.v4.view.ViewCompat import android.support.v7.app.AlertDialog import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import android.support.v7.preference.PreferenceFragmentCompat.OnPreferenceStartFragmentCallback import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import android.widget.AdapterView.OnItemClickListener import kotlinx.android.synthetic.main.activity_settings.* import org.mariotaku.chameleon.Chameleon import org.mariotaku.ktextension.Bundle import org.mariotaku.ktextension.set import de.vanita5.twittnuker.R import de.vanita5.twittnuker.constant.IntentConstants.* import de.vanita5.twittnuker.constant.KeyboardShortcutConstants.ACTION_NAVIGATION_BACK import de.vanita5.twittnuker.constant.KeyboardShortcutConstants.CONTEXT_TAG_NAVIGATION import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.onShow import de.vanita5.twittnuker.fragment.* import de.vanita5.twittnuker.util.DeviceUtils import de.vanita5.twittnuker.util.KeyboardShortcutsHandler import de.vanita5.twittnuker.util.ThemeUtils import java.util.* class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartFragmentCallback { var shouldRecreate: Boolean = false var shouldRestart: Boolean = false var shouldTerminate: Boolean = false private lateinit var entriesAdapter: EntriesAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) entriesAdapter = EntriesAdapter(this) if (savedInstanceState != null) { shouldRecreate = savedInstanceState.getBoolean(EXTRA_SHOULD_RECREATE, shouldRecreate) shouldRestart = savedInstanceState.getBoolean(EXTRA_SHOULD_RESTART, shouldRestart) shouldTerminate = savedInstanceState.getBoolean(EXTRA_SHOULD_TERMINATE, shouldTerminate) } else if (intent.getBooleanExtra(EXTRA_SHOULD_TERMINATE, false)) { finishNoRestart() System.exit(0) return } val backgroundOption = currentThemeBackgroundOption val backgroundAlpha = currentThemeBackgroundAlpha detailFragmentContainer.setBackgroundColor(ThemeUtils.getColorBackground(this, backgroundOption, backgroundAlpha)) slidingPane.setShadowResourceLeft(R.drawable.sliding_pane_shadow_left) slidingPane.setShadowResourceRight(R.drawable.sliding_pane_shadow_right) slidingPane.sliderFadeColor = 0 ViewCompat.setOnApplyWindowInsetsListener(slidingPane) listener@ { view, insets -> onApplyWindowInsets(view, insets) entriesList.setPadding(0, insets.systemWindowInsetTop, 0, insets.systemWindowInsetBottom) return@listener insets } initEntries() entriesList.adapter = entriesAdapter entriesList.choiceMode = AbsListView.CHOICE_MODE_SINGLE entriesList.onItemClickListener = this //Twittnuker - Settings pane opened slidingPane.openPane() if (savedInstanceState == null) { val initialTag = intent.data?.authority var initialItem = -1 var firstEntry = -1 for (i in 0 until entriesAdapter.count) { val entry = entriesAdapter.getItem(i) if (entry is PreferenceEntry) { if (firstEntry == -1) { firstEntry = i } if (initialTag == entry.tag) { initialItem = i break } } } if (initialItem == -1) { initialItem = firstEntry } if (initialItem != -1) { openDetails(initialItem) entriesList.setItemChecked(initialItem, true) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == RESULT_SETTINGS_CHANGED && data != null) { shouldRecreate = data.getBooleanExtra(EXTRA_SHOULD_RECREATE, false) shouldRestart = data.getBooleanExtra(EXTRA_SHOULD_RESTART, false) shouldTerminate = data.getBooleanExtra(EXTRA_SHOULD_TERMINATE, false) } super.onActivityResult(requestCode, resultCode, data) } override fun finish() { if (shouldRecreate || shouldRestart) { val data = Intent() data.putExtra(EXTRA_SHOULD_RECREATE, shouldRecreate) data.putExtra(EXTRA_SHOULD_RESTART, shouldRestart) setResult(RESULT_SETTINGS_CHANGED, data) } super.finish() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(EXTRA_SHOULD_RECREATE, shouldRecreate) outState.putBoolean(EXTRA_SHOULD_RESTART, shouldRestart) } override fun handleKeyboardShortcutSingle(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean { val action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState) if (ACTION_NAVIGATION_BACK == action) { onBackPressed() return true } return super.handleKeyboardShortcutSingle(handler, keyCode, event, metaState) } override fun isKeyboardShortcutHandled(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean { val action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState) return ACTION_NAVIGATION_BACK == action } override fun handleKeyboardShortcutRepeat(handler: KeyboardShortcutsHandler, keyCode: Int, repeatCount: Int, event: KeyEvent, metaState: Int): Boolean { return super.handleKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState) } override fun onSupportNavigateUp(): Boolean { if (notifyUnsavedChange()) { return true } return super.onSupportNavigateUp() } override fun onBackPressed() { if (notifyUnsavedChange()) return super.onBackPressed() } override fun onPreferenceStartFragment(fragment: PreferenceFragmentCompat, preference: Preference): Boolean { val fm = supportFragmentManager val ft = fm.beginTransaction() val f = Fragment.instantiate(this, preference.fragment, preference.extras) ft.replace(R.id.detailFragmentContainer, f) ft.addToBackStack(preference.title.toString()) ft.commit() return true } override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { openDetails(position) } private fun finishNoRestart() { super.finish() } private val isTopSettings: Boolean = true private fun initEntries() { entriesAdapter.addHeader(getString(R.string.appearance)) entriesAdapter.addPreference("theme", R.drawable.ic_action_color_palette, getString(R.string.theme), R.xml.preferences_theme) entriesAdapter.addPreference("cards", R.drawable.ic_action_card, getString(R.string.cards), R.xml.preferences_cards) if (DeviceUtils.isDeviceTablet(this)) { entriesAdapter.addPreference("tablet_mode", R.drawable.ic_action_tablet, getString(R.string.preference_title_tablet_mode), R.xml.preferences_tablet_mode) } entriesAdapter.addHeader(getString(R.string.function)) entriesAdapter.addPreference("tabs", R.drawable.ic_action_tab, getString(R.string.tabs), CustomTabsFragment::class.java) entriesAdapter.addPreference("refresh", R.drawable.ic_action_refresh, getString(R.string.action_refresh), R.xml.preferences_refresh) entriesAdapter.addPreference("streaming", R.drawable.ic_action_streaming, getString(R.string.settings_streaming), R.xml.preferences_streaming) entriesAdapter.addPreference("notifications", R.drawable.ic_action_notification, getString(R.string.settings_notifications), R.xml.preferences_notifications) entriesAdapter.addPreference("network", R.drawable.ic_action_web, getString(R.string.network), R.xml.preferences_network) entriesAdapter.addPreference("compose", R.drawable.ic_action_status_compose, getString(R.string.action_compose), R.xml.preferences_compose) entriesAdapter.addPreference("content", R.drawable.ic_action_twittnuker_square, getString(R.string.content), R.xml.preferences_content) entriesAdapter.addPreference("storage", R.drawable.ic_action_storage, getString(R.string.preference_title_storage), R.xml.preferences_storage) entriesAdapter.addPreference("other", R.drawable.ic_action_more_horizontal, getString(R.string.other_settings), R.xml.preferences_other) entriesAdapter.addHeader(getString(R.string.title_about)) entriesAdapter.addPreference("about", R.drawable.ic_action_info, getString(R.string.title_about), R.xml.preferences_about) val browserArgs = Bundle() browserArgs.putString(EXTRA_URI, "file:///android_asset/gpl-3.0-standalone.html") entriesAdapter.addPreference("license", R.drawable.ic_action_open_source, getString(R.string.title_open_source_license), BrowserFragment::class.java, browserArgs) } private fun openDetails(position: Int) { if (isFinishing) return val entry = entriesAdapter.getItem(position) as? PreferenceEntry ?: return val fm = supportFragmentManager fm.popBackStackImmediate(null, 0) val ft = fm.beginTransaction() if (entry.preference != 0) { val args = Bundle() args.putInt(EXTRA_RESID, entry.preference) val f = Fragment.instantiate(this, SettingsDetailsFragment::class.java.name, args) ft.replace(R.id.detailFragmentContainer, f) } else if (entry.fragment != null) { ft.replace(R.id.detailFragmentContainer, Fragment.instantiate(this, entry.fragment, entry.args)) } ft.setBreadCrumbTitle(entry.title) ft.commit() //KEEP disable closing pane //slidingPane.closePane() } private fun notifyUnsavedChange(): Boolean { if (isTopSettings && (shouldRecreate || shouldRestart || shouldTerminate)) { executeAfterFragmentResumed { if (it.isFinishing) return@executeAfterFragmentResumed it as SettingsActivity val df = RestartConfirmDialogFragment() df.arguments = Bundle { this[EXTRA_SHOULD_RECREATE] = it.shouldRecreate this[EXTRA_SHOULD_RESTART] = it.shouldRestart this[EXTRA_SHOULD_TERMINATE] = it.shouldTerminate } df.show(it.supportFragmentManager, "restart_confirm") } return true } return false } internal class EntriesAdapter(context: Context) : BaseAdapter() { private val inflater: LayoutInflater = LayoutInflater.from(context) private val entries: MutableList<Entry> = ArrayList() fun addPreference(tag: String, @DrawableRes icon: Int, title: String, @XmlRes preference: Int) { entries.add(PreferenceEntry(tag, icon, title, preference, null, null)) notifyDataSetChanged() } fun addPreference(tag: String, @DrawableRes icon: Int, title: String, cls: Class<out Fragment>, args: Bundle? = null) { entries.add(PreferenceEntry(tag, icon, title, 0, cls.name, args)) notifyDataSetChanged() } fun addHeader(title: String) { entries.add(HeaderEntry(title)) notifyDataSetChanged() } override fun getCount(): Int { return entries.size } override fun getItem(position: Int): Entry { return entries[position] } override fun getItemId(position: Int): Long { return getItem(position).hashCode().toLong() } override fun isEnabled(position: Int): Boolean { return getItemViewType(position) == VIEW_TYPE_PREFERENCE_ENTRY } override fun getViewTypeCount(): Int { return 2 } override fun getItemViewType(position: Int): Int { val entry = getItem(position) if (entry is PreferenceEntry) { return VIEW_TYPE_PREFERENCE_ENTRY } else if (entry is HeaderEntry) { return VIEW_TYPE_HEADER_ENTRY } throw UnsupportedOperationException() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val viewType = getItemViewType(position) val entry = getItem(position) val view: View = convertView ?: let { when (viewType) { VIEW_TYPE_PREFERENCE_ENTRY -> { return@let inflater.inflate(R.layout.list_item_preference_header_item, parent, false) } VIEW_TYPE_HEADER_ENTRY -> { return@let inflater.inflate(R.layout.list_item_preference_header_category, parent, false) } else -> { throw UnsupportedOperationException() } } } entry.bind(view) return view } companion object { val VIEW_TYPE_PREFERENCE_ENTRY = 0 val VIEW_TYPE_HEADER_ENTRY = 1 } } internal abstract class Entry { abstract fun bind(view: View) } internal class PreferenceEntry( val tag: String, val icon: Int, val title: String, val preference: Int, val fragment: String?, val args: Bundle? ) : Entry() { override fun bind(view: View) { view.findViewById<ImageView>(android.R.id.icon).setImageResource(icon) view.findViewById<TextView>(android.R.id.title).text = title } } internal class HeaderEntry(private val title: String) : Entry() { override fun bind(view: View) { val theme = Chameleon.getOverrideTheme(view.context, view.context) val textView: TextView = view.findViewById(android.R.id.title) textView.setTextColor(ThemeUtils.getOptimalAccentColor(theme.colorAccent, theme.colorForeground)) textView.text = title } } class RestartConfirmDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(activity) if (arguments.getBoolean(EXTRA_SHOULD_TERMINATE)) { builder.setMessage(R.string.app_terminate_confirm) builder.setNegativeButton(R.string.action_dont_terminate, this) } else { builder.setMessage(R.string.app_restart_confirm) builder.setNegativeButton(R.string.action_dont_restart, this) } builder.setPositiveButton(android.R.string.ok, this) val dialog = builder.create() dialog.onShow { it.applyTheme() } return dialog } override fun onClick(dialog: DialogInterface, which: Int) { val activity = activity as SettingsActivity when (which) { DialogInterface.BUTTON_POSITIVE -> { if (arguments.getBoolean(EXTRA_SHOULD_TERMINATE)) { val intent = Intent(context, SettingsActivity::class.java) intent.putExtra(EXTRA_SHOULD_TERMINATE, true) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) activity.startActivity(intent) } else { activity.finish() } } DialogInterface.BUTTON_NEGATIVE -> { activity.finishNoRestart() } } } } companion object { private val RESULT_SETTINGS_CHANGED = 10 fun setShouldRecreate(activity: Activity) { if (activity !is SettingsActivity) return activity.shouldRecreate = true } fun setShouldRestart(activity: Activity) { if (activity !is SettingsActivity) return activity.shouldRestart = true } fun setShouldTerminate(activity: Activity) { if (activity !is SettingsActivity) return activity.shouldTerminate = true } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/SettingsActivity.kt
2309914442
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <mail@vanit.as> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.loader.statuses import android.content.Context import android.support.annotation.WorkerThread import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.microblog.library.twitter.model.ResponseList import de.vanita5.microblog.library.twitter.model.Status import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.annotation.FilterScope import de.vanita5.twittnuker.extension.model.api.mastodon.mapToPaginated import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.PaginatedList import de.vanita5.twittnuker.util.database.ContentFiltersUtils class UserFavoritesLoader( context: Context, accountKey: UserKey?, private val userKey: UserKey?, private val screenName: String?, data: List<ParcelableStatus>?, savedStatusesArgs: Array<String>?, tabPosition: Int, fromUser: Boolean, loadingMore: Boolean ) : AbsRequestStatusesLoader(context, accountKey, data, savedStatusesArgs, tabPosition, fromUser, loadingMore) { @Throws(MicroBlogException::class) override fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> { when (account.type) { AccountType.MASTODON -> { return getMastodonStatuses(account, paging) } } return getMicroBlogStatuses(account, paging).mapMicroBlogToPaginated { it.toParcelable(account, profileImageSize) } } @WorkerThread override fun shouldFilterStatus(status: ParcelableStatus): Boolean { return ContentFiltersUtils.isFiltered(context.contentResolver, status, false, FilterScope.FAVORITES) } private fun getMicroBlogStatuses(account: AccountDetails, paging: Paging): ResponseList<Status> { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) if (userKey != null) { return microBlog.getFavorites(userKey.id, paging) } else if (screenName != null) { return microBlog.getFavoritesByScreenName(screenName, paging) } throw MicroBlogException("Null user") } private fun getMastodonStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> { if (userKey != null && userKey != account.key) { throw MicroBlogException("Only current account favorites is supported") } if (screenName != null && !screenName.equals(account.user?.screen_name, ignoreCase = true)) { throw MicroBlogException("Only current account favorites is supported") } val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java) return mastodon.getFavourites(paging).mapToPaginated { it.toParcelable(account) } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/statuses/UserFavoritesLoader.kt
964305205
package org.wikipedia.feed.announcement import android.net.Uri import org.wikipedia.feed.model.Card import org.wikipedia.feed.model.CardType open class AnnouncementCard(private val announcement: Announcement) : Card() { val isArticlePlacement get() = Announcement.PLACEMENT_ARTICLE == announcement.placement override fun title(): String { return announcement.type } override fun extract(): String? { return announcement.text } override fun image(): Uri { return Uri.parse(announcement.imageUrl.orEmpty()) } override fun type(): CardType { return CardType.ANNOUNCEMENT } override fun dismissHashCode(): Int { return announcement.id.hashCode() } fun imageHeight(): Int { return announcement.imageHeight.orEmpty().ifEmpty { "0" }.toIntOrNull() ?: 0 } fun hasAction(): Boolean { return announcement.hasAction() } fun actionTitle(): String { return announcement.actionTitle() } fun actionUri(): Uri { return Uri.parse(announcement.actionUrl()) } fun negativeText(): String? { return announcement.negativeText } fun hasFooterCaption(): Boolean { return announcement.hasFooterCaption() } fun footerCaption(): String { return announcement.footerCaption.orEmpty() } fun hasImage(): Boolean { return announcement.hasImageUrl() } fun hasBorder(): Boolean { return announcement.border == true } }
app/src/main/java/org/wikipedia/feed/announcement/AnnouncementCard.kt
2046507084
package net.semlang.internal.test import net.semlang.api.CURRENT_NATIVE_MODULE_VERSION import net.semlang.api.ValidatedModule import net.semlang.modules.getDefaultLocalRepository import net.semlang.modules.parseAndValidateModuleDirectory import java.io.File /** * First argument: Standalone compilable file as a File * Second argument: List of ValidatedModules to be used as libraries */ fun getCompilableFilesWithAssociatedLibraries(): Collection<Array<Any?>> { val compilerTestsFolder = File("../../semlang-parser-tests/pass") val corpusFolder = File("../../semlang-corpus/src/main/semlang") val standardLibraryCorpusFolder = File("../../semlang-library-corpus/src/main/semlang") val allResults = ArrayList<Array<Any?>>() val allStandaloneFiles = compilerTestsFolder.listFiles() + corpusFolder.listFiles() allResults.addAll(allStandaloneFiles.map { file -> arrayOf<Any?>(file, listOf<Any?>()) }) val standardLibrary: ValidatedModule = validateStandardLibraryModule() allResults.addAll(standardLibraryCorpusFolder.listFiles().map { file -> arrayOf<Any?>(file, listOf(standardLibrary)) }) return allResults } fun validateStandardLibraryModule(): ValidatedModule { val standardLibraryFolder = File("../../semlang-library/src/main/semlang") return parseAndValidateModuleDirectory(standardLibraryFolder, CURRENT_NATIVE_MODULE_VERSION, getDefaultLocalRepository()).assumeSuccess() }
kotlin/semlang-module-test-utils/src/main/kotlin/moduleCorpuses.kt
2413805025
package training import org.deeplearning4j.earlystopping.EarlyStoppingConfiguration import org.deeplearning4j.earlystopping.saver.InMemoryModelSaver import org.deeplearning4j.earlystopping.scorecalc.DataSetLossCalculator import org.deeplearning4j.earlystopping.termination.MaxEpochsTerminationCondition import org.deeplearning4j.earlystopping.termination.MaxTimeIterationTerminationCondition import org.deeplearning4j.earlystopping.trainer.EarlyStoppingTrainer import org.deeplearning4j.nn.api.OptimizationAlgorithm import org.deeplearning4j.nn.conf.NeuralNetConfiguration import org.deeplearning4j.nn.conf.layers.DenseLayer import org.deeplearning4j.nn.conf.layers.OutputLayer import org.deeplearning4j.nn.multilayer.MultiLayerNetwork import org.deeplearning4j.nn.weights.WeightInit import org.nd4j.linalg.activations.Activation import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize import org.nd4j.linalg.dataset.api.preprocessor.serializer.NormalizerSerializer import org.nd4j.linalg.lossfunctions.LossFunctions import resource import sg.studium.neurals.dataset.InMemoryDataSetIterator import sg.studium.neurals.dataset.csvToXY import sg.studium.neurals.model.Dl4jModel import java.io.FileOutputStream import java.util.concurrent.TimeUnit /** * Speed: 14199 epochs in 2 minutes on T460p I7 nd4j-native * Score: 0.7069 @ epoch 14198 */ class TrainClassificationInMemory { companion object { @JvmStatic fun main(args: Array<String>) { val batchSize = 10 val iterator = InMemoryDataSetIterator(csvToXY(resource("iris.onehot.csv"), "class"), batchSize) val normalizer = NormalizerStandardize() normalizer.fit(iterator) iterator.preProcessor = normalizer val netConf = NeuralNetConfiguration.Builder() .seed(123) .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .learningRate(0.001) .iterations(1) .list( DenseLayer.Builder() .nIn(iterator.inputColumns()) .nOut(iterator.inputColumns()) .weightInit(WeightInit.XAVIER) .activation(Activation.SIGMOID) .build(), OutputLayer.Builder(LossFunctions.LossFunction.XENT) .nIn(iterator.inputColumns()) .nOut(iterator.totalOutcomes()) .weightInit(WeightInit.XAVIER) .activation(Activation.SIGMOID) .build() ) .pretrain(false) .backprop(true) .build() val net = MultiLayerNetwork(netConf) val esms = InMemoryModelSaver<MultiLayerNetwork>() val esc = EarlyStoppingConfiguration.Builder<MultiLayerNetwork>() // .epochTerminationConditions(MaxEpochsTerminationCondition(1000)) .iterationTerminationConditions(MaxTimeIterationTerminationCondition(2, TimeUnit.MINUTES)) .scoreCalculator(DataSetLossCalculator(iterator, false)) .modelSaver(esms) .build() val trainer = EarlyStoppingTrainer(esc, net, iterator) val result = trainer.fit() println(result) val bestModel = result.bestModel val dl4jModel = Dl4jModel.build(iterator.getAllColumns(), iterator.getlYColumns(), normalizer, bestModel) dl4jModel.save(FileOutputStream("/tmp/iris.onehot.dl4jmodel.zip")) val xy = csvToXY(resource("iris.onehot.csv"), "class") xy.X.forEach { println(dl4jModel.predict(it).toList()) } // ModelSerializer.writeModel(bestModel, "/tmp/iris.onehot.model.inmemory.zip", true) } } }
src/test/java/training/TrainClassificationInMemory.kt
3054022144
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.Page /** * List of the logged in user's [ConnectedApps][ConnectedApp]. */ @JsonClass(generateAdapter = true) data class ConnectedAppList( @Json(name = "total") override val total: Int? = null, @Json(name = "data") override val data: List<ConnectedApp>? = null, @Json(name = "filtered_total") override val filteredTotal: Int? = null ) : Page<ConnectedApp>
models/src/main/java/com/vimeo/networking2/ConnectedAppList.kt
2243526932
package com.github.kittinunf.fuel.util import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty internal fun <T> readWriteLazy(initializer: () -> T): ReadWriteProperty<Any?, T> = ReadWriteLazyVal(initializer) private class ReadWriteLazyVal<T>(private val initializer: () -> T) : ReadWriteProperty<Any?, T> { private var value: Any? = null override operator fun getValue(thisRef: Any?, property: KProperty<*>): T { if (value == null) { value = (initializer()) ?: throw IllegalStateException("Initializer block of property ${property.name} return null") } @Suppress("UNCHECKED_CAST") return value as T } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } }
fuel/src/main/kotlin/com/github/kittinunf/fuel/util/Delegates.kt
3936497282
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.ksp import androidx.room.compiler.processing.ksp.synthetic.KspSyntheticFileMemberContainer import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSPropertyAccessor import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.Modifier /** * Finds the class that contains this declaration and throws [IllegalStateException] if it cannot * be found. * @see [findEnclosingAncestorClassDeclaration] */ internal fun KSDeclaration.requireEnclosingMemberContainer( env: KspProcessingEnv ): KspMemberContainer { return checkNotNull(findEnclosingMemberContainer(env)) { "Cannot find required enclosing type for $this" } } /** * Find the class that contains this declaration. * * Node that this is not necessarily the parent declaration. e.g. when a property is declared in * a constructor, its containing type is actual two levels up. */ @OptIn(KspExperimental::class) internal fun KSDeclaration.findEnclosingMemberContainer( env: KspProcessingEnv ): KspMemberContainer? { val memberContainer = findEnclosingAncestorClassDeclaration()?.let { env.wrapClassDeclaration(it) } ?: this.containingFile?.let { env.wrapKSFile(it) } memberContainer?.let { return it } // in compiled files, we may not find it. Try using the binary name val ownerJvmClassName = when (this) { is KSPropertyDeclaration -> env.resolver.getOwnerJvmClassName(this) is KSFunctionDeclaration -> env.resolver.getOwnerJvmClassName(this) else -> null } ?: return null // Binary name of a top level type is its canonical name. So we just load it directly by // that value env.findTypeElement(ownerJvmClassName)?.let { return it } // When a top level function/property is compiled, its containing class does not exist in KSP, // neither the file. So instead, we synthesize one return KspSyntheticFileMemberContainer(ownerJvmClassName) } private fun KSDeclaration.findEnclosingAncestorClassDeclaration(): KSClassDeclaration? { var parent = parentDeclaration while (parent != null && parent !is KSClassDeclaration) { parent = parent.parentDeclaration } return parent as? KSClassDeclaration } internal fun KSDeclaration.isStatic(): Boolean { return modifiers.contains(Modifier.JAVA_STATIC) || hasJvmStaticAnnotation() || // declarations in the companion object move into the enclosing class as statics. // https://kotlinlang.org/docs/java-to-kotlin-interop.html#static-fields this.findEnclosingAncestorClassDeclaration()?.isCompanionObject == true || when (this) { is KSPropertyAccessor -> this.receiver.findEnclosingAncestorClassDeclaration() == null is KSPropertyDeclaration -> this.findEnclosingAncestorClassDeclaration() == null is KSFunctionDeclaration -> this.findEnclosingAncestorClassDeclaration() == null else -> false } } internal fun KSDeclaration.isTransient(): Boolean { return modifiers.contains(Modifier.JAVA_TRANSIENT) || hasJvmTransientAnnotation() }
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KSDeclarationExt.kt
1273064938
package de.sudoq.persistence import org.amshove.kluent.* import org.junit.jupiter.api.Test class XmlAttributeTests { @Test fun testConstructorStringStringIllegalArgumentException2() { invoking { XmlAttribute("", "value") } .`should throw`(IllegalArgumentException::class) } @Test fun testGetName() { val attribute = XmlAttribute("xyzName", "") attribute.name `should be equal to` "xyzName" } @Test fun testGetValue() { val attribute = XmlAttribute("xyzName", "xyzValue") attribute.value `should be equal to` "xyzValue" } @Test fun testIsSameAttribute() { val a = XmlAttribute("xyzName", "value") val b = XmlAttribute("xyzName","differentvalue") a.isSameAttribute(b).`should be true`() } }
sudoq-app/sudoqapp/src/test/kotlin/de/sudoq/persistence/XmlAttributeTests.kt
3857906581
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.impl import org.rust.ide.formatter.RsAlignmentStrategy import org.rust.ide.formatter.blocks.RsFmtBlock import org.rust.lang.core.psi.RsElementTypes.* fun RsFmtBlock.getAlignmentStrategy(): RsAlignmentStrategy = when (node.elementType) { TUPLE_EXPR, VALUE_ARGUMENT_LIST, in SPECIAL_MACRO_ARGS, USE_GROUP -> RsAlignmentStrategy.wrap() .alignIf { child, parent, _ -> // Do not align if we have only one argument as this may lead to // some quirks when that argument is tuple expr. // Alignment do not allow "negative indentation" i.e.: // func(( // happy tuple param // )) // would be formatted to: // func(( // happy tuple param // )) // because due to applied alignment, closing paren has to be // at least in the same column as the opening one. var result = true if (parent != null) { val lBrace = parent.firstChildNode val rBrace = parent.lastChildNode if (lBrace.isBlockDelim(parent) && rBrace.isBlockDelim(parent)) { result = child.treeNonWSPrev() != lBrace || child.treeNonWSNext() != rBrace } } result } .alignUnlessBlockDelim() .alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS) TUPLE_TYPE, TUPLE_FIELDS -> RsAlignmentStrategy.wrap() .alignUnlessBlockDelim() .alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS) VALUE_PARAMETER_LIST -> RsAlignmentStrategy.shared() .alignUnlessBlockDelim() .alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS) in FN_DECLS -> RsAlignmentStrategy.shared() .alignIf { c, _, _ -> c.elementType == RET_TYPE && ctx.rustSettings.ALIGN_RET_TYPE || c.elementType == WHERE_CLAUSE && ctx.rustSettings.ALIGN_WHERE_CLAUSE } PAT_TUPLE_STRUCT -> RsAlignmentStrategy.wrap() .alignIf { c, p, x -> x.metLBrace && !c.isBlockDelim(p) } .alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS) DOT_EXPR -> RsAlignmentStrategy.shared() .alignIf(DOT) // DOT is synthetic's block representative .alignIf(ctx.commonSettings.ALIGN_MULTILINE_CHAINED_METHODS) WHERE_CLAUSE -> RsAlignmentStrategy.wrap() .alignIf(WHERE_PRED) .alignIf(ctx.rustSettings.ALIGN_WHERE_BOUNDS) TYPE_PARAMETER_LIST -> RsAlignmentStrategy.wrap() .alignIf(TYPE_PARAMETER, LIFETIME_PARAMETER) .alignIf(ctx.rustSettings.ALIGN_TYPE_PARAMS) FOR_LIFETIMES -> RsAlignmentStrategy.wrap() .alignIf(LIFETIME_PARAMETER) .alignIf(ctx.rustSettings.ALIGN_TYPE_PARAMS) else -> RsAlignmentStrategy.NullStrategy } fun RsAlignmentStrategy.alignUnlessBlockDelim(): RsAlignmentStrategy = alignIf { c, p, _ -> !c.isBlockDelim(p) }
src/main/kotlin/org/rust/ide/formatter/impl/alignment.kt
2602237253
package com.tenebras.spero.route.uri class SegmentParam(val name: String) { companion object { fun fromString(str: String): SegmentParam { return SegmentParam(str) } } }
src/main/kotlin/com/tenebras/spero/route/uri/SegmentParam.kt
2962179513
package com.teamwizardry.librarianlib.foundation.util import net.minecraft.block.Block import net.minecraft.entity.EntityType import net.minecraft.fluid.Fluid import net.minecraft.item.Item import net.minecraft.tags.* import net.minecraft.util.Identifier /** * A utility class for easily creating tags. * * **Note:** You'll almost always want to create an item tag when you create a block tag. You can do this using * [itemFormOf], and you can specify their equivalence using * `registrationManager.datagen.blockTags.addItemForm(blockTag, itemTag)` */ public object TagWrappers { /** * Creates a tag for the item form of the given block. i.e. creates an item tag with the same ID as the block tag. */ @JvmStatic public fun itemFormOf(blockTag: ITag.INamedTag<Block>): ITag.INamedTag<Item> = item(blockTag.name) @JvmStatic public fun block(name: String): ITag.INamedTag<Block> = BlockTags.makeWrapperTag(name) @JvmStatic public fun entityType(name: String): ITag.INamedTag<EntityType<*>> = EntityTypeTags.getTagById(name) @JvmStatic public fun fluid(name: String): ITag.INamedTag<Fluid> = FluidTags.makeWrapperTag(name) @JvmStatic public fun item(name: String): ITag.INamedTag<Item> = ItemTags.makeWrapperTag(name) @JvmStatic public fun block(modid: String, name: String): ITag.INamedTag<Block> = block(Identifier(modid, name)) @JvmStatic public fun entityType(modid: String, name: String): ITag.INamedTag<EntityType<*>> = entityType(Identifier(modid, name)) @JvmStatic public fun fluid(modid: String, name: String): ITag.INamedTag<Fluid> = fluid(Identifier(modid, name)) @JvmStatic public fun item(modid: String, name: String): ITag.INamedTag<Item> = item(Identifier(modid, name)) @JvmStatic public fun block(name: Identifier): ITag.INamedTag<Block> = BlockTags.makeWrapperTag(name.toString()) @JvmStatic public fun entityType(name: Identifier): ITag.INamedTag<EntityType<*>> = EntityTypeTags.getTagById(name.toString()) @JvmStatic public fun fluid(name: Identifier): ITag.INamedTag<Fluid> = FluidTags.makeWrapperTag(name.toString()) @JvmStatic public fun item(name: Identifier): ITag.INamedTag<Item> = ItemTags.makeWrapperTag(name.toString()) }
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/util/TagWrappers.kt
1396483183
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve import org.rust.MockRustcVersion import org.rust.WithoutExperimentalFeatures import org.rust.ide.experiments.RsExperiments import org.rust.lang.core.psi.RsImplItem import org.rust.lang.core.psi.ext.RsFieldDecl class RsResolveTest : RsResolveTestBase() { fun `test function argument`() = checkByCode(""" fn foo(x: i32, y: f64) -> f64 { //X y //^ } """) fun `test locals`() = checkByCode(""" fn foo() { let z = 92; //X z; //^ } """) fun `test shadowing`() = checkByCode(""" fn foo() { let z = 92; let z = 42; //X z; //^ } """) fun `test nested patterns`() = checkByCode(""" enum E { Variant(i32, i32) } struct S { field: E } fn main() { let S { field: E::Variant(x, _) } = S { field : E::Variant(0, 0) }; //X x; //^ } """) fun `test ref pattern`() = checkByCode(""" fn main() { let x = 92; if let Some(&y) = Some(&x) { //X y; //^ } } """) fun `test closure`() = checkByCode(""" fn main() { (0..10).map(|x| { //X x //^ })} """) fun `test match`() = checkByCode(""" fn main() { match Some(92) { Some(i) => { //X i //^ } _ => 0 }; } """) fun `test match if`() = checkByCode(""" fn main() { let a = true; //X match Some(92) { Some(i) if a => { //^ i } _ => 0 }; } """) fun `test match if 2`() = checkByCode(""" fn main() { match Some(92) { Some(i) //X if i < 5 => { //^ i } _ => 0 }; } """) fun `test match if let 1`() = checkByCode(""" fn main() { match Some(92) { Some(i) if let Some(i) = Some(i) => { //X i //^ } _ => 0 }; } """) fun `test match if let 2`() = checkByCode(""" fn main() { match Some(92) { Some(i) //X if let Some(i) = Some(i) => { //^ i } _ => 0 }; } """) fun `test match let chain 1`() = checkByCode(""" fn foo(x: Option<i32>) { match Some(92) { Some(x) //X if let Some(x) = x && let Some(x) = x => x, //^ _ => x }; } """) fun `test match let chain 2`() = checkByCode(""" fn foo(x: Option<i32>) { match Some(92) { Some(x) if let Some(x) = x //X && let Some(x) = x => x, //^ _ => x }; } """) fun `test match let chain 3`() = checkByCode(""" fn foo(x: Option<i32>) { match Some(92) { Some(x) if let Some(x) = x && let Some(x) = x => //X x, //^ _ => 0 }; } """) fun `test match let chain 4`() = checkByCode(""" fn foo(x: Option<i32>) { //X match Some(92) { Some(x) if let Some(x) = x && let Some(x) = x => 1, _ => x //^ }; } """) fun `test let`() = checkByCode(""" fn f(i: i32) -> Option<i32> {} fn bar() { if let Some(x) = f(42) { //X if let Some(y) = f(x) { //^ if let Some(z) = f(y) {} } } } """) fun `test let cycle 1`() = checkByCode(""" fn main() { let x = { x }; //^ unresolved } """) fun `test let cycle 2`() = checkByCode(""" fn main() { let x = 92; //X let x = x; //^ } """) fun `test let cycle 3`() = checkByCode(""" fn main() { if let Some(x) = x { } //^ unresolved } """) fun `test if let 1`() = checkByCode(""" fn main() { if let Some(i) = Some(92) { //X i; //^ } } """) fun `test if let 2`() = checkByCode(""" fn main() { if let Some(i) = Some(92) { } i; //^ unresolved } """) fun `test if let with or pattern 1`() = checkByCode(""" fn foo(x: V) { if let V1(v) | V2(v) = x { //X v; //^ } } """) fun `test if let with or pattern 2`() = checkByCode(""" fn foo(x: Option<V>) { if let Some(V1(v) | V2(v)) = x { //X v; //^ } } """) fun `test if let with or pattern 3`() = checkByCode(""" fn foo(x: Option<V>) { if let Some(L(V1(v) | V2(v)) | R(V1(v) | V2(v))) = x { //X v; //^ } } """) fun `test if let else branch`() = checkByCode(""" fn foo(x: Option<i32>) { //X if let Some(x) = x { x } else { x //^ } } """) fun `test if let chain 1`() = checkByCode(""" fn foo(x: Option<i32>) { if let Some(x) = x && //X let Some(x) = x { //^ x } else { x }; } """) fun `test if let chain 2`() = checkByCode(""" fn foo(x: Option<i32>) { //X if let Some(x) = x && let Some(x) = x { //^ x } else { x }; } """) fun `test if let chain 3`() = checkByCode(""" fn foo(x: Option<i32>) { if let Some(x) = x && let Some(x) = x { //X x //^ } else { x }; } """) fun `test if let chain 4`() = checkByCode(""" fn foo(x: Option<i32>) { //X if let Some(x) = x && let Some(x) = x { x } else { x //^ }; } """) fun `test while let 1`() = checkByCode(""" fn main() { while let Some(i) = Some(92) { //X i //^ } } """) fun `test while let 2`() = checkByCode(""" fn main() { while let Some(i) = Some(92) { } i; //^ unresolved } """) fun `test while let with or pattern 1`() = checkByCode(""" fn foo(x: V) { while let V1(v) | V2(v) = x { //X v; //^ } } """) fun `test while let with or pattern 2`() = checkByCode(""" fn foo(x: Option<V>) { while let Some(V1(v) | V2(v)) = x { //X v; //^ } } """) fun `test for`() = checkByCode(""" fn main() { for x in 0..10 { //X x; //^ } } """) fun `test for no leak`() = checkByCode(""" fn main() { for x in x { } //^ unresolved } """) fun `test let overlapping with mod`() = checkByCode(""" mod abc { pub fn foo() {} //X } fn main() { let abc = 1u32; abc::foo(); //^ } """) fun `test if let overlapping with mod`() = checkByCode(""" mod abc { pub fn foo() {} //X } fn main() { if let Some(abc) = Some(1u32) { abc::foo(); //^ } } """) fun `test while let overlapping with mod`() = checkByCode(""" mod abc { pub fn foo() {} //X } fn main() { while let Some(abc) = Some(1u32) { abc::foo(); //^ } } """) fun `test for overlapping with mod`() = checkByCode(""" mod abc { pub fn foo() {} //X } fn main() { for abc in Some(1u32).iter() { abc::foo(); //^ } } """) fun `test match overlapping with mod`() = checkByCode(""" mod abc { pub fn foo() {} //X } fn main() { match Some(1u32) { Some(abc) => { abc::foo(); //^ } None => {} } } """) fun `test lambda overlapping with mod`() = checkByCode(""" mod abc { pub fn foo() {} //X } fn main() { let zz = |abc: u32| { abc::foo(); //^ }; } """) fun `test trait method argument`() = checkByCode(""" trait T { fn foo(x: i32) { //X x; //^ } } """) fun `test impl method argument`() = checkByCode(""" impl T { fn foo(x: i32) { //X x; //^ } } """) fun `test struct patterns 1`() = checkByCode(""" #[derive(Default)] struct S { foo: i32 } fn main() { let S {foo} = S::default(); //X foo; //^ } """) fun `test struct patterns 2`() = checkByCode(""" #[derive(Default)] struct S { foo: i32 } fn main() { let S {foo: bar} = S::default(); //X bar; //^ } """) fun `test mod items 1`() = checkByCode(""" mod m { fn main() { foo() //^ } fn foo() { } //X } """) fun `test mod items 2`() = checkByCode(""" mod bar { pub fn foo() {} //X } mod baz { fn boo() {} mod foo { fn foo() { super::super::bar::foo() //^ } } } """) fun `test mod items 3`() = checkByCode(""" mod bar { pub fn foo() {} } mod baz { fn boo() {} mod foo { fn foo() { bar::foo() //^ unresolved } } } """) fun `test mod items 4`() = checkByCode(""" mod bar { pub fn foo() {} } mod baz { fn boo() {} //X mod foo { fn foo() { super::boo() //^ } } } """) fun `test mod items 5`() = checkByCode(""" mod bar { pub fn foo() {} } mod baz { fn boo() {} mod foo { fn foo() { boo() //^ unresolved } } } """) fun `test nested module`() = checkByCode(""" mod a { mod b { mod c { pub fn foo() { } //X } } fn main() { b::c::foo(); //^ } } """) fun `test self`() = checkByCode(""" //X fn foo() {} fn main() { self::foo(); //^ } """) fun `test self 2`() = checkByCode(""" fn foo() {} //X fn main() { self::foo(); //^ } """) fun `test self identifier`() = checkByCode(""" struct S; impl S { fn foo(&self) -> &S { //X self //^ } } """) fun `test super`() = checkByCode(""" fn foo() {} //X mod inner { fn main() { super::foo(); //^ } } """) fun `test nested super 1`() = checkByCode(""" mod foo { mod bar { fn main() { self::super::super::foo() //^ } } } fn foo() {} //X """) fun `test nested super 2`() = checkByCode(""" mod foo { mod bar { use self::super::super::foo; fn main() { foo(); //^ } } } fn foo() {} //X """) fun `test function and mod with same name`() = checkByCode(""" mod foo {} fn foo() {} //X fn main() { foo(); //^ } """) fun `test format positional`() = checkByCode(""" fn main() { let x = 92; //X println!("{}", x); //^ } """) fun `test format named`() = checkByCode(""" fn main() { let x = 92; let y = 62; //X print!("{} + {foo}", x, foo = y); //^ } """) fun `test dbg argument`() = checkByCode(""" fn main() { let x = 42; //X dbg!(x); //^ } """) fun `test enum variant 1`() = checkByCode(""" enum E { X } //X fn main() { let _ = E::X; //^ } """) fun `test enum Self in impl block`() = checkByCode(""" enum E { X } //X impl E { fn foo() -> Self { Self::X }} //^ """) fun `test enum Self in impl block for invalid self-containing struct`() = checkByCodeGeneric<RsImplItem>(""" struct E { value: Self } impl E { //X fn new() -> Self { Self } //^ } """) fun `test enum variant 2`() = checkByCode(""" enum E { X, Y(X) } //^ unresolved """) fun `test enum variant 3`() = checkByCode(""" use E::A; enum E { A { a: u32 }, //X } fn main() { let e = A { a: 10 }; //^ } """) fun `test enum variant in match pattern`() = checkByCode(""" pub enum E { A } //X use E::*; fn func(x: E) { match x { A { .. } => {} } //^ } """) fun `test enum variant with alias`() = checkByCode(""" enum E { A } //X type T1 = E; fn main() { let _ = T1::A; } //^ """) fun `test struct field named`() = checkByCode(""" struct S { foo: i32 } //X fn main() { let _ = S { foo: 92 }; } //^ """) fun `test struct field positional`() = checkByCodeGeneric<RsFieldDecl>(""" struct S(i32, i32); //X fn main() { let _ = S { 1: 92 }; } //^ """) fun `test struct field with alias`() = checkByCode(""" struct S { foo: i32 } //X type T1 = S; type T2 = T1; fn main() { let _ = T2 { foo: 92 }; } //^ """) fun `test unknown struct field shorthand`() = checkByCode(""" fn main() { let foo = 62; //X let _ = UnknownStruct { foo }; } //^ """) fun `test cyclic type aliases`() = checkByCode(""" type Foo = Bar; type Bar = Foo; fn main() { let x = Foo { foo: 123 }; //^ unresolved } """) fun `test struct field Self`() = checkByCode(""" struct S { foo: i32 } //X impl S { fn new() -> Self { Self { foo: 0 } //^ } } """) fun `test type reference inside Self struct literal`() = checkByCode(""" struct A; //X struct S { foo: A } impl S { fn new() -> Self { Self { foo: A } //^ } } """) fun `test type reference struct literal that resolved to non-struct type`() = checkByCode(""" struct A; //X trait Trait {} fn main() { Trait { foo: A } //^ } """) fun `test Self-related item lookup`() = checkByCode(""" struct S; impl S { fn new() -> S { S } } //X trait T { fn x(); } impl T for S { fn x() { Self::new(); } //^ } """) fun `test method of Self type`() = checkByCode(""" struct S; impl S { fn foo(a: Self) { a.bar() } } //^ trait T { fn bar(&self) {} } //X impl T for S {} """) fun `test struct update syntax`() = checkByCode(""" struct S { f1: u32, f2: u8, } impl S { fn new() -> Self { //X S { f1: 0, f2: 0 } } } fn main() { let a = S { f1: 1, ..S::new() }; } //^ """) fun `test struct update syntax Default`() = checkByCode(""" trait Default { fn default() -> Self; } struct S { f1: u32, f2: u8, } impl Default for S { fn default() -> Self { //X S { f1: 0, f2: 0 } } } fn main() { let a = S { f1: 1, ..Default::default() }; } //^ """) fun `test enum field`() = checkByCode(""" enum E { X { foo: i32 } } //X fn main() { let _ = E::X { foo: 92 }; //^ } """) fun `test enum struct pattern`() = checkByCode(""" enum E { B { f: i32 } //X } fn process_message(msg: E) { match msg { E::B { .. } => {} //^ }; } """) fun `test non global path with colons`() = checkByCode(""" mod m { pub struct Matrix<T> { data: Vec<T> } //X pub fn apply(){ let _ = Matrix::<f32>::fill(); //^ } } """) fun `test type alias`() = checkByCode(""" type Foo = usize; //X trait T { type O; } struct S; impl T for S { type O = Foo; } //^ """) fun `test trait`() = checkByCode(""" trait Foo { } //X struct S; impl Foo for S { } //^ """) fun `test foreign fn`() = checkByCode(""" extern "C" { fn foo(); } //X fn main() { unsafe { foo() } //^ } """) fun `test foreign static`() = checkByCode(""" extern "C" { static FOO: i32; } //X fn main() { let _ = FOO; //^ } """) fun `test trait Self type`() = checkByCode(""" trait T { //X fn create() -> Self; //^ } """) fun `test struct Self type`() = checkByCode(""" pub struct S<'a> { //X field: &'a Self } //^ """) fun `test enum Self type`() = checkByCode(""" pub enum E<'a> { //X V { field: &'a Self } } //^ """) fun `test union def`() = checkByCode(""" union U { f: f64, u: u64 } //X fn foo(u: U) { } //^ """) fun `test unbound`() = checkByCode(""" fn foo() { y } //^ unresolved """) fun `test ordering`() = checkByCode(""" fn foo() { z; //^ unresolved let z = 92; } """) fun `test mod boundary`() = checkByCode(""" mod a { fn foo() {} mod b { fn main() { foo() //^ unresolved } } } """) fun `test follow path`() = checkByCode(""" fn main() { let x = 92; foo::x; //^ unresolved } """) fun `test self in static`() = checkByCode(""" struct S; impl S { fn foo() { self } //^ unresolved } """) fun `test wrong self`() = checkByCode(""" fn foo() {} fn main() { self::self::foo(); //^ unresolved } """) // We resolve this, although this usage of `super` is invalid. // Annotator will highlight it as an error. fun `test wrong super`() = checkByCode(""" fn foo() {} //X mod inner { fn main() { crate::inner::super::foo(); } //^ } """) fun `test function is not module`() = checkByCode(""" fn foo(bar: usize) {} fn main() { foo::bar // Yep, we used to resolve this! //^ unresolved } """) fun `test lifetime in function arguments`() = checkByCode(""" fn foo<'a>( //X a: &'a u32) {} //^ """) fun `test lifetime in function return type`() = checkByCode(""" fn foo<'a>() //X -> &'a u32 {} //^ """) fun `test lifetime in struct`() = checkByCode(""" struct Foo<'a> { //X a: &'a u32 } //^ """) fun `test lifetime in enum`() = checkByCode(""" enum Foo<'a> { //X BAR(&'a u32) } //^ """) fun `test lifetime in type alias`() = checkByCode(""" type Str<'a> //X = &'a str; //^ """) fun `test lifetime in impl`() = checkByCode(""" struct Foo<'a> { a: &'a str } impl<'a> //X Foo<'a> {} //^ """) fun `test lifetime in trait`() = checkByCode(""" trait Named<'a> { //X fn name(&self) -> &'a str; //^ } """) fun `test lifetime in fn parameters`() = checkByCode(""" fn foo<'a>( //X f: &'a Fn() -> &'a str) {} //^ """) fun `test lifetime in type param bounds`() = checkByCode(""" fn foo<'a, //X T: 'a>(a: &'a T) {} //^ """) fun `test lifetime in where clause`() = checkByCode(""" fn foo<'a, T>(a: &'a T) //X where T: 'a {} //^ """) fun `test lifetime in for lifetimes 1`() = checkByCode(""" fn foo_func<'a>(a: &'a u32) -> &'a u32 { a } const FOO: for<'a> fn(&'a u32) //X -> &'a u32 = foo_func; //^ """) fun `test lifetime in for lifetimes 2`() = checkByCode(""" fn foo<F>(f: F) where F: for<'a> //X Fn(&'a i32) {} //^ """) fun `test lifetime in for lifetimes 3`() = checkByCode(""" trait Foo<T> {} fn foo<T>(t: T) where for<'a> //X T: Foo<&'a T> {} //^ """) fun `test static lifetime unresolved`() = checkByCode(""" fn foo(name: &'static str) {} //^ unresolved """) @MockRustcVersion("1.23.0") fun `test in-band lifetime unresolved`() = checkByCode(""" fn foo( x: &'a str, y: &'a str //^ unresolved ) {} """) @MockRustcVersion("1.23.0-nightly") fun `test in-band lifetime resolve`() = checkByCode(""" #![feature(in_band_lifetimes)] fn foo( x: &'a str, //X y: &'a str //^ ) {} """) @MockRustcVersion("1.23.0-nightly") fun `test in-band lifetime single definition`() = checkByCode(""" #![feature(in_band_lifetimes)] fn foo( x: &'a str, //X y: &'a str ) { let z: &'a str = unimplemented!(); //^ } """) @MockRustcVersion("1.23.0-nightly") fun `test in-band lifetime no definition in body`() = checkByCode(""" #![feature(in_band_lifetimes)] fn foo() { let z: &'a str = unimplemented!(); //^ unresolved } """) @MockRustcVersion("1.23.0-nightly") fun `test in-band and explicit lifetimes`() = checkByCode(""" #![feature(in_band_lifetimes)] fn foo<'b>( x: &'a str, y: &'a str //^ unresolved ) {} """) @MockRustcVersion("1.23.0-nightly") fun `test in-band lifetime resolve in impl`() = checkByCode(""" #![feature(in_band_lifetimes)] trait T<'a> {} struct S<'a>(&'a str); impl T<'a> //X for S<'a> {} //^ """) @MockRustcVersion("1.23.0-nightly") fun `test in-band lifetime resolve in impl (where)`() = checkByCode(""" #![feature(in_band_lifetimes)] trait T<'a> {} struct S<'a>(&'a str); impl T<'a> //X for S<'a> where 'a: 'static {} //^ """) @MockRustcVersion("1.23.0-nightly") fun `test in-band lifetime resolve in impl and explicit lifetimes`() = checkByCode(""" #![feature(in_band_lifetimes)] trait T<'a> {} struct S<'a>(&'a str); impl <'b> T<'a> for S<'a> {} //^ unresolved """) fun `test loop label`() = checkByCode(""" fn foo() { 'a: loop { //X break 'a; //^ } } """) fun `test while loop label`() = checkByCode(""" fn foo() { 'a: while true { //X continue 'a; //^ } } """) fun `test for loop label`() = checkByCode(""" fn foo() { 'a: for _ in 0..3 { //X break 'a; //^ } } """) fun `test for loop label vs lifetime conflict 1`() = checkByCode(""" fn foo<'a>(a: &'a str) { 'a: for _ in 0..3 { //X break 'a; //^ } } """) fun `test for loop label vs lifetime conflict 2`() = checkByCode(""" fn foo<'a>(a: &'a str) { //X 'a: for _ in 0..3 { let _: &'a str = a; //^ } } """) fun `test block label`() = checkByCode(""" fn main() { let block_with_label = 'block: { //X if true { break 'block 1; } //^ 3 }; } """) fun `test nested for loop shadowing`() = checkByCode(""" fn main() { 'shadowed: for _ in 0..2 { 'shadowed: for _ in 0..2 { //X break 'shadowed; //^ } } } """) fun `test nested for loop without shadowing`() = checkByCode(""" fn main() { 'not_shadowed: for _ in 0..2 { //X 'another_label: for _ in 0..2 { break 'not_shadowed; //^ } } } """) fun `test nested for loop shadowing and macro`() = checkByCode(""" macro_rules! match_lifetimes { ($ lt:lifetime) => { break $ lt; } } fn main() { 'shadowed: for _ in 0..2 { 'shadowed: for _ in 0..2 { //X match_lifetimes!('shadowed); //^ } } } """) fun `test pattern constant binding ambiguity`() = checkByCode(""" const X: i32 = 0; //X fn foo(x: i32) { match x { X => 92 };//^ } """) fun `test pattern constant ambiguity 2`() = checkByCode(""" const NONE: () = (); //X fn main() { match () { NONE => NONE } } //^ """) fun `test pattern binding in let 1`() = checkByCode(""" struct S { foo: i32 } //X fn main() { let S { foo } = S { foo: 92 }; //^ let x = foo; } """) fun `test pattern binding in let 2`() = checkByCode(""" struct S { foo: i32 } //X type A = S; fn main() { let A { foo } = A { foo: 92 }; //^ let x = foo; } """) fun `test pattern constant binding ambiguity enum variant`() = checkByCode(""" enum Enum { Var1, Var2 } //X use Enum::Var1; fn main() { match Enum::Var1 { Var1 => {} //^ _ => {} } } """) fun `test pattern constant binding ambiguity unit struct`() = checkByCode(""" struct Foo; //X fn main() { match Foo { Foo => {} //^ } } """) fun `test match enum path`() = checkByCode(""" enum Enum { Var1, Var2 } //X fn main() { match Enum::Var1 { Enum::Var1 => {} //^ _ => {} } } """) fun `test associated type binding`() = checkByCode(""" trait Tr { type Item; } //X type T = Tr<Item=u8>; //^ """) fun `test inherited associated type binding`() = checkByCode(""" trait Tr1 { type Item; } //X trait Tr2: Tr1 {} type T = Tr2<Item=u8>; //^ """) fun `test associated type binding in (wrong) non-type context (fn call)`() = checkByCode(""" fn foo() {} fn main () { foo::<Item=u8>(); } //^ unresolved """) fun `test associated type binding in (wrong) non-type context (method call)`() = checkByCode(""" struct S; impl S { fn foo(&self) {} } fn main () { S.foo::<Item=u8>(); } //^ unresolved """) fun `test raw identifier 1`() = checkByCode(""" fn foo() { let r#match = 42; //X r#match; //^ } """) fun `test raw identifier 2`() = checkByCode(""" fn foo() {} //X fn main() { r#foo(); //^ } """) fun `test raw identifier 3`() = checkByCode(""" struct r#Foo; //X fn main() { let f = Foo; //^ } """) fun `test resolve path with crate keyword`() = checkByCode(""" mod foo { pub struct Foo; //X } use crate::foo::Foo; //^ """) fun `test resolve path with crate keyword 2`() = checkByCode(""" mod foo { pub struct Foo; //X } fn main() { let foo = crate::foo::Foo; //^ } """) @WithoutExperimentalFeatures(RsExperiments.DERIVE_PROC_MACROS) fun `test derive serde Serialize`() = checkByCode(""" #[lang = "serde::Serialize"] trait Serialize { fn serialize(&self); } //X #[derive(Serialize)] struct Foo; fn bar(foo: Foo) { foo.serialize(); //^ } """) fun `test 'pub (in path)' is crate-relative`() = checkByCode(""" mod foo { //X mod bar { pub(in foo) fn baz() {} } //^ } """) fun `test 'pub (in incomplete_path)'`() = checkByCode(""" mod foo { mod bar { pub(in foo::) fn baz() {} //X fn main() { // here we just check that incomplete path doesn't cause exceptions baz(); } //^ } } """) fun `test 'pub (self)'`() = checkByCode(""" mod bar { //X pub(self) fn baz() {} } //^ """) fun `test 'pub (super)'`() = checkByCode(""" mod foo { //X mod bar { pub(super) fn baz() {} } //^ } """) fun `test 'pub (self)' mod`() = checkByCode(""" mod foo { //X pub(self) mod bar {} } //^ """) fun `test extern crate self`() = checkByCode(""" extern crate self as foo; struct Foo; //X use foo::Foo; //^ """) fun `test extern crate self without alias`() = checkByCode(""" extern crate self; struct Foo; //X use self::Foo; //^ """) fun `test const generic in fn`() = checkByCode(""" fn f<const AAA: usize>() { //X AAA; //^ } """) fun `test const generic in struct`() = checkByCode(""" struct S<const AAA: usize> { //X x: [usize; AAA] //^ } """) fun `test const generic in trait`() = checkByCode(""" trait T<const AAA: usize> { //X const BBB: usize = AAA; //^ } """) fun `test const generic in enum`() = checkByCode(""" enum E<const AAA: usize> { //X V([usize; AAA]), //^ } """) fun `test Self with nested impls`() = checkByCodeGeneric<RsImplItem>(""" struct A; impl A { fn foo() { struct E { value: i32 } impl E { //X fn new() -> Self { //^ Self { value: h } } } } } """) }
src/test/kotlin/org/rust/lang/core/resolve/RsResolveTest.kt
716090392
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.annotation.web import org.springframework.context.ApplicationContext import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository import org.springframework.security.web.util.matcher.RequestMatcher import org.springframework.util.ClassUtils import jakarta.servlet.Filter import jakarta.servlet.http.HttpServletRequest /** * Configures [HttpSecurity] using a [HttpSecurity Kotlin DSL][HttpSecurityDsl]. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * authorizeRequests { * authorize("/public", permitAll) * authorize(anyRequest, authenticated) * } * formLogin { * loginPage = "/log-in" * } * } * } * } * ``` * * @author Eleftheria Stein * @author Norbert Nowak * @since 5.3 * @param httpConfiguration the configurations to apply to [HttpSecurity] */ operator fun HttpSecurity.invoke(httpConfiguration: HttpSecurityDsl.() -> Unit) = HttpSecurityDsl(this, httpConfiguration).build() /** * An [HttpSecurity] Kotlin DSL created by [`http { }`][invoke] * in order to configure [HttpSecurity] using idiomatic Kotlin code. * * @author Eleftheria Stein * @since 5.3 * @param http the [HttpSecurity] which all configurations will be applied to * @param init the configurations to apply to the provided [HttpSecurity] * @property authenticationManager the default [AuthenticationManager] to use */ @SecurityMarker class HttpSecurityDsl(private val http: HttpSecurity, private val init: HttpSecurityDsl.() -> Unit) { private val HANDLER_MAPPING_INTROSPECTOR = "org.springframework.web.servlet.handler.HandlerMappingIntrospector" var authenticationManager: AuthenticationManager? = null /** * Allows configuring the [HttpSecurity] to only be invoked when matching the * provided pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not an the classpath, it will use an ant matcher. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * securityMatcher("/private/&ast;&ast;") * formLogin { * loginPage = "/log-in" * } * } * } * } * ``` * * @param pattern one or more patterns used to determine whether this * configuration should be invoked. */ fun securityMatcher(vararg pattern: String) { val mvcPresent = ClassUtils.isPresent( HANDLER_MAPPING_INTROSPECTOR, AuthorizeRequestsDsl::class.java.classLoader) || ClassUtils.isPresent( HANDLER_MAPPING_INTROSPECTOR, AuthorizeHttpRequestsDsl::class.java.classLoader) this.http.requestMatchers { if (mvcPresent) { it.mvcMatchers(*pattern) } else { it.antMatchers(*pattern) } } } /** * Allows configuring the [HttpSecurity] to only be invoked when matching the * provided [RequestMatcher]. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * securityMatcher(AntPathRequestMatcher("/private/&ast;&ast;")) * formLogin { * loginPage = "/log-in" * } * } * } * } * ``` * * @param requestMatcher one or more [RequestMatcher] used to determine whether * this configuration should be invoked. */ fun securityMatcher(vararg requestMatcher: RequestMatcher) { this.http.requestMatchers { it.requestMatchers(*requestMatcher) } } /** * Enables form based authentication. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * formLogin { * loginPage = "/log-in" * } * } * } * } * ``` * * @param formLoginConfiguration custom configurations to be applied * to the form based authentication * @see [FormLoginDsl] */ fun formLogin(formLoginConfiguration: FormLoginDsl.() -> Unit) { val loginCustomizer = FormLoginDsl().apply(formLoginConfiguration).get() this.http.formLogin(loginCustomizer) } /** * Allows restricting access based upon the [HttpServletRequest] * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * authorizeRequests { * authorize("/public", permitAll) * authorize(anyRequest, authenticated) * } * } * } * } * ``` * * @param authorizeRequestsConfiguration custom configuration that specifies * access for requests * @see [AuthorizeRequestsDsl] */ fun authorizeRequests(authorizeRequestsConfiguration: AuthorizeRequestsDsl.() -> Unit) { val authorizeRequestsCustomizer = AuthorizeRequestsDsl().apply(authorizeRequestsConfiguration).get() this.http.authorizeRequests(authorizeRequestsCustomizer) } /** * Allows restricting access based upon the [HttpServletRequest] * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig { * * @Bean * fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { * http { * authorizeHttpRequests { * authorize("/public", permitAll) * authorize(anyRequest, authenticated) * } * } * return http.build() * } * } * ``` * * @param authorizeHttpRequestsConfiguration custom configuration that specifies * access for requests * @see [AuthorizeHttpRequestsDsl] * @since 5.7 */ fun authorizeHttpRequests(authorizeHttpRequestsConfiguration: AuthorizeHttpRequestsDsl.() -> Unit) { val authorizeHttpRequestsCustomizer = AuthorizeHttpRequestsDsl().apply(authorizeHttpRequestsConfiguration).get() this.http.authorizeHttpRequests(authorizeHttpRequestsCustomizer) } /** * Enables HTTP basic authentication. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * httpBasic { * realmName = "Custom Realm" * } * } * } * } * ``` * * @param httpBasicConfiguration custom configurations to be applied to the * HTTP basic authentication * @see [HttpBasicDsl] */ fun httpBasic(httpBasicConfiguration: HttpBasicDsl.() -> Unit) { val httpBasicCustomizer = HttpBasicDsl().apply(httpBasicConfiguration).get() this.http.httpBasic(httpBasicCustomizer) } /** * Enables password management. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * passwordManagement { * changePasswordPage = "/custom-change-password-page" * } * } * } * } * ``` * * @param passwordManagementConfiguration custom configurations to be applied to the * password management * @see [PasswordManagementDsl] * @since 5.6 */ fun passwordManagement(passwordManagementConfiguration: PasswordManagementDsl.() -> Unit) { val passwordManagementCustomizer = PasswordManagementDsl().apply(passwordManagementConfiguration).get() this.http.passwordManagement(passwordManagementCustomizer) } /** * Allows configuring response headers. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * headers { * referrerPolicy { * policy = ReferrerPolicy.SAME_ORIGIN * } * } * } * } * } * ``` * * @param headersConfiguration custom configurations to configure the * response headers * @see [HeadersDsl] */ fun headers(headersConfiguration: HeadersDsl.() -> Unit) { val headersCustomizer = HeadersDsl().apply(headersConfiguration).get() this.http.headers(headersCustomizer) } /** * Enables CORS. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * cors { * disable() * } * } * } * } * ``` * * @param corsConfiguration custom configurations to configure the * response headers * @see [CorsDsl] */ fun cors(corsConfiguration: CorsDsl.() -> Unit) { val corsCustomizer = CorsDsl().apply(corsConfiguration).get() this.http.cors(corsCustomizer) } /** * Allows configuring session management. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * sessionManagement { * invalidSessionUrl = "/invalid-session" * sessionConcurrency { * maximumSessions = 1 * } * } * } * } * } * ``` * * @param sessionManagementConfiguration custom configurations to configure * session management * @see [SessionManagementDsl] */ fun sessionManagement(sessionManagementConfiguration: SessionManagementDsl.() -> Unit) { val sessionManagementCustomizer = SessionManagementDsl().apply(sessionManagementConfiguration).get() this.http.sessionManagement(sessionManagementCustomizer) } /** * Allows configuring a port mapper. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * portMapper { * map(80, 443) * } * } * } * } * ``` * * @param portMapperConfiguration custom configurations to configure * the port mapper * @see [PortMapperDsl] */ fun portMapper(portMapperConfiguration: PortMapperDsl.() -> Unit) { val portMapperCustomizer = PortMapperDsl().apply(portMapperConfiguration).get() this.http.portMapper(portMapperCustomizer) } /** * Allows configuring channel security based upon the [HttpServletRequest] * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * requiresChannel { * secure("/public", requiresInsecure) * secure(anyRequest, requiresSecure) * } * } * } * } * ``` * * @param requiresChannelConfiguration custom configuration that specifies * channel security * @see [RequiresChannelDsl] */ fun requiresChannel(requiresChannelConfiguration: RequiresChannelDsl.() -> Unit) { val requiresChannelCustomizer = RequiresChannelDsl().apply(requiresChannelConfiguration).get() this.http.requiresChannel(requiresChannelCustomizer) } /** * Adds X509 based pre authentication to an application * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * x509 { } * } * } * } * ``` * * @param x509Configuration custom configuration to apply to the * X509 based pre authentication * @see [X509Dsl] */ fun x509(x509Configuration: X509Dsl.() -> Unit) { val x509Customizer = X509Dsl().apply(x509Configuration).get() this.http.x509(x509Customizer) } /** * Enables request caching. Specifically this ensures that requests that * are saved (i.e. after authentication is required) are later replayed. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * requestCache { } * } * } * } * ``` * * @param requestCacheConfiguration custom configuration to apply to the * request cache * @see [RequestCacheDsl] */ fun requestCache(requestCacheConfiguration: RequestCacheDsl.() -> Unit) { val requestCacheCustomizer = RequestCacheDsl().apply(requestCacheConfiguration).get() this.http.requestCache(requestCacheCustomizer) } /** * Allows configuring exception handling. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * exceptionHandling { * accessDeniedPage = "/access-denied" * } * } * } * } * ``` * * @param exceptionHandlingConfiguration custom configuration to apply to the * exception handling * @see [ExceptionHandlingDsl] */ fun exceptionHandling(exceptionHandlingConfiguration: ExceptionHandlingDsl.() -> Unit) { val exceptionHandlingCustomizer = ExceptionHandlingDsl().apply(exceptionHandlingConfiguration).get() this.http.exceptionHandling(exceptionHandlingCustomizer) } /** * Enables CSRF protection. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * csrf { } * } * } * } * ``` * * @param csrfConfiguration custom configuration to apply to CSRF * @see [CsrfDsl] */ fun csrf(csrfConfiguration: CsrfDsl.() -> Unit) { val csrfCustomizer = CsrfDsl().apply(csrfConfiguration).get() this.http.csrf(csrfCustomizer) } /** * Provides logout support. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * logout { * logoutUrl = "/log-out" * } * } * } * } * ``` * * @param logoutConfiguration custom configuration to apply to logout * @see [LogoutDsl] */ fun logout(logoutConfiguration: LogoutDsl.() -> Unit) { val logoutCustomizer = LogoutDsl().apply(logoutConfiguration).get() this.http.logout(logoutCustomizer) } /** * Configures authentication support using a SAML 2.0 Service Provider. * A [RelyingPartyRegistrationRepository] is required and must be registered with * the [ApplicationContext] or configured via * [Saml2Dsl.relyingPartyRegistrationRepository] * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * saml2Login { * relyingPartyRegistration = getSaml2RelyingPartyRegistration() * } * } * } * } * ``` * * @param saml2LoginConfiguration custom configuration to configure the * SAML2 service provider * @see [Saml2Dsl] */ fun saml2Login(saml2LoginConfiguration: Saml2Dsl.() -> Unit) { val saml2LoginCustomizer = Saml2Dsl().apply(saml2LoginConfiguration).get() this.http.saml2Login(saml2LoginCustomizer) } /** * Allows configuring how an anonymous user is represented. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * anonymous { * authorities = listOf(SimpleGrantedAuthority("ROLE_ANON")) * } * } * } * } * ``` * * @param anonymousConfiguration custom configuration to configure the * anonymous user * @see [AnonymousDsl] */ fun anonymous(anonymousConfiguration: AnonymousDsl.() -> Unit) { val anonymousCustomizer = AnonymousDsl().apply(anonymousConfiguration).get() this.http.anonymous(anonymousCustomizer) } /** * Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider. * A [ClientRegistrationRepository] is required and must be registered as a Bean or * configured via [OAuth2LoginDsl.clientRegistrationRepository] * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * oauth2Login { * clientRegistrationRepository = getClientRegistrationRepository() * } * } * } * } * ``` * * @param oauth2LoginConfiguration custom configuration to configure the * OAuth 2.0 Login * @see [OAuth2LoginDsl] */ fun oauth2Login(oauth2LoginConfiguration: OAuth2LoginDsl.() -> Unit) { val oauth2LoginCustomizer = OAuth2LoginDsl().apply(oauth2LoginConfiguration).get() this.http.oauth2Login(oauth2LoginCustomizer) } /** * Configures OAuth 2.0 client support. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * oauth2Client { } * } * } * } * ``` * * @param oauth2ClientConfiguration custom configuration to configure the * OAuth 2.0 client support * @see [OAuth2ClientDsl] */ fun oauth2Client(oauth2ClientConfiguration: OAuth2ClientDsl.() -> Unit) { val oauth2ClientCustomizer = OAuth2ClientDsl().apply(oauth2ClientConfiguration).get() this.http.oauth2Client(oauth2ClientCustomizer) } /** * Configures OAuth 2.0 resource server support. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * oauth2ResourceServer { * jwt { } * } * } * } * } * ``` * * @param oauth2ResourceServerConfiguration custom configuration to configure the * OAuth 2.0 resource server support * @see [OAuth2ResourceServerDsl] */ fun oauth2ResourceServer(oauth2ResourceServerConfiguration: OAuth2ResourceServerDsl.() -> Unit) { val oauth2ResourceServerCustomizer = OAuth2ResourceServerDsl().apply(oauth2ResourceServerConfiguration).get() this.http.oauth2ResourceServer(oauth2ResourceServerCustomizer) } /** * Configures Remember Me authentication. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * rememberMe { * tokenValiditySeconds = 604800 * } * } * } * } * ``` * * @param rememberMeConfiguration custom configuration to configure remember me * @see [RememberMeDsl] */ fun rememberMe(rememberMeConfiguration: RememberMeDsl.() -> Unit) { val rememberMeCustomizer = RememberMeDsl().apply(rememberMeConfiguration).get() this.http.rememberMe(rememberMeCustomizer) } /** * Adds the [Filter] at the location of the specified [Filter] class. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * addFilterAt(CustomFilter(), UsernamePasswordAuthenticationFilter::class.java) * } * } * } * ``` * * @param filter the [Filter] to register * @param atFilter the location of another [Filter] that is already registered * (i.e. known) with Spring Security. */ @Deprecated("Use 'addFilterAt<T>(filter)' instead.") fun addFilterAt(filter: Filter, atFilter: Class<out Filter>) { this.http.addFilterAt(filter, atFilter) } /** * Adds the [Filter] at the location of the specified [Filter] class. * Variant that is leveraging Kotlin reified type parameters. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * addFilterAt<UsernamePasswordAuthenticationFilter>(CustomFilter()) * } * } * } * ``` * * @param filter the [Filter] to register * @param T the location of another [Filter] that is already registered * (i.e. known) with Spring Security. */ @Suppress("DEPRECATION") inline fun <reified T: Filter> addFilterAt(filter: Filter) { this.addFilterAt(filter, T::class.java) } /** * Adds the [Filter] after the location of the specified [Filter] class. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * addFilterAfter(CustomFilter(), UsernamePasswordAuthenticationFilter::class.java) * } * } * } * ``` * * @param filter the [Filter] to register * @param afterFilter the location of another [Filter] that is already registered * (i.e. known) with Spring Security. */ @Deprecated("Use 'addFilterAfter<T>(filter)' instead.") fun addFilterAfter(filter: Filter, afterFilter: Class<out Filter>) { this.http.addFilterAfter(filter, afterFilter) } /** * Adds the [Filter] after the location of the specified [Filter] class. * Variant that is leveraging Kotlin reified type parameters. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * addFilterAfter<UsernamePasswordAuthenticationFilter>(CustomFilter()) * } * } * } * ``` * * @param filter the [Filter] to register * @param T the location of another [Filter] that is already registered * (i.e. known) with Spring Security. */ @Suppress("DEPRECATION") inline fun <reified T: Filter> addFilterAfter(filter: Filter) { this.addFilterAfter(filter, T::class.java) } /** * Adds the [Filter] before the location of the specified [Filter] class. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * addFilterBefore(CustomFilter(), UsernamePasswordAuthenticationFilter::class.java) * } * } * } * ``` * * @param filter the [Filter] to register * @param beforeFilter the location of another [Filter] that is already registered * (i.e. known) with Spring Security. */ @Deprecated("Use 'addFilterBefore<T>(filter)' instead.") fun addFilterBefore(filter: Filter, beforeFilter: Class<out Filter>) { this.http.addFilterBefore(filter, beforeFilter) } /** * Adds the [Filter] before the location of the specified [Filter] class. * Variant that is leveraging Kotlin reified type parameters. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * addFilterBefore<UsernamePasswordAuthenticationFilter>(CustomFilter()) * } * } * } * ``` * * @param filter the [Filter] to register * @param T the location of another [Filter] that is already registered * (i.e. known) with Spring Security. */ @Suppress("DEPRECATION") inline fun <reified T: Filter> addFilterBefore(filter: Filter) { this.addFilterBefore(filter, T::class.java) } /** * Apply all configurations to the provided [HttpSecurity] */ internal fun build() { init() authenticationManager?.also { this.http.authenticationManager(authenticationManager) } } /** * Enables security context configuration. * * Example: * * ``` * @EnableWebSecurity * class SecurityConfig : WebSecurityConfigurerAdapter() { * * override fun configure(http: HttpSecurity) { * http { * securityContext { * securityContextRepository = SECURITY_CONTEXT_REPOSITORY * } * } * } * } * ``` * @author Norbert Nowak * @since 5.7 * @param securityContextConfiguration configuration to be applied to Security Context * @see [SecurityContextDsl] */ fun securityContext(securityContextConfiguration: SecurityContextDsl.() -> Unit) { val securityContextCustomizer = SecurityContextDsl().apply(securityContextConfiguration).get() this.http.securityContext(securityContextCustomizer) } }
config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDsl.kt
3051093803
/* Copyright 2017-2020 Charles Korn. 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 batect.os.windows.namedpipes import batect.os.windows.WindowsNativeMethods import jnr.posix.POSIXFactory import kotlinx.io.IOException import java.io.FileNotFoundException import java.io.InputStream import java.io.OutputStream import java.net.InetAddress import java.net.InetSocketAddress import java.net.Socket import java.net.SocketAddress import java.nio.channels.SocketChannel class NamedPipeSocket : Socket() { private val nativeMethods = WindowsNativeMethods(POSIXFactory.getNativePOSIX()) private lateinit var pipe: NamedPipe private var isOpen = false private var readTimeout = 0 private val inputStream = object : InputStream() { override fun skip(n: Long): Long = throw UnsupportedOperationException() override fun available(): Int = 0 override fun close() = this@NamedPipeSocket.close() override fun reset() = throw UnsupportedOperationException() override fun mark(readlimit: Int): Unit = throw UnsupportedOperationException() override fun markSupported(): Boolean = false override fun read(): Int { val bytes = ByteArray(1) val result = read(bytes) if (result == -1) { return -1 } return bytes.first().toInt() } override fun read(b: ByteArray): Int { return read(b, 0, b.size) } override fun read(b: ByteArray, off: Int, len: Int): Int { return pipe.read(b, off, len, readTimeout) } } private val outputStream = object : OutputStream() { override fun write(b: Int) { write(byteArrayOf(b.toByte())) } override fun write(b: ByteArray) { write(b, 0, b.size) } override fun write(b: ByteArray, off: Int, len: Int) { pipe.write(b, off, len) } override fun flush() {} override fun close() = this@NamedPipeSocket.close() } override fun connect(addr: SocketAddress?) { this.connect(addr, 0) } override fun connect(addr: SocketAddress?, timeout: Int) { val encodedHostName = (addr as InetSocketAddress).hostName val path = NamedPipeDns.decodePath(encodedHostName) try { pipe = nativeMethods.openNamedPipe(path, timeout) isOpen = true } catch (e: FileNotFoundException) { throw IOException("Cannot connect to '$path': the named pipe does not exist", e) } } override fun getInputStream(): InputStream = inputStream override fun getOutputStream(): OutputStream = outputStream override fun close() { if (!isOpen) { return } pipe.close() isOpen = false } override fun getSoTimeout(): Int = readTimeout override fun setSoTimeout(timeout: Int) { readTimeout = timeout } override fun shutdownInput() {} override fun shutdownOutput() {} override fun isInputShutdown(): Boolean = !this.isConnected override fun isOutputShutdown(): Boolean = !this.isConnected override fun isBound(): Boolean = isOpen override fun isConnected(): Boolean = isOpen override fun isClosed(): Boolean = !isOpen override fun getReuseAddress(): Boolean = throw UnsupportedOperationException() override fun setReuseAddress(on: Boolean) = throw UnsupportedOperationException() override fun getKeepAlive(): Boolean = throw UnsupportedOperationException() override fun setKeepAlive(on: Boolean): Unit = throw UnsupportedOperationException() override fun getPort(): Int = throw UnsupportedOperationException() override fun getSoLinger(): Int = throw UnsupportedOperationException() override fun setSoLinger(on: Boolean, linger: Int): Unit = throw UnsupportedOperationException() override fun getTrafficClass(): Int = throw UnsupportedOperationException() override fun setTrafficClass(tc: Int): Unit = throw UnsupportedOperationException() override fun getTcpNoDelay(): Boolean = throw UnsupportedOperationException() override fun setTcpNoDelay(on: Boolean): Unit = throw UnsupportedOperationException() override fun getOOBInline(): Boolean = throw UnsupportedOperationException() override fun setOOBInline(on: Boolean): Unit = throw UnsupportedOperationException() override fun getLocalPort(): Int = throw UnsupportedOperationException() override fun getLocalSocketAddress(): SocketAddress = throw UnsupportedOperationException() override fun getRemoteSocketAddress(): SocketAddress = throw UnsupportedOperationException() override fun getReceiveBufferSize(): Int = throw UnsupportedOperationException() override fun getSendBufferSize(): Int = throw UnsupportedOperationException() override fun sendUrgentData(data: Int): Unit = throw UnsupportedOperationException() override fun setSendBufferSize(size: Int): Unit = throw UnsupportedOperationException() override fun setReceiveBufferSize(size: Int): Unit = throw UnsupportedOperationException() override fun getLocalAddress(): InetAddress = throw UnsupportedOperationException() override fun getChannel(): SocketChannel = throw UnsupportedOperationException() override fun setPerformancePreferences(connectionTime: Int, latency: Int, bandwidth: Int): Unit = throw UnsupportedOperationException() override fun getInetAddress(): InetAddress = throw UnsupportedOperationException() override fun bind(bindpoint: SocketAddress?): Unit = throw UnsupportedOperationException() }
app/src/main/kotlin/batect/os/windows/namedpipes/NamedPipeSocket.kt
1219299517
package com.habitrpg.android.habitica.ui.adapter import android.content.Context import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.SkillListItemBinding import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.extensions.isUsingNightModeResources import com.habitrpg.android.habitica.models.Skill import com.habitrpg.android.habitica.models.user.OwnedItem import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import io.reactivex.rxjava3.core.BackpressureStrategy import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.subjects.PublishSubject import io.realm.RealmList class SkillsRecyclerViewAdapter : RecyclerView.Adapter<SkillsRecyclerViewAdapter.SkillViewHolder>() { private val useSkillSubject = PublishSubject.create<Skill>() val useSkillEvents: Flowable<Skill> = useSkillSubject.toFlowable(BackpressureStrategy.DROP) var mana: Double = 0.0 set(value) { field = value notifyDataSetChanged() } var level: Int = 0 set(value) { field = value notifyDataSetChanged() } var specialItems: RealmList<OwnedItem>?? = null set(value) { field = value notifyDataSetChanged() } private var skillList: List<Skill> = emptyList() fun setSkillList(skillList: List<Skill>) { this.skillList = skillList this.notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SkillViewHolder { return SkillViewHolder(parent.inflate(R.layout.skill_list_item)) } override fun onBindViewHolder(holder: SkillViewHolder, position: Int) { holder.bind(skillList[position]) } override fun getItemCount(): Int { return skillList.size } inner class SkillViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { private val binding = SkillListItemBinding.bind(itemView) private val magicDrawable: Drawable private val lockDrawable: Drawable var skill: Skill? = null var context: Context = itemView.context init { binding.buttonWrapper.setOnClickListener(this) magicDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfMagic()) lockDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfLocked(ContextCompat.getColor(context, R.color.text_dimmed))) } fun bind(skill: Skill) { this.skill = skill binding.skillText.text = skill.text binding.skillNotes.text = skill.notes binding.skillText.setTextColor(ContextCompat.getColor(context, R.color.text_primary)) binding.skillNotes.setTextColor(ContextCompat.getColor(context, R.color.text_ternary)) binding.skillNotes.visibility = View.VISIBLE binding.priceLabel.visibility = View.VISIBLE if ("special" == skill.habitClass) { binding.countLabel.visibility = View.VISIBLE binding.countLabel.text = getOwnedCount(skill.key).toString() binding.priceLabel.setText(R.string.skill_transformation_use) if (context.isUsingNightModeResources()) { binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.brand_500)) } else { binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.color_accent)) } binding.buttonIconView.setImageDrawable(null) binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.offset_background)) binding.buttonIconView.alpha = 1.0f binding.priceLabel.alpha = 1.0f } else { binding.countLabel.visibility = View.GONE binding.priceLabel.text = skill.mana?.toString() if (context.isUsingNightModeResources()) { binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.blue_500)) } else { binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.blue_10)) } binding.buttonIconView.setImageDrawable(magicDrawable) if (skill.mana ?: 0 > mana) { binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.offset_background)) binding.buttonIconView.alpha = 0.3f binding.priceLabel.alpha = 0.3f } else { binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.blue_500_24)) binding.buttonIconView.alpha = 1.0f binding.priceLabel.alpha = 1.0f } if ((skill.lvl ?: 0) > level) { binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.offset_background)) binding.skillText.setTextColor(ContextCompat.getColor(context, R.color.text_dimmed)) binding.skillText.text = context.getString(R.string.skill_unlocks_at, skill.lvl) binding.skillNotes.visibility = View.GONE binding.buttonIconView.setImageDrawable(lockDrawable) binding.priceLabel.visibility = View.GONE } } DataBindingUtils.loadImage(binding.skillImage, "shop_" + skill.key) } override fun onClick(v: View) { if ((skill?.lvl ?: 0) <= level) { skill?.let { useSkillSubject.onNext(it) } } } private fun getOwnedCount(key: String): Int { return specialItems?.firstOrNull() { it.key == key }?.numberOwned ?: 0 } } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/SkillsRecyclerViewAdapter.kt
1357112307
package org.jtalks.pochta.http.controllers import org.json.simple.JSONArray import org.json.simple.JSONObject import org.jtalks.pochta.store.Email import org.jtalks.pochta.store.Base64DecodedEmail /** * Extension functions to ease rest data output */ fun <T> Iterable<T>.asJsonArray(): JSONArray { return this.fold(JSONArray()){(array, address) -> array.add(address); array } } fun Email.asJson(): JSONObject { val result = JSONObject() result.put("server_id", id) result.put("envelope_from", envelopeFrom) result.put("envelope_recipients", envelopeRecipients.asJsonArray()) result.put("delivery_date", "$receivedDate") result.put("sender_ip", ip) result.put("mail_body", Base64DecodedEmail(this).getMessage()) result.put("mail_body_raw", getMessage()) return result }
src/main/kotlin/org/jtalks/pochta/http/controllers/RestExtensions.kt
261530964
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.health.connect.client.aggregate.AggregateMetric import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType import androidx.health.connect.client.aggregate.AggregateMetric.Companion.doubleMetric import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Energy import androidx.health.connect.client.units.Mass import java.time.Instant import java.time.ZoneOffset /** Captures what nutrients were consumed as part of a meal or a food item. */ public class NutritionRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** Biotin in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val biotin: Mass? = null, /** Caffeine in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val caffeine: Mass? = null, /** Calcium in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val calcium: Mass? = null, /** Energy in [Energy] unit. Optional field. Valid range: 0-100000 kcal. */ public val energy: Energy? = null, /** Energy from fat in [Energy] unit. Optional field. Valid range: 0-100000 kcal. */ public val energyFromFat: Energy? = null, /** Chloride in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val chloride: Mass? = null, /** Cholesterol in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val cholesterol: Mass? = null, /** Chromium in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val chromium: Mass? = null, /** Copper in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val copper: Mass? = null, /** Dietary fiber in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val dietaryFiber: Mass? = null, /** Folate in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val folate: Mass? = null, /** Folic acid in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val folicAcid: Mass? = null, /** Iodine in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val iodine: Mass? = null, /** Iron in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val iron: Mass? = null, /** Magnesium in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val magnesium: Mass? = null, /** Manganese in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val manganese: Mass? = null, /** Molybdenum in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val molybdenum: Mass? = null, /** Monounsaturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val monounsaturatedFat: Mass? = null, /** Niacin in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val niacin: Mass? = null, /** Pantothenic acid in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val pantothenicAcid: Mass? = null, /** Phosphorus in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val phosphorus: Mass? = null, /** Polyunsaturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val polyunsaturatedFat: Mass? = null, /** Potassium in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val potassium: Mass? = null, /** Protein in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val protein: Mass? = null, /** Riboflavin in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val riboflavin: Mass? = null, /** Saturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val saturatedFat: Mass? = null, /** Selenium in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val selenium: Mass? = null, /** Sodium in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val sodium: Mass? = null, /** Sugar in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val sugar: Mass? = null, /** Thiamin in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val thiamin: Mass? = null, /** Total carbohydrate in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val totalCarbohydrate: Mass? = null, /** Total fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val totalFat: Mass? = null, /** Trans fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val transFat: Mass? = null, /** Unsaturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */ public val unsaturatedFat: Mass? = null, /** Vitamin A in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminA: Mass? = null, /** Vitamin B12 in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminB12: Mass? = null, /** Vitamin B6 in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminB6: Mass? = null, /** Vitamin C in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminC: Mass? = null, /** Vitamin D in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminD: Mass? = null, /** Vitamin E in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminE: Mass? = null, /** Vitamin K in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val vitaminK: Mass? = null, /** Zinc in [Mass] unit. Optional field. Valid range: 0-100 grams. */ public val zinc: Mass? = null, /** Name for food or drink, provided by the user. Optional field. */ public val name: String? = null, /** * Type of meal related to the nutrients consumed. Optional, enum field. Allowed values: * [MealType]. * * @see MealType */ @property:MealTypes public val mealType: Int = MealType.MEAL_TYPE_UNKNOWN, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NutritionRecord) return false if (biotin != other.biotin) return false if (caffeine != other.caffeine) return false if (calcium != other.calcium) return false if (energy != other.energy) return false if (energyFromFat != other.energyFromFat) return false if (chloride != other.chloride) return false if (cholesterol != other.cholesterol) return false if (chromium != other.chromium) return false if (copper != other.copper) return false if (dietaryFiber != other.dietaryFiber) return false if (folate != other.folate) return false if (folicAcid != other.folicAcid) return false if (iodine != other.iodine) return false if (iron != other.iron) return false if (magnesium != other.magnesium) return false if (manganese != other.manganese) return false if (molybdenum != other.molybdenum) return false if (monounsaturatedFat != other.monounsaturatedFat) return false if (niacin != other.niacin) return false if (pantothenicAcid != other.pantothenicAcid) return false if (phosphorus != other.phosphorus) return false if (polyunsaturatedFat != other.polyunsaturatedFat) return false if (potassium != other.potassium) return false if (protein != other.protein) return false if (riboflavin != other.riboflavin) return false if (saturatedFat != other.saturatedFat) return false if (selenium != other.selenium) return false if (sodium != other.sodium) return false if (sugar != other.sugar) return false if (thiamin != other.thiamin) return false if (totalCarbohydrate != other.totalCarbohydrate) return false if (totalFat != other.totalFat) return false if (transFat != other.transFat) return false if (unsaturatedFat != other.unsaturatedFat) return false if (vitaminA != other.vitaminA) return false if (vitaminB12 != other.vitaminB12) return false if (vitaminB6 != other.vitaminB6) return false if (vitaminC != other.vitaminC) return false if (vitaminD != other.vitaminD) return false if (vitaminE != other.vitaminE) return false if (vitaminK != other.vitaminK) return false if (zinc != other.zinc) return false if (name != other.name) return false if (mealType != other.mealType) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = biotin.hashCode() result = 31 * result + caffeine.hashCode() result = 31 * result + calcium.hashCode() result = 31 * result + energy.hashCode() result = 31 * result + energyFromFat.hashCode() result = 31 * result + chloride.hashCode() result = 31 * result + cholesterol.hashCode() result = 31 * result + chromium.hashCode() result = 31 * result + copper.hashCode() result = 31 * result + dietaryFiber.hashCode() result = 31 * result + folate.hashCode() result = 31 * result + folicAcid.hashCode() result = 31 * result + iodine.hashCode() result = 31 * result + iron.hashCode() result = 31 * result + magnesium.hashCode() result = 31 * result + manganese.hashCode() result = 31 * result + molybdenum.hashCode() result = 31 * result + monounsaturatedFat.hashCode() result = 31 * result + niacin.hashCode() result = 31 * result + pantothenicAcid.hashCode() result = 31 * result + phosphorus.hashCode() result = 31 * result + polyunsaturatedFat.hashCode() result = 31 * result + potassium.hashCode() result = 31 * result + protein.hashCode() result = 31 * result + riboflavin.hashCode() result = 31 * result + saturatedFat.hashCode() result = 31 * result + selenium.hashCode() result = 31 * result + sodium.hashCode() result = 31 * result + sugar.hashCode() result = 31 * result + thiamin.hashCode() result = 31 * result + totalCarbohydrate.hashCode() result = 31 * result + totalFat.hashCode() result = 31 * result + transFat.hashCode() result = 31 * result + unsaturatedFat.hashCode() result = 31 * result + vitaminA.hashCode() result = 31 * result + vitaminB12.hashCode() result = 31 * result + vitaminB6.hashCode() result = 31 * result + vitaminC.hashCode() result = 31 * result + vitaminD.hashCode() result = 31 * result + vitaminE.hashCode() result = 31 * result + vitaminK.hashCode() result = 31 * result + zinc.hashCode() result = 31 * result + (name?.hashCode() ?: 0) result = 31 * result + mealType result = 31 * result + startTime.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } companion object { private const val TYPE_NAME = "Nutrition" /** * Metric identifier to retrieve the total biotin from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val BIOTIN_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "biotin", Mass::grams) /** * Metric identifier to retrieve the total caffeine from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val CAFFEINE_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "caffeine", Mass::grams) /** * Metric identifier to retrieve the total calcium from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val CALCIUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "calcium", Mass::grams) /** * Metric identifier to retrieve the total energy from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val ENERGY_TOTAL: AggregateMetric<Energy> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "calories", Energy::kilocalories) /** * Metric identifier to retrieve the total energy from fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val ENERGY_FROM_FAT_TOTAL: AggregateMetric<Energy> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "caloriesFromFat", Energy::kilocalories) /** * Metric identifier to retrieve the total chloride from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val CHLORIDE_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "chloride", Mass::grams) /** * Metric identifier to retrieve the total cholesterol from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val CHOLESTEROL_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "cholesterol", Mass::grams) /** * Metric identifier to retrieve the total chromium from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val CHROMIUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "chromium", Mass::grams) /** * Metric identifier to retrieve the total copper from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val COPPER_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "copper", Mass::grams) /** * Metric identifier to retrieve the total dietary fiber from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val DIETARY_FIBER_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "dietaryFiber", Mass::grams) /** * Metric identifier to retrieve the total folate from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val FOLATE_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "folate", Mass::grams) /** * Metric identifier to retrieve the total folic acid from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val FOLIC_ACID_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "folicAcid", Mass::grams) /** * Metric identifier to retrieve the total iodine from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val IODINE_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "iodine", Mass::grams) /** * Metric identifier to retrieve the total iron from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val IRON_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "iron", Mass::grams) /** * Metric identifier to retrieve the total magnesium from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val MAGNESIUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "magnesium", Mass::grams) /** * Metric identifier to retrieve the total manganese from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val MANGANESE_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "manganese", Mass::grams) /** * Metric identifier to retrieve the total molybdenum from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val MOLYBDENUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "molybdenum", Mass::grams) /** * Metric identifier to retrieve the total monounsaturated fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val MONOUNSATURATED_FAT_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "monounsaturatedFat", Mass::grams) /** * Metric identifier to retrieve the total niacin from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val NIACIN_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "niacin", Mass::grams) /** * Metric identifier to retrieve the total pantothenic acid from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val PANTOTHENIC_ACID_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "pantothenicAcid", Mass::grams) /** * Metric identifier to retrieve the total phosphorus from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val PHOSPHORUS_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "phosphorus", Mass::grams) /** * Metric identifier to retrieve the total polyunsaturated fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val POLYUNSATURATED_FAT_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "polyunsaturatedFat", Mass::grams) /** * Metric identifier to retrieve the total potassium from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val POTASSIUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "potassium", Mass::grams) /** * Metric identifier to retrieve the total protein from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val PROTEIN_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "protein", Mass::grams) /** * Metric identifier to retrieve the total riboflavin from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val RIBOFLAVIN_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "riboflavin", Mass::grams) /** * Metric identifier to retrieve the total saturated fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val SATURATED_FAT_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "saturatedFat", Mass::grams) /** * Metric identifier to retrieve the total selenium from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val SELENIUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "selenium", Mass::grams) /** * Metric identifier to retrieve the total sodium from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val SODIUM_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "sodium", Mass::grams) /** * Metric identifier to retrieve the total sugar from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val SUGAR_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "sugar", Mass::grams) /** * Metric identifier to retrieve the total thiamin from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val THIAMIN_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "thiamin", Mass::grams) /** * Metric identifier to retrieve the total total carbohydrate from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val TOTAL_CARBOHYDRATE_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "totalCarbohydrate", Mass::grams) /** * Metric identifier to retrieve the total total fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val TOTAL_FAT_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "totalFat", Mass::grams) /** * Metric identifier to retrieve the total trans fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val TRANS_FAT_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "transFat", Mass::grams) /** * Metric identifier to retrieve the total unsaturated fat from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val UNSATURATED_FAT_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "unsaturatedFat", Mass::grams) /** * Metric identifier to retrieve the total vitamin a from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_A_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminA", Mass::grams) /** * Metric identifier to retrieve the total vitamin b12 from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_B12_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminB12", Mass::grams) /** * Metric identifier to retrieve the total vitamin b6 from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_B6_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminB6", Mass::grams) /** * Metric identifier to retrieve the total vitamin c from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_C_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminC", Mass::grams) /** * Metric identifier to retrieve the total vitamin d from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_D_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminD", Mass::grams) /** * Metric identifier to retrieve the total vitamin e from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_E_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminE", Mass::grams) /** * Metric identifier to retrieve the total vitamin k from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val VITAMIN_K_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminK", Mass::grams) /** * Metric identifier to retrieve the total zinc from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val ZINC_TOTAL: AggregateMetric<Mass> = doubleMetric(TYPE_NAME, AggregationType.TOTAL, "zinc", Mass::grams) } }
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/NutritionRecord.kt
496920893
/* * 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.compose.material3 import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.tween import androidx.compose.animation.expandHorizontally import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkHorizontally import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.HoverInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.width import androidx.compose.material3.tokens.ExtendedFabPrimaryTokens import androidx.compose.material3.tokens.FabPrimaryLargeTokens import androidx.compose.material3.tokens.FabPrimarySmallTokens import androidx.compose.material3.tokens.FabPrimaryTokens import androidx.compose.material3.tokens.MotionTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * <a href="https://m3.material.io/components/floating-action-button/overview" class="external" target="_blank">Material Design floating action button</a>. * * The FAB represents the most important action on a screen. It puts key actions within reach. * * ![FAB image](https://developer.android.com/images/reference/androidx/compose/material3/fab.png) * * FAB typically contains an icon, for a FAB with text and an icon, see * [ExtendedFloatingActionButton]. * * @sample androidx.compose.material3.samples.FloatingActionButtonSample * * @param onClick called when this FAB is clicked * @param modifier the [Modifier] to be applied to this FAB * @param shape defines the shape of this FAB's container and shadow (when using [elevation]) * @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to * have no color. * @param contentColor the preferred color for content inside this FAB. Defaults to either the * matching content color for [containerColor], or to the current [LocalContentColor] if * [containerColor] is not a color from the theme. * @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in * different states. This controls the size of the shadow below the FAB. Additionally, when the * container color is [ColorScheme.surface], this controls the amount of primary color applied as an * overlay. See also: [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this FAB in different states. * @param content the content of this FAB, typically an [Icon] */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun FloatingActionButton( onClick: () -> Unit, modifier: Modifier = Modifier, shape: Shape = FloatingActionButtonDefaults.shape, containerColor: Color = FloatingActionButtonDefaults.containerColor, contentColor: Color = contentColorFor(containerColor), elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { Surface( onClick = onClick, modifier = modifier, shape = shape, color = containerColor, contentColor = contentColor, tonalElevation = elevation.tonalElevation(interactionSource = interactionSource).value, shadowElevation = elevation.shadowElevation(interactionSource = interactionSource).value, interactionSource = interactionSource, ) { CompositionLocalProvider(LocalContentColor provides contentColor) { // Adding the text style from [ExtendedFloatingActionButton] to all FAB variations. In // the majority of cases this will have no impact, because icons are expected, but if a // developer decides to put some short text to emulate an icon, (like "?") then it will // have the correct styling. ProvideTextStyle( MaterialTheme.typography.fromToken(ExtendedFabPrimaryTokens.LabelTextFont), ) { Box( modifier = Modifier .defaultMinSize( minWidth = FabPrimaryTokens.ContainerWidth, minHeight = FabPrimaryTokens.ContainerHeight, ), contentAlignment = Alignment.Center, ) { content() } } } } } /** * <a href="https://m3.material.io/components/floating-action-button/overview" class="external" target="_blank">Material Design small floating action button</a>. * * The FAB represents the most important action on a screen. It puts key actions within reach. * * ![Small FAB image](https://developer.android.com/images/reference/androidx/compose/material3/small-fab.png) * * @sample androidx.compose.material3.samples.SmallFloatingActionButtonSample * * @param onClick called when this FAB is clicked * @param modifier the [Modifier] to be applied to this FAB * @param shape defines the shape of this FAB's container and shadow (when using [elevation]) * @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to * have no color. * @param contentColor the preferred color for content inside this FAB. Defaults to either the * matching content color for [containerColor], or to the current [LocalContentColor] if * [containerColor] is not a color from the theme. * @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in * different states. This controls the size of the shadow below the FAB. Additionally, when the * container color is [ColorScheme.surface], this controls the amount of primary color applied as an * overlay. See also: [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this FAB in different states. * @param content the content of this FAB, typically an [Icon] */ @Composable fun SmallFloatingActionButton( onClick: () -> Unit, modifier: Modifier = Modifier, shape: Shape = FloatingActionButtonDefaults.smallShape, containerColor: Color = FloatingActionButtonDefaults.containerColor, contentColor: Color = contentColorFor(containerColor), elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { FloatingActionButton( onClick = onClick, modifier = modifier.sizeIn( minWidth = FabPrimarySmallTokens.ContainerWidth, minHeight = FabPrimarySmallTokens.ContainerHeight, ), shape = shape, containerColor = containerColor, contentColor = contentColor, elevation = elevation, interactionSource = interactionSource, content = content, ) } /** * <a href="https://m3.material.io/components/floating-action-button/overview" class="external" target="_blank">Material Design large floating action button</a>. * * The FAB represents the most important action on a screen. It puts key actions within reach. * * ![Large FAB image](https://developer.android.com/images/reference/androidx/compose/material3/large-fab.png) * * @sample androidx.compose.material3.samples.LargeFloatingActionButtonSample * * @param onClick called when this FAB is clicked * @param modifier the [Modifier] to be applied to this FAB * @param shape defines the shape of this FAB's container and shadow (when using [elevation]) * @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to * have no color. * @param contentColor the preferred color for content inside this FAB. Defaults to either the * matching content color for [containerColor], or to the current [LocalContentColor] if * [containerColor] is not a color from the theme. * @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in * different states. This controls the size of the shadow below the FAB. Additionally, when the * container color is [ColorScheme.surface], this controls the amount of primary color applied as an * overlay. See also: [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this FAB in different states. * @param content the content of this FAB, typically an [Icon] */ @Composable fun LargeFloatingActionButton( onClick: () -> Unit, modifier: Modifier = Modifier, shape: Shape = FloatingActionButtonDefaults.largeShape, containerColor: Color = FloatingActionButtonDefaults.containerColor, contentColor: Color = contentColorFor(containerColor), elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { FloatingActionButton( onClick = onClick, modifier = modifier.sizeIn( minWidth = FabPrimaryLargeTokens.ContainerWidth, minHeight = FabPrimaryLargeTokens.ContainerHeight, ), shape = shape, containerColor = containerColor, contentColor = contentColor, elevation = elevation, interactionSource = interactionSource, content = content, ) } /** * <a href="https://m3.material.io/components/extended-fab/overview" class="external" target="_blank">Material Design extended floating action button</a>. * * Extended FABs help people take primary actions. They're wider than FABs to accommodate a text * label and larger target area. * * ![Extended FAB image](https://developer.android.com/images/reference/androidx/compose/material3/extended-fab.png) * * The other extended floating action button overload supports a text label and icon. * * @sample androidx.compose.material3.samples.ExtendedFloatingActionButtonTextSample * * @param onClick called when this FAB is clicked * @param modifier the [Modifier] to be applied to this FAB * @param shape defines the shape of this FAB's container and shadow (when using [elevation]) * @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to * have no color. * @param contentColor the preferred color for content inside this FAB. Defaults to either the * matching content color for [containerColor], or to the current [LocalContentColor] if * [containerColor] is not a color from the theme. * @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in * different states. This controls the size of the shadow below the FAB. Additionally, when the * container color is [ColorScheme.surface], this controls the amount of primary color applied as an * overlay. See also: [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this FAB in different states. * @param content the content of this FAB, typically a [Text] label */ @Composable fun ExtendedFloatingActionButton( onClick: () -> Unit, modifier: Modifier = Modifier, shape: Shape = FloatingActionButtonDefaults.extendedFabShape, containerColor: Color = FloatingActionButtonDefaults.containerColor, contentColor: Color = contentColorFor(containerColor), elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit, ) { FloatingActionButton( onClick = onClick, modifier = modifier, shape = shape, containerColor = containerColor, contentColor = contentColor, elevation = elevation, interactionSource = interactionSource, ) { Row( modifier = Modifier .sizeIn(minWidth = ExtendedFabMinimumWidth) .padding(horizontal = ExtendedFabTextPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content, ) } } /** * <a href="https://m3.material.io/components/extended-fab/overview" class="external" target="_blank">Material Design extended floating action button</a>. * * Extended FABs help people take primary actions. They're wider than FABs to accommodate a text * label and larger target area. * * ![Extended FAB image](https://developer.android.com/images/reference/androidx/compose/material3/extended-fab.png) * * The other extended floating action button overload is for FABs without an icon. * * Default content description for accessibility is extended from the extended fabs icon. For custom * behavior, you can provide your own via [Modifier.semantics]. * * @sample androidx.compose.material3.samples.ExtendedFloatingActionButtonSample * @sample androidx.compose.material3.samples.AnimatedExtendedFloatingActionButtonSample * * @param text label displayed inside this FAB * @param icon optional icon for this FAB, typically an [Icon] * @param onClick called when this FAB is clicked * @param modifier the [Modifier] to be applied to this FAB * @param expanded controls the expansion state of this FAB. In an expanded state, the FAB will show * both the [icon] and [text]. In a collapsed state, the FAB will show only the [icon]. * @param shape defines the shape of this FAB's container and shadow (when using [elevation]) * @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to * have no color. * @param contentColor the preferred color for content inside this FAB. Defaults to either the * matching content color for [containerColor], or to the current [LocalContentColor] if * [containerColor] is not a color from the theme. * @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in * different states. This controls the size of the shadow below the FAB. Additionally, when the * container color is [ColorScheme.surface], this controls the amount of primary color applied as an * overlay. See also: [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this FAB in different states. */ @Composable fun ExtendedFloatingActionButton( text: @Composable () -> Unit, icon: @Composable () -> Unit, onClick: () -> Unit, modifier: Modifier = Modifier, expanded: Boolean = true, shape: Shape = FloatingActionButtonDefaults.extendedFabShape, containerColor: Color = FloatingActionButtonDefaults.containerColor, contentColor: Color = contentColorFor(containerColor), elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { FloatingActionButton( onClick = onClick, modifier = modifier, shape = shape, containerColor = containerColor, contentColor = contentColor, elevation = elevation, interactionSource = interactionSource, ) { val startPadding = if (expanded) ExtendedFabStartIconPadding else 0.dp val endPadding = if (expanded) ExtendedFabTextPadding else 0.dp Row( modifier = Modifier .sizeIn( minWidth = if (expanded) ExtendedFabMinimumWidth else FabPrimaryTokens.ContainerWidth ) .padding(start = startPadding, end = endPadding), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = if (expanded) Arrangement.Start else Arrangement.Center ) { icon() AnimatedVisibility( visible = expanded, enter = ExtendedFabExpandAnimation, exit = ExtendedFabCollapseAnimation, ) { Row(Modifier.clearAndSetSemantics {}) { Spacer(Modifier.width(ExtendedFabEndIconPadding)) text() } } } } } /** * Contains the default values used by [FloatingActionButton] */ object FloatingActionButtonDefaults { /** * The recommended size of the icon inside a [LargeFloatingActionButton]. */ val LargeIconSize = FabPrimaryLargeTokens.IconSize /** Default shape for a floating action button. */ val shape: Shape @Composable get() = FabPrimaryTokens.ContainerShape.toShape() /** Default shape for a small floating action button. */ val smallShape: Shape @Composable get() = FabPrimarySmallTokens.ContainerShape.toShape() /** Default shape for a large floating action button. */ val largeShape: Shape @Composable get() = FabPrimaryLargeTokens.ContainerShape.toShape() /** Default shape for an extended floating action button. */ val extendedFabShape: Shape @Composable get() = ExtendedFabPrimaryTokens.ContainerShape.toShape() /** Default container color for a floating action button. */ val containerColor: Color @Composable get() = FabPrimaryTokens.ContainerColor.toColor() /** * Creates a [FloatingActionButtonElevation] that represents the elevation of a * [FloatingActionButton] in different states. For use cases in which a less prominent * [FloatingActionButton] is possible consider the [loweredElevation]. * * @param defaultElevation the elevation used when the [FloatingActionButton] has no other * [Interaction]s. * @param pressedElevation the elevation used when the [FloatingActionButton] is pressed. * @param focusedElevation the elevation used when the [FloatingActionButton] is focused. * @param hoveredElevation the elevation used when the [FloatingActionButton] is hovered. */ @Composable fun elevation( defaultElevation: Dp = FabPrimaryTokens.ContainerElevation, pressedElevation: Dp = FabPrimaryTokens.PressedContainerElevation, focusedElevation: Dp = FabPrimaryTokens.FocusContainerElevation, hoveredElevation: Dp = FabPrimaryTokens.HoverContainerElevation, ): FloatingActionButtonElevation = FloatingActionButtonElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, ) /** * Use this to create a [FloatingActionButton] with a lowered elevation for less emphasis. Use * [elevation] to get a normal [FloatingActionButton]. * * @param defaultElevation the elevation used when the [FloatingActionButton] has no other * [Interaction]s. * @param pressedElevation the elevation used when the [FloatingActionButton] is pressed. * @param focusedElevation the elevation used when the [FloatingActionButton] is focused. * @param hoveredElevation the elevation used when the [FloatingActionButton] is hovered. */ @Composable fun loweredElevation( defaultElevation: Dp = FabPrimaryTokens.LoweredContainerElevation, pressedElevation: Dp = FabPrimaryTokens.LoweredPressedContainerElevation, focusedElevation: Dp = FabPrimaryTokens.LoweredFocusContainerElevation, hoveredElevation: Dp = FabPrimaryTokens.LoweredHoverContainerElevation, ): FloatingActionButtonElevation = FloatingActionButtonElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, ) /** * Use this to create a [FloatingActionButton] that represents the default elevation of a * [FloatingActionButton] used for [BottomAppBar] in different states. * * @param defaultElevation the elevation used when the [FloatingActionButton] has no other * [Interaction]s. * @param pressedElevation the elevation used when the [FloatingActionButton] is pressed. * @param focusedElevation the elevation used when the [FloatingActionButton] is focused. * @param hoveredElevation the elevation used when the [FloatingActionButton] is hovered. */ fun bottomAppBarFabElevation( defaultElevation: Dp = 0.dp, pressedElevation: Dp = 0.dp, focusedElevation: Dp = 0.dp, hoveredElevation: Dp = 0.dp ): FloatingActionButtonElevation = FloatingActionButtonElevation( defaultElevation, pressedElevation, focusedElevation, hoveredElevation ) } /** * Represents the tonal and shadow elevation for a floating action button in different states. * * See [FloatingActionButtonDefaults.elevation] for the default elevation used in a * [FloatingActionButton] and [ExtendedFloatingActionButton]. */ @Stable open class FloatingActionButtonElevation internal constructor( private val defaultElevation: Dp, private val pressedElevation: Dp, private val focusedElevation: Dp, private val hoveredElevation: Dp, ) { @Composable internal fun shadowElevation(interactionSource: InteractionSource): State<Dp> { return animateElevation(interactionSource = interactionSource) } @Composable internal fun tonalElevation(interactionSource: InteractionSource): State<Dp> { return animateElevation(interactionSource = interactionSource) } @Composable private fun animateElevation(interactionSource: InteractionSource): State<Dp> { val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is HoverInteraction.Enter -> { interactions.add(interaction) } is HoverInteraction.Exit -> { interactions.remove(interaction.enter) } is FocusInteraction.Focus -> { interactions.add(interaction) } is FocusInteraction.Unfocus -> { interactions.remove(interaction.focus) } is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } } } } val interaction = interactions.lastOrNull() val target = when (interaction) { is PressInteraction.Press -> pressedElevation is HoverInteraction.Enter -> hoveredElevation is FocusInteraction.Focus -> focusedElevation else -> defaultElevation } val animatable = remember { Animatable(target, Dp.VectorConverter) } LaunchedEffect(target) { val lastInteraction = when (animatable.targetValue) { pressedElevation -> PressInteraction.Press(Offset.Zero) hoveredElevation -> HoverInteraction.Enter() focusedElevation -> FocusInteraction.Focus() else -> null } animatable.animateElevation( from = lastInteraction, to = interaction, target = target, ) } return animatable.asState() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is FloatingActionButtonElevation) return false if (defaultElevation != other.defaultElevation) return false if (pressedElevation != other.pressedElevation) return false if (focusedElevation != other.focusedElevation) return false if (hoveredElevation != other.hoveredElevation) return false return true } override fun hashCode(): Int { var result = defaultElevation.hashCode() result = 31 * result + pressedElevation.hashCode() result = 31 * result + focusedElevation.hashCode() result = 31 * result + hoveredElevation.hashCode() return result } } private val ExtendedFabStartIconPadding = 16.dp private val ExtendedFabEndIconPadding = 12.dp private val ExtendedFabTextPadding = 20.dp private val ExtendedFabMinimumWidth = 80.dp private val ExtendedFabCollapseAnimation = fadeOut( animationSpec = tween( durationMillis = MotionTokens.DurationShort2.toInt(), easing = MotionTokens.EasingLinearCubicBezier, ) ) + shrinkHorizontally( animationSpec = tween( durationMillis = MotionTokens.DurationLong2.toInt(), easing = MotionTokens.EasingEmphasizedCubicBezier, ), shrinkTowards = Alignment.Start, ) private val ExtendedFabExpandAnimation = fadeIn( animationSpec = tween( durationMillis = MotionTokens.DurationShort4.toInt(), delayMillis = MotionTokens.DurationShort2.toInt(), easing = MotionTokens.EasingLinearCubicBezier, ), ) + expandHorizontally( animationSpec = tween( durationMillis = MotionTokens.DurationLong2.toInt(), easing = MotionTokens.EasingEmphasizedCubicBezier, ), expandFrom = Alignment.Start, )
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/FloatingActionButton.kt
674732889
package com.github.tommykw.musical.di import android.app.Activity import android.app.Application import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.github.tommykw.musical.application.MusicalApplication import dagger.android.AndroidInjection import dagger.android.support.AndroidSupportInjection import dagger.android.support.HasSupportFragmentInjector object AppInjector { fun init(application: MusicalApplication) { DaggerAppComponent.builder().application(application) .build().inject(application) application .registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { handleActivity(activity) } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) { } override fun onActivityDestroyed(activity: Activity) { } }) } private fun handleActivity(activity: Activity) { if (activity is HasSupportFragmentInjector) { AndroidInjection.inject(activity) } if (activity is FragmentActivity) { activity.supportFragmentManager .registerFragmentLifecycleCallbacks( object : FragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentCreated( fm: FragmentManager, f: Fragment, savedInstanceState: Bundle? ) { if (f is Injectable) { AndroidSupportInjection.inject(f) } } }, true ) } } }
app/src/main/java/com/github/tommykw/musical/di/AppInjector.kt
2286253193
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import android.os.Build import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.isSimple import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.asAndroidPath import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import kotlin.math.roundToInt import android.graphics.Outline as AndroidOutline /** * Resolves the [AndroidOutline] from the [Shape] of an [OwnedLayer]. */ internal class OutlineResolver(private var density: Density) { /** * Flag to determine if the shape specified on the outline is supported. * On older API levels, concave shapes are not allowed */ private var isSupportedOutline = true /** * The Android Outline that is used in the layer. */ private val cachedOutline = AndroidOutline().apply { alpha = 1f } /** * The size of the layer. This is used in generating the [Outline] from the [Shape]. */ private var size: Size = Size.Zero /** * The [Shape] of the Outline of the Layer. */ private var shape: Shape = RectangleShape /** * Asymmetric rounded rectangles need to use a Path. This caches that Path so that * a new one doesn't have to be generated each time. */ // TODO(andreykulikov): Make Outline API reuse the Path when generating. private var cachedRrectPath: Path? = null // for temporary allocation in rounded rects /** * The outline Path when a non-conforming (rect or symmetric rounded rect) Outline * is used. This Path is necessary when [usePathForClip] is true to indicate the * Path to clip in [clipPath]. */ private var outlinePath: Path? = null /** * True when there's been an update that caused a change in the path and the Outline * has to be reevaluated. */ private var cacheIsDirty = false /** * True when Outline cannot clip the content and the path should be used instead. * This is when an asymmetric rounded rect or general Path is used in the outline. * This is false when a Rect or a symmetric RoundRect is used in the outline. */ private var usePathForClip = false /** * Scratch path used for manually clipping in software backed canvases */ private var tmpPath: Path? = null /** * Scratch [RoundRect] used for manually clipping round rects in software backed canvases */ private var tmpRoundRect: RoundRect? = null /** * Radius value used for symmetric rounded shapes. For rectangular or path based outlines * this value is 0f */ private var roundedCornerRadius: Float = 0f /** * Returns the Android Outline to be used in the layer. */ val outline: AndroidOutline? get() { updateCache() return if (!outlineNeeded || !isSupportedOutline) null else cachedOutline } /** * Determines if the particular outline shape or path supports clipping. * True for rect or symmetrical round rects. * This method is used to determine if the framework can handle clipping to the outline * for a particular shape. If not, then the clipped path must be applied directly to the canvas. */ val outlineClipSupported: Boolean get() = !usePathForClip /** * Returns the path used to manually clip regardless if the layer supports clipping or not. * In some cases (i.e. software rendering) clipping must be done manually. * Consumers should query whether or not the layer will handle clipping with * [outlineClipSupported] first before applying the clip manually. * Or when rendering in software, the clip path provided here must always be clipped manually. */ val clipPath: Path? get() { updateCache() return outlinePath } /** * Returns the top left offset for a rectangular, or rounded rect outline (regardless if it * is symmetric or asymmetric) * For path based outlines this returns [Offset.Zero] */ private var rectTopLeft: Offset = Offset.Zero /** * Returns the size for a rectangular, or rounded rect outline (regardless if it * is symmetric or asymmetric) * For path based outlines this returns [Size.Zero] */ private var rectSize: Size = Size.Zero /** * True when we are going to clip or have a non-zero elevation for shadows. */ private var outlineNeeded = false private var layoutDirection = LayoutDirection.Ltr private var tmpTouchPointPath: Path? = null private var tmpOpPath: Path? = null private var calculatedOutline: Outline? = null /** * Updates the values of the outline. Returns `true` when the shape has changed. */ fun update( shape: Shape, alpha: Float, clipToOutline: Boolean, elevation: Float, layoutDirection: LayoutDirection, density: Density ): Boolean { cachedOutline.alpha = alpha val shapeChanged = this.shape != shape if (shapeChanged) { this.shape = shape cacheIsDirty = true } val outlineNeeded = clipToOutline || elevation > 0f if (this.outlineNeeded != outlineNeeded) { this.outlineNeeded = outlineNeeded cacheIsDirty = true } if (this.layoutDirection != layoutDirection) { this.layoutDirection = layoutDirection cacheIsDirty = true } if (this.density != density) { this.density = density cacheIsDirty = true } return shapeChanged } /** * Returns true if there is a outline and [position] is outside the outline. */ fun isInOutline(position: Offset): Boolean { if (!outlineNeeded) { return true } val outline = calculatedOutline ?: return true return isInOutline(outline, position.x, position.y, tmpTouchPointPath, tmpOpPath) } /** * Manually applies the clip to the provided canvas based on the given outline. * This is used in scenarios where clipping must be applied manually either because * the outline cannot be clipped automatically for specific shapes or if the * layer is being rendered in software */ fun clipToOutline(canvas: Canvas) { // If we have a clip path that means we are clipping to an arbitrary path or // a rounded rect with non-uniform corner radii val targetPath = clipPath if (targetPath != null) { canvas.clipPath(targetPath) } else { // If we have a non-zero radius, that means we are clipping to a symmetrical // rounded rectangle. // Canvas does not include a clipRoundRect API so create a path with the round rect // and clip to the given path/ if (roundedCornerRadius > 0f) { var roundRectClipPath = tmpPath var roundRect = tmpRoundRect if (roundRectClipPath == null || !roundRect.isSameBounds(rectTopLeft, rectSize, roundedCornerRadius)) { roundRect = RoundRect( left = rectTopLeft.x, top = rectTopLeft.y, right = rectTopLeft.x + rectSize.width, bottom = rectTopLeft.y + rectSize.height, cornerRadius = CornerRadius(roundedCornerRadius) ) if (roundRectClipPath == null) { roundRectClipPath = Path() } else { roundRectClipPath.reset() } roundRectClipPath.addRoundRect(roundRect) tmpRoundRect = roundRect tmpPath = roundRectClipPath } canvas.clipPath(roundRectClipPath) } else { // ... otherwise, just clip to the bounds of the rect canvas.clipRect( left = rectTopLeft.x, top = rectTopLeft.y, right = rectTopLeft.x + rectSize.width, bottom = rectTopLeft.y + rectSize.height, ) } } } /** * Updates the size. */ fun update(size: Size) { if (this.size != size) { this.size = size cacheIsDirty = true } } private fun updateCache() { if (cacheIsDirty) { rectTopLeft = Offset.Zero rectSize = size roundedCornerRadius = 0f outlinePath = null cacheIsDirty = false usePathForClip = false if (outlineNeeded && size.width > 0.0f && size.height > 0.0f) { // Always assume the outline type is supported // The methods to configure the outline will determine/update the flag // if it not supported on the API level isSupportedOutline = true val outline = shape.createOutline(size, layoutDirection, density) calculatedOutline = outline when (outline) { is Outline.Rectangle -> updateCacheWithRect(outline.rect) is Outline.Rounded -> updateCacheWithRoundRect(outline.roundRect) is Outline.Generic -> updateCacheWithPath(outline.path) } } else { cachedOutline.setEmpty() } } } private fun updateCacheWithRect(rect: Rect) { rectTopLeft = Offset(rect.left, rect.top) rectSize = Size(rect.width, rect.height) cachedOutline.setRect( rect.left.roundToInt(), rect.top.roundToInt(), rect.right.roundToInt(), rect.bottom.roundToInt() ) } private fun updateCacheWithRoundRect(roundRect: RoundRect) { val radius = roundRect.topLeftCornerRadius.x rectTopLeft = Offset(roundRect.left, roundRect.top) rectSize = Size(roundRect.width, roundRect.height) if (roundRect.isSimple) { cachedOutline.setRoundRect( roundRect.left.roundToInt(), roundRect.top.roundToInt(), roundRect.right.roundToInt(), roundRect.bottom.roundToInt(), radius ) roundedCornerRadius = radius } else { val path = cachedRrectPath ?: Path().also { cachedRrectPath = it } path.reset() path.addRoundRect(roundRect) updateCacheWithPath(path) } } @Suppress("deprecation") private fun updateCacheWithPath(composePath: Path) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P || composePath.isConvex) { // TODO(mount): Use setPath() for R+ when available. cachedOutline.setConvexPath(composePath.asAndroidPath()) usePathForClip = !cachedOutline.canClip() } else { isSupportedOutline = false // Concave outlines are not supported on older API levels cachedOutline.setEmpty() usePathForClip = true } outlinePath = composePath } /** * Helper method to see if the RoundRect has the same bounds as the offset as well as the same * corner radius. If the RoundRect does not have symmetrical corner radii this method always * returns false */ private fun RoundRect?.isSameBounds(offset: Offset, size: Size, radius: Float): Boolean { if (this == null || !isSimple) { return false } return left == offset.x && top == offset.y && right == (offset.x + size.width) && bottom == (offset.y + size.height) && topLeftCornerRadius.x == radius } }
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/OutlineResolver.android.kt
944684590
package com.github.bfsmith.recorder import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.text.InputType.* import android.view.Gravity import android.view.View import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.ListAdapter import com.github.bfsmith.recorder.util.MyListAdapter import com.github.bfsmith.recorder.util.TemplateRenderer import com.github.bfsmith.recorder.util.showKeyboardOnFocus import org.jetbrains.anko.* import org.jetbrains.anko.design.coordinatorLayout import org.jetbrains.anko.design.floatingActionButton import org.jetbrains.anko.sdk25.coroutines.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MainActivityUi().setContentView(this) } fun tagSelected(ui: AnkoContext<MainActivity>, tag: Tag) { ui.doAsync { activityUiThreadWithContext { toast("You selected tag ${tag.tag}.") startActivity<TagViewActivity>("TagId" to tag.id) } } } } class MainActivityUi : AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>): View = with(ui) { fun addValue(tagId: Int, value: Double?): Boolean { if (value != null) { ui.owner.database.addRecordForTag(tagId, value) toast("Recorded ${value}") return true } return false } var listAdapter: MyListAdapter<Tag>? = null fun removeTag(tagId: Int) { ui.owner.database.removeTag(tagId) listAdapter?.notifyDataSetChanged() } listAdapter = MyListAdapter(owner.database.tags, { it.id }) { tag -> TemplateRenderer(owner) { with(it) { relativeLayout { // backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent) val buttonContainer = linearLayout { id = R.id.buttonContainer // Add value button imageButton(android.R.drawable.ic_input_add) { isFocusable = false onClick { var valueField: EditText? = null val alertDialog = alert { customView { verticalLayout { toolbar { lparams(width = matchParent, height = wrapContent) backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent) title = "Add a value" setTitleTextColor(ContextCompat.getColor(ctx, android.R.color.white)) } valueField = editText { hint = "Value" padding = dip(20) inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL // isFocusable = true // isFocusableInTouchMode = true showKeyboardOnFocus(ctx) imeOptions = EditorInfo.IME_ACTION_DONE } positiveButton("Add") { val value = valueField?.text.toString().toDoubleOrNull() if (addValue(tag.id, value)) { it.dismiss() } } cancelButton { } } } }.show() valueField?.onEditorAction { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE && addValue(tag.id, valueField?.text.toString().toDoubleOrNull())) { alertDialog.dismiss() } } } } imageButton(android.R.drawable.ic_delete) { isFocusable = false onClick { alert { customView { verticalLayout { toolbar { lparams(width = matchParent, height = wrapContent) backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent) title = "Delete '${tag.tag}'?" setTitleTextColor(ContextCompat.getColor(ctx, android.R.color.white)) } positiveButton("Yes") { removeTag(tag.id) it.dismiss() } negativeButton("No") {} } } }.show() } } }.lparams { width = wrapContent height = wrapContent alignParentRight() alignParentTop() } textView { text = tag.tag textSize = 32f // background = ContextCompat.getDrawable(ctx, R.drawable.border) // onClick { // ui.owner.tagSelected(ui, tag) // } }.lparams { alignParentLeft() alignParentTop() leftOf(buttonContainer) } } } } } coordinatorLayout { verticalLayout { padding = dip(8) listView { adapter = listAdapter onItemClick { _, _, _, id -> val tag = owner.database.tags.find { it.id == id.toInt() } if (tag != null) { owner.tagSelected(ui, tag) } } }.lparams { margin = dip(8) width = matchParent height = matchParent } }.lparams { width = matchParent height = matchParent } floatingActionButton { imageResource = android.R.drawable.ic_input_add onClick { fun addTag(tag: String?): Boolean { if (!tag.isNullOrEmpty()) { owner.database.addTag(tag!!) listAdapter?.notifyDataSetChanged() return true } return false } var tagField: EditText? = null val alertDialog = alert { customView { verticalLayout { toolbar { lparams(width = matchParent, height = wrapContent) backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent) title = "Add a Tag" setTitleTextColor(ContextCompat.getColor(ctx, android.R.color.white)) } tagField = editText { hint = "Tag" padding = dip(20) showKeyboardOnFocus(ctx) inputType = TYPE_CLASS_TEXT or TYPE_TEXT_FLAG_CAP_WORDS imeOptions = EditorInfo.IME_ACTION_DONE } positiveButton("Add") { if (addTag(tagField?.text.toString())) { it.dismiss() } } cancelButton { } } } }.show() tagField?.onEditorAction { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE && addTag(tagField?.text.toString())) { alertDialog.dismiss() } } } }.lparams { margin = dip(10) gravity = Gravity.BOTTOM or Gravity.END } } } }
app/src/main/java/com/github/bfsmith/recorder/MainActivity.kt
1070053076
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.openal.templates import org.lwjgl.generator.* import org.lwjgl.openal.* val AL_LOKI_IMA_ADPCM = "LOKIIMAADPCM".nativeClassAL("LOKI_IMA_ADPCM") { documentation = "Native bindings to the $extensionName extension." IntConstant( "Buffer formats.", "FORMAT_IMA_ADPCM_MONO16_EXT"..0x10000, "FORMAT_IMA_ADPCM_STEREO16_EXT"..0x10001 ) }
modules/templates/src/main/kotlin/org/lwjgl/openal/templates/AL_LOKI_IMA_ADPCM.kt
2964366017
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opencl.templates import org.lwjgl.generator.* import org.lwjgl.opencl.* val intel_motion_estimation = "INTELMotionEstimation".nativeClassCL("intel_motion_estimation", INTEL) { documentation = """ Native bindings to the $extensionLink extension. This document presents the motion estimation extension for OpenCL. This extension includes a set of host-callable functions for frame-based motion estimation and introduces motion estimators, or also "motion estimation accelerator objects". These accelerator objects provide an abstraction of software- and/or hardware-accelerated functions for motion estimation, which can be provided by select OpenCL vendors. This extension depends on the OpenCL 1.2 built-in kernel infrastructure and on the accelerator extension, which provides an abstraction for domain-specific acceleration in the OpenCL runtime. Requires ${intel_accelerator.link}. """ IntConstant( """ Accepted as a type in the {@code accelerator_type} parameter of INTELAccelerator#CreateAcceleratorINTEL(). Creates a full-frame motion estimation accelerator. """, "ACCELERATOR_TYPE_MOTION_ESTIMATION_INTEL"..0x0 ) IntConstant( "Accepted as types to the fields of {@code cl_motion_estimator_desc_intel}.", "ME_MB_TYPE_16x16_INTEL"..0x0, "ME_MB_TYPE_8x8_INTEL"..0x1, "ME_MB_TYPE_4x4_INTEL"..0x2, "ME_SUBPIXEL_MODE_INTEGER_INTEL"..0x0, "ME_SUBPIXEL_MODE_HPEL_INTEL"..0x1, "ME_SUBPIXEL_MODE_QPEL_INTEL"..0x2, "ME_SAD_ADJUST_MODE_NONE_INTEL"..0x0, "ME_SAD_ADJUST_MODE_HAAR_INTEL"..0x1, "ME_SEARCH_PATH_RADIUS_2_2_INTEL"..0x0, "ME_SEARCH_PATH_RADIUS_4_4_INTEL"..0x1, "ME_SEARCH_PATH_RADIUS_16_12_INTEL"..0x5 ) }
modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/intel_motion_estimation.kt
2770594473
/** * Photo EXIF Toolkit for Android. * * Copyright (C) 2017 Ángel Iván Gladín García * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.angelgladin.photoexiftoolkit.dialog import android.app.Activity import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.support.v7.widget.Toolbar import android.util.Log import android.view.* import com.angelgladin.photoexiftoolkit.R import com.angelgladin.photoexiftoolkit.domain.Location import com.angelgladin.photoexiftoolkit.util.Constants import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions /** * Created on 12/22/16. */ class MapDialog : DialogFragment(), OnMapReadyCallback, GoogleMap.OnMapClickListener, Toolbar.OnMenuItemClickListener { lateinit var dialogEvents: DialogEvents lateinit var toolbar: Toolbar lateinit var mMap: GoogleMap lateinit var location: LatLng lateinit var marker: Marker var editModeLocation = false var locationChanged = false companion object { fun newInstance(latitude: Double, longitude: Double): MapDialog { val frag = MapDialog() val bundle = Bundle() bundle.putDouble(Constants.EXIF_LATITUDE, latitude) bundle.putDouble(Constants.EXIF_LONGITUDE, longitude) frag.arguments = bundle return frag } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.dialog_maps, container, false) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) toolbar = view.findViewById(R.id.toolbar) as Toolbar toolbar.apply { inflateMenu(R.menu.menu_dialog_maps) setOnMenuItemClickListener(this@MapDialog) setNavigationIcon(R.drawable.ic_arrow_back_black_24dp) setNavigationOnClickListener { dismiss() } title = resources.getString(R.string.dialog_maps_title) } return view } override fun onAttach(activity: Activity?) { super.onAttach(activity) try { dialogEvents = activity as DialogEvents } catch (e: ClassCastException) { throw ClassCastException(activity.toString() + " must implement DialogEvents") } } override fun onResume() { super.onResume() val mapFragment = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onDestroyView() { super.onDestroyView() dialogEvents.locationChanged(locationChanged, Location(location.latitude, location.longitude)) Log.d(this.javaClass.simpleName, "Location changed: $locationChanged, Location: $location") val f = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment? if (f != null) fragmentManager.beginTransaction().remove(f).commit() } override fun onMenuItemClick(item: MenuItem): Boolean = when (item.itemId) { R.id.action_edit_location -> { editLocation() true } R.id.action_done_editing -> { doneEditing() true } else -> false } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap location = LatLng(arguments.getDouble(Constants.EXIF_LATITUDE), arguments.getDouble(Constants.EXIF_LONGITUDE)) mMap.apply { setOnMapClickListener(this@MapDialog) uiSettings.isZoomControlsEnabled = true isMyLocationEnabled = true moveCamera(CameraUpdateFactory.newLatLngZoom(location, 14.8f)) } addMarker(location) } override fun onMapClick(latLng: LatLng) { if (editModeLocation) { Log.d(this.javaClass.simpleName, "Latitude ${latLng.latitude} -- Longitude ${latLng.longitude}") marker.remove() addMarker(latLng) } } private fun editLocation() { editModeLocation = true toolbar.title = resources.getString(R.string.dialog_maps_title_tap_for_new_location) toolbar.menu.findItem(R.id.action_edit_location).isVisible = false toolbar.menu.findItem(R.id.action_done_editing).isVisible = true } private fun doneEditing() { editModeLocation = false showAlertDialog() toolbar.title = resources.getString(R.string.dialog_maps_title) toolbar.menu.findItem(R.id.action_done_editing).isVisible = false toolbar.menu.findItem(R.id.action_edit_location).isVisible = true } private fun showAlertDialog() { AlertDialog.Builder(context) .setTitle(resources.getString(R.string.dialog_maps_title_edit_location)) .setMessage(resources.getString(R.string.dialog_maps_title_edit_location_message)) .setPositiveButton(resources.getString(android.R.string.ok), { dialogInterface, i -> locationChanged = true location = marker.position dismiss() }) .setNegativeButton(resources.getString(android.R.string.cancel), { dialogInterface, i -> marker.remove() addMarker(location) }) .show() } private fun addMarker(location: LatLng) { marker = mMap.addMarker(MarkerOptions().position(location)) marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) } interface DialogEvents { fun locationChanged(locationChanged: Boolean, location: Location) } }
app/src/main/kotlin/com/angelgladin/photoexiftoolkit/dialog/MapsDialog.kt
3845903851
package com.commonsense.android.kotlin.system.base import com.commonsense.android.kotlin.system.R import com.commonsense.android.kotlin.system.logging.* import com.commonsense.android.kotlin.test.* import kotlinx.coroutines.* import org.junit.* import org.robolectric.* import org.robolectric.annotation.* import java.util.concurrent.* /** * Created by Kasper Tvede on 07-10-2017. */ @Config(sdk = [21]) class BaseActivityTest : BaseRoboElectricTest() { @Throws(InterruptedException::class) @Test fun launchInUiLifecycleEventsPaused() = testCallbackWithSemaphore( shouldAcquire = false, errorMessage = "callback should not be called") { _ -> val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() pause() } act.get().launchInUi("test") { failTest("Should not get called when the pause or destroy have been called") } } @Throws(InterruptedException::class) @Test fun launchInUiLifecycleEventsPausedResume() { val sem = Semaphore(0) val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() pause() } var counter = 0 act.get().launchInUi("test") { if (counter == 0) { failTest("Should not get called when the pause or destroy have been called") } else { sem.release() } } counter += 1 act.visible() act.resume() act.postResume() awaitAllTheading({ sem.tryAcquire() }, 1, TimeUnit.SECONDS, "callback should be called after onresume after a pause") } @Throws(InterruptedException::class) @Test fun launchInUiLifecycleEventsPausedDestory() = testCallbackWithSemaphore( shouldAcquire = false, errorMessage = "callback should be called after onresume after a pause") { val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() pause() } act.get().launchInUi("test") { failTest("Should not get called when the pause or destroy have been called") } runBlocking { Robolectric.flushBackgroundThreadScheduler() Robolectric.flushForegroundThreadScheduler() delay(50) } act.destroy() (tryAndLog("should throw due to ") { act.postResume() false } ?: true).assert(true, "should throw as the activity is dead. ") } @Throws(InterruptedException::class) @Test fun launchInBackgroundLifecycleEventsPaused() = testCallbackWithSemaphore( shouldAcquire = true, errorMessage = "callback should be called even when activity is paused.") { sem -> val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() pause() } act.get().launchInBackground("test") { sem.release() } } @Throws(InterruptedException::class) @Test fun launchInUiLifecycleEventsVisible() = testCallbackWithSemaphore( shouldAcquire = true, errorMessage = "callback should be called") { sem -> val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() visible() } act.get().launchInUi("test") { sem.release() } } @Throws(InterruptedException::class) @Test fun launchInBackgroundLifecycleEventsVisible() = testCallbackWithSemaphore( shouldAcquire = true, errorMessage = "callback should be called") { sem -> val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() visible() } act.get().launchInBackground("test") { sem.release() } } @Throws(InterruptedException::class) @Test fun addOnBackPressedListeners() = testCallbackWithSemaphore( shouldAcquire = true, errorMessage = "callback should be called") { sem -> val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() visible() } val listerner = { sem.release() true } act.get().apply { addOnBackPressedListener(listerner) } act.get().onBackPressed() } @Throws(InterruptedException::class) @Test fun removeOnBackPressedListeners() = testCallbackWithSemaphore( shouldAcquire = false, errorMessage = "callback should NOT be called") { val act = createActivityController<BaseActivity>(R.style.Theme_AppCompat).apply { setup() visible() } val listerner = { failTest("Should not be called once removed.") true } act.get().apply { addOnBackPressedListener(listerner) removeOnBackPressedListener(listerner) } act.get().onBackPressed() } /* @Test fun onBackPressedSuperNotCalledDueToListener() { //TODO make me //listener for the supers on back pressed and tell if it gets called. in all senarious (no listeners, , only no listeners, only yes listeners, mixture). }*/ @Ignore @Test fun `getPermissionHandler$system_debug`() { } @Ignore @Test fun getReceiverHandler() { } @Ignore @Test fun getKeyboardHandler() { } @Ignore @Test fun addOnBackPressedListener() { } @Ignore @Test fun removeOnBackPressedListener() { } @Ignore @Test fun launchInUi() { } @Ignore @Test fun launchInBackground() { } @Ignore @Test fun onCreate() { } @Ignore @Test fun onRequestPermissionsResult() { } @Ignore @Test fun onDestroy() { } @Ignore @Test fun onOptionsItemSelected() { } @Ignore @Test fun onActivityResult() { } @Ignore @Test fun onResume() { } @Ignore @Test fun onPostResume() { } @Ignore @Test fun onPause() { } @Ignore @Test fun onBackPressed() { } @Ignore @Test fun addActivityResultListenerOnlyOk() { } @Ignore @Test fun addActivityResultListener() { } @Ignore @Test fun addActivityResultListenerOnlyOkAsync() { } @Ignore @Test fun addActivityResultListenerAsync() { } @Ignore @Test fun removeActivityResultListener() { } @Ignore @Test fun isPaused() { } @Ignore @Test fun isVisible() { } @Ignore @Test fun getMIsPaused() { } @Ignore @Test fun setMIsPaused() { } @Ignore @Test fun registerReceiver() { } @Ignore @Test fun registerReceiver1() { } @Ignore @Test fun registerReceiver2() { } @Ignore @Test fun registerReceiver3() { } @Ignore @Test fun unregisterReceiver() { } @Ignore @Test fun toPrettyString() { } }
system/src/test/kotlin/com/commonsense/android/kotlin/system/base/BaseActivityTest.kt
676803343
package gl4 import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.KeyListener import com.jogamp.newt.event.WindowAdapter import com.jogamp.newt.event.WindowEvent import com.jogamp.newt.opengl.GLWindow import com.jogamp.opengl.* import com.jogamp.opengl.GL2ES2.GL_DEBUG_SEVERITY_HIGH import com.jogamp.opengl.GL2ES2.GL_DEBUG_SEVERITY_MEDIUM import com.jogamp.opengl.GL2ES3.* import com.jogamp.opengl.GL4.GL_MAP_COHERENT_BIT import com.jogamp.opengl.GL4.GL_MAP_PERSISTENT_BIT import com.jogamp.opengl.util.Animator import com.jogamp.opengl.util.texture.TextureIO import framework.Semantic import glm.* import glm.mat.Mat4 import glm.vec._2.Vec2 import glm.vec._3.Vec3 import glm.vec._4.Vec4 import uno.buffer.* import uno.debug.GlDebugOutput import uno.glsl.Program import java.nio.ByteBuffer import java.nio.FloatBuffer import java.nio.ShortBuffer import kotlin.properties.Delegates fun main(args: Array<String>) { HelloGlobe_().setup() } class HelloGlobe_ : GLEventListener, KeyListener { var window by Delegates.notNull<GLWindow>() val animator = Animator() object Buffer { val VERTEX = 0 val ELEMENT = 1 val GLOBAL_MATRICES = 2 val MODEL_MATRIX = 3 val MAX = 4 } val bufferName = intBufferBig(Buffer.MAX) val vertexArrayName = intBufferBig(1) val textureName = intBufferBig(1) val samplerName = intBufferBig(1) val clearColor = floatBufferBig(Vec4.length) val clearDepth = floatBufferBig(1) var globalMatricesPointer by Delegates.notNull<ByteBuffer>() var modelMatrixPointer by Delegates.notNull<ByteBuffer>() // https://jogamp.org/bugzilla/show_bug.cgi?id=1287 val bug1287 = true var program by Delegates.notNull<Program>() var start = 0L var elementCount = 0 fun setup() { val glProfile = GLProfile.get(GLProfile.GL3) val glCapabilities = GLCapabilities(glProfile) window = GLWindow.create(glCapabilities) window.title = "Hello Globe" window.setSize(1024, 768) window.contextCreationFlags = GLContext.CTX_OPTION_DEBUG window.isVisible = true window.addGLEventListener(this) window.addKeyListener(this) animator.add(window) animator.start() window.addWindowListener(object : WindowAdapter() { override fun windowDestroyed(e: WindowEvent?) { animator.stop() System.exit(1) } }) } override fun init(drawable: GLAutoDrawable) { val gl = drawable.gl.gL4 initDebug(gl) initBuffers(gl) initTexture(gl) initSampler(gl) initVertexArray(gl) program = Program(gl, this::class.java, "shaders/gl4", "hello-globe.vert", "hello-globe.frag") gl.glEnable(GL.GL_DEPTH_TEST) start = System.currentTimeMillis() } fun initDebug(gl: GL4) = with(gl) { window.context.addGLDebugListener(GlDebugOutput()) glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, null, false) glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, null, true) glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, null, true) } fun initBuffers(gl: GL4) = with(gl) { val radius = 1f val rings = 100.s val sectors = 100.s val vertexBuffer = getVertexBuffer(radius, rings, sectors) val elementBuffer = getElementBuffer(radius, rings, sectors) elementCount = elementBuffer.capacity() glCreateBuffers(Buffer.MAX, bufferName) if (!bug1287) { glNamedBufferStorage(bufferName[Buffer.VERTEX], vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW) glNamedBufferStorage(bufferName[Buffer.ELEMENT], elementBuffer.SIZE.L, elementBuffer, GL_STATIC_DRAW) glNamedBufferStorage(bufferName[Buffer.GLOBAL_MATRICES], Mat4.SIZE * 2.L, null, GL_MAP_WRITE_BIT) glNamedBufferStorage(bufferName[Buffer.MODEL_MATRIX], Mat4.SIZE.L, null, GL_MAP_WRITE_BIT) } else { glBindBuffer(GL_ARRAY_BUFFER, bufferName[Buffer.VERTEX]) glBufferStorage(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, 0) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName[Buffer.ELEMENT]) glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.SIZE.L, elementBuffer, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) val uniformBufferOffset = intBufferBig(1) glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, uniformBufferOffset) val globalBlockSize = glm.max(Mat4.SIZE * 2, uniformBufferOffset[0]) val modelBlockSize = glm.max(Mat4.SIZE, uniformBufferOffset[0]) glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.GLOBAL_MATRICES]) glBufferStorage(GL_UNIFORM_BUFFER, globalBlockSize.L, null, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT) glBindBuffer(GL_UNIFORM_BUFFER, 0) glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.MODEL_MATRIX]) glBufferStorage(GL_UNIFORM_BUFFER, modelBlockSize.L, null, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT) glBindBuffer(GL_UNIFORM_BUFFER, 0) uniformBufferOffset.destroy() } destroyBuffers(vertexBuffer, elementBuffer) // map the transform buffers and keep them mapped globalMatricesPointer = glMapNamedBufferRange( bufferName[Buffer.GLOBAL_MATRICES], 0, Mat4.SIZE * 2.L, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT or GL_MAP_INVALIDATE_BUFFER_BIT) modelMatrixPointer = glMapNamedBufferRange( bufferName[Buffer.MODEL_MATRIX], 0, Mat4.SIZE.L, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT or GL_MAP_INVALIDATE_BUFFER_BIT) } fun getVertexBuffer(radius: Float, rings: Short, sectors: Short): FloatBuffer { val R = 1f / (rings - 1).toFloat() val S = 1f / (sectors - 1).toFloat() var r: Short = 0 var s: Short var x: Float var y: Float var z: Float val vertexBuffer = floatBufferBig(rings.toInt() * sectors.toInt() * (3 + 2)) while (r < rings) { s = 0 while (s < sectors) { x = glm.cos(2f * glm.pi.toFloat() * s.toFloat() * S) * glm.sin(glm.pi.toFloat() * r.toFloat() * R) y = glm.sin(-glm.pi.toFloat() / 2 + glm.pi.toFloat() * r.toFloat() * R) z = glm.sin(2f * glm.pi.toFloat() * s.toFloat() * S) * glm.sin(glm.pi.toFloat() * r.toFloat() * R) // positions vertexBuffer.put(x * radius) vertexBuffer.put(y * radius) vertexBuffer.put(z * radius) // texture coordinates vertexBuffer.put(1 - s * S) vertexBuffer.put(r * R) s++ } r++ } vertexBuffer.position(0) return vertexBuffer } fun getElementBuffer(radius: Float, rings: Short, sectors: Short): ShortBuffer { val R = 1f / (rings - 1).f val S = 1f / (sectors - 1).f var r = 0.s var s: Short val x: Float val y: Float val z: Float val elementBuffer = shortBufferBig(rings.i * sectors.i * 6) while (r < rings - 1) { s = 0 while (s < sectors - 1) { elementBuffer.put((r * sectors + s).s) elementBuffer.put((r * sectors + (s + 1)).s) elementBuffer.put(((r + 1) * sectors + (s + 1)).s) elementBuffer.put(((r + 1) * sectors + (s + 1)).s) elementBuffer.put((r * sectors + s).s) // elementBuffer.put((short) (r * sectors + (s + 1))); elementBuffer.put(((r + 1) * sectors + s).s) s++ } r++ } elementBuffer.position(0) return elementBuffer } fun initVertexArray(gl: GL4) = with(gl) { glCreateVertexArrays(1, vertexArrayName) glVertexArrayAttribBinding(vertexArrayName[0], Semantic.Attr.POSITION, Semantic.Stream.A) glVertexArrayAttribBinding(vertexArrayName[0], Semantic.Attr.TEXCOORD, Semantic.Stream.A) glVertexArrayAttribFormat(vertexArrayName[0], Semantic.Attr.POSITION, Vec3.length, GL_FLOAT, false, 0) glVertexArrayAttribFormat(vertexArrayName[0], Semantic.Attr.TEXCOORD, Vec2.length, GL_FLOAT, false, Vec3.SIZE) glEnableVertexArrayAttrib(vertexArrayName[0], Semantic.Attr.POSITION) glEnableVertexArrayAttrib(vertexArrayName[0], Semantic.Attr.TEXCOORD) glVertexArrayElementBuffer(vertexArrayName[0], bufferName[Buffer.ELEMENT]) glVertexArrayVertexBuffer(vertexArrayName[0], Semantic.Stream.A, bufferName[Buffer.VERTEX], 0, Vec2.SIZE + Vec3.SIZE) } fun initTexture(gl: GL4) = with(gl) { val texture = this::class.java.classLoader.getResource("images/globe.png") val textureData = TextureIO.newTextureData(glProfile, texture!!, false, TextureIO.PNG) glCreateTextures(GL_TEXTURE_2D, 1, textureName) glTextureParameteri(textureName[0], GL_TEXTURE_BASE_LEVEL, 0) glTextureParameteri(textureName[0], GL_TEXTURE_MAX_LEVEL, 0) glTextureStorage2D(textureName[0], 1, // level textureData.internalFormat, textureData.width, textureData.height) glTextureSubImage2D(textureName.get(0), 0, // level 0, 0, // offset textureData.width, textureData.height, textureData.pixelFormat, textureData.pixelType, textureData.buffer) } fun initSampler(gl: GL4) = with(gl) { glGenSamplers(1, samplerName) glSamplerParameteri(samplerName[0], GL_TEXTURE_MAG_FILTER, GL_NEAREST) glSamplerParameteri(samplerName[0], GL_TEXTURE_MIN_FILTER, GL_NEAREST) glSamplerParameteri(samplerName[0], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glSamplerParameteri(samplerName[0], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) } override fun display(drawable: GLAutoDrawable) = with(drawable.gl.gL4) { // view matrix run { val view = glm.lookAt(Vec3(0f, 0f, 3f), Vec3(), Vec3(0f, 1f, 0f)) view.to(globalMatricesPointer, Mat4.SIZE) } glClearBufferfv(GL_COLOR, 0, clearColor.put(1f, .5f, 0f, 1f)) glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1f)) // model matrix run { val now = System.currentTimeMillis() val diff = (now - start).f / 1_000f val model = Mat4().rotate_(-diff, 0f, 1f, 0f) model to modelMatrixPointer } glUseProgram(program.name) glBindVertexArray(vertexArrayName[0]) glBindBufferBase( GL_UNIFORM_BUFFER, Semantic.Uniform.TRANSFORM0, bufferName[Buffer.GLOBAL_MATRICES]) glBindBufferBase( GL_UNIFORM_BUFFER, Semantic.Uniform.TRANSFORM1, bufferName[Buffer.MODEL_MATRIX]) glBindTextureUnit( Semantic.Sampler.DIFFUSE, textureName[0]) glBindSampler(Semantic.Sampler.DIFFUSE, samplerName[0]) glDrawElements( GL.GL_TRIANGLES, elementCount, GL_UNSIGNED_SHORT, 0) } override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) { val gl = drawable.gl.gL4 val aspect = width.f / height val proj = glm.perspective(glm.pi.f * 0.25f, aspect, 0.1f, 100f) proj to globalMatricesPointer } override fun dispose(drawable: GLAutoDrawable) = with(drawable.gl.gL4) { glUnmapNamedBuffer(bufferName[Buffer.GLOBAL_MATRICES]) glUnmapNamedBuffer(bufferName[Buffer.MODEL_MATRIX]) glDeleteProgram(program.name) glDeleteVertexArrays(1, vertexArrayName) glDeleteBuffers(Buffer.MAX, bufferName) glDeleteTextures(1, textureName) glDeleteSamplers(1, samplerName) destroyBuffers(vertexArrayName, bufferName, textureName, samplerName, clearColor, clearDepth) } override fun keyPressed(e: KeyEvent) { if (e.keyCode == KeyEvent.VK_ESCAPE) { Thread { window.destroy() }.start() } } override fun keyReleased(e: KeyEvent) {} }
src/main/kotlin/gl4/helloGlobe.kt
549523504
package com.jagrosh.jdautilities.menu import com.jagrosh.jdautilities.waiter.EventWaiter import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.MessageEmbed import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent import xyz.gnarbot.gnar.utils.embed import java.awt.Color import java.util.concurrent.TimeUnit class Selector(waiter: EventWaiter, user: User?, title: String?, description: String?, color: Color?, fields: List<MessageEmbed.Field>, val type: Type, val options: List<Entry>, timeout: Long, unit: TimeUnit, finally: (Message?) -> Unit) : Menu(waiter, user, title, description, color, fields, timeout, unit, finally) { enum class Type { REACTIONS, MESSAGE } val cancel = "\u274C" var message: Message? = null fun display(channel: TextChannel) { if (!channel.guild.selfMember.hasPermission(channel, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_MANAGE, Permission.MESSAGE_EMBED_LINKS)) { channel.sendMessage(embed("Error") { color { Color.RED } desc { buildString { append("The bot requires the permission `${Permission.MESSAGE_ADD_REACTION.getName()}`, ") append("`${Permission.MESSAGE_MANAGE.getName()}` and ") append("`${Permission.MESSAGE_EMBED_LINKS.getName()}` for selection menus.") } } }.build()).queue() finally(message) return } channel.sendMessage(embed(title) { color { channel.guild.selfMember.color } description { buildString { append(description).append('\n').append('\n') options.forEachIndexed { index, (name) -> append("${'\u0030' + index}\u20E3 $name\n") } } } field("Select an Option") { when (type) { Type.REACTIONS -> "Pick a reaction corresponding to the options." Type.MESSAGE -> "Type a number corresponding to the options. ie: `0` or `cancel`" } } super.fields.forEach { addField(it) } setFooter("This selection will time out in $timeout ${unit.toString().toLowerCase()}.", null) }.build()).queue { message = it when (type) { Type.REACTIONS -> { options.forEachIndexed { index, _ -> it.addReaction("${'\u0030' + index}\u20E3").queue() } it.addReaction(cancel).queue() } Type.MESSAGE -> { /* pass */ } } } when (type) { Type.REACTIONS -> { waiter.waitFor(MessageReactionAddEvent::class.java) { if (it.reaction.reactionEmote.name == cancel) { finally(message) return@waitFor } val value = it.reaction.reactionEmote.name[0] - '\u0030' it.channel.retrieveMessageById(it.messageIdLong).queue { options[value].action(it) } finally(message) }.predicate { when { it.messageIdLong != message?.idLong -> false it!!.user!!.isBot -> false user != null && it.user != user -> { it.reaction.removeReaction(it!!.user!!).queue() false } else -> { if (it.reaction.reactionEmote.name == cancel) { true } else { val value = it.reaction.reactionEmote.name[0] - '\u0030' if (value in 0 until options.size) { true } else { it.reaction.removeReaction(it!!.user!!).queue() false } } } } }.timeout(timeout, unit) { finally(message) } } Type.MESSAGE -> { waiter.waitFor(GuildMessageReceivedEvent::class.java) { val content = it.message.contentDisplay if (content == "cancel") { finally(message) return@waitFor } val value = content.toIntOrNull() ?: return@waitFor it.channel.retrieveMessageById(it.messageIdLong).queue { options[value].action(it) } finally(message) }.predicate { when { it.author.isBot -> false user != null && it.author != user -> { false } else -> { val content = it.message.contentDisplay if (content == "cancel") { true } else { val value = content.toIntOrNull() ?: return@predicate false value in 0 until options.size } } } }.timeout(timeout, unit) { finally(message) } } } } data class Entry(val name: String, val action: (Message) -> Unit) }
src/main/kotlin/com/jagrosh/jdautilities/menu/Selector.kt
295218585
package org.smileLee.cyls import org.ansj.splitWord.analysis.ToAnalysis import org.smileLee.cyls.cyls.Cyls /** * @author 2333 */ object Main { private val loggerInfoName = "cylsData/cylsInfo.properties" private val cyls = Cyls(loggerInfoName) @JvmStatic fun main(args: Array<String>) { ToAnalysis.parse("233").toString() //初始化分词库,无实际作用 cyls.init() } }
src/main/kotlin/org/smileLee/cyls/Main.kt
3291844057
// Copyright (c) 2017, Daniel Andersen (daniel@trollsahead.dk) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package dk.etiktak.backend.security import dk.etiktak.backend.model.acl.AclRole import org.springframework.security.core.GrantedAuthority open class AuthenticationAuthority constructor( private val role: AclRole): GrantedAuthority { override fun getAuthority(): String? { return role.name } }
src/main/kotlin/dk/etiktak/backend/security/AuthenticationAuthority.kt
1038778369
package com.demonwav.statcraft.listeners import org.bukkit.event.Listener class XpGainedListener : Listener { }
statcraft-bukkit/src/main/kotlin/com/demonwav/statcraft/listeners/XpGainedListener.kt
2871007810
/* Copyright (c) 2021 Boris Timofeev This file is part of UniPatcher. UniPatcher 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. UniPatcher 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 UniPatcher. If not, see <http://www.gnu.org/licenses/>. */ package org.emunix.unipatcher.utils import org.junit.Assert.* import org.junit.* class Crc16Test { private val crc16 = Crc16() @Test fun `check crc16 with A`() { assertEquals(0xB915, crc16.calculate("A".toByteArray())) } @Test fun `check crc16 with 123456789`() { assertEquals(0x29B1, crc16.calculate("123456789".toByteArray())) } @Test fun `check crc16 with empty value`() { assertEquals(0xFFFF, crc16.calculate("".toByteArray())) } }
app/src/test/java/org/emunix/unipatcher/utils/Crc16Test.kt
3312008323