path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
px-checkout/src/main/java/com/mercadopago/android/px/internal/audio/SelectPaymentSoundUseCase.kt | ETS-Android5 | 497,641,294 | true | {"Java Properties": 1, "Markdown": 7, "Gradle": 15, "Shell": 1, "INI": 4, "YAML": 2, "Batchfile": 1, "Text": 1, "Ignore List": 7, "Proguard": 5, "XML": 228, "Kotlin": 655, "Java": 446, "JSON": 45, "HTML": 309, "JavaScript": 14, "CSS": 6, "SVG": 2, "Python": 2} | package com.mercadopago.android.px.internal.audio
import com.mercadopago.android.px.internal.base.CoroutineContextProvider
import com.mercadopago.android.px.internal.base.use_case.UseCase
import com.mercadopago.android.px.internal.callbacks.Response
import com.mercadopago.android.px.internal.repository.PaymentSettingRepository
import com.mercadopago.android.px.model.PaymentResult
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.tracking.internal.MPTracker
internal class SelectPaymentSoundUseCase(
tracker: MPTracker,
private val paymentSettingRepository: PaymentSettingRepository,
override val contextProvider: CoroutineContextProvider = CoroutineContextProvider()
) : UseCase<PaymentResult, AudioPlayer.Sound>(tracker) {
override suspend fun doExecute(param: PaymentResult): Response<AudioPlayer.Sound, MercadoPagoError> {
var sound = AudioPlayer.Sound.NONE
if (paymentSettingRepository.configuration.sonicBrandingEnabled()) {
sound = when {
param.isApproved -> AudioPlayer.Sound.SUCCESS
param.isRejected -> AudioPlayer.Sound.FAILURE
else -> AudioPlayer.Sound.NONE
}
}
return Response.Success(sound)
}
} | 0 | Java | 0 | 0 | 99f1433c4147dfd8646420fefacc688f23fc390f | 1,290 | px-android | MIT License |
chats/src/main/java/com/cyberland/messenger/chats/privatechat/ContactCardShareForwardActivity.kt | Era-CyberLabs | 576,196,269 | false | {"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472} | package com.bcm.messenger.chats.privatechat
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.bcm.messenger.chats.R
import com.bcm.messenger.chats.group.logic.GroupMessageLogic
import com.bcm.messenger.chats.privatechat.logic.MessageSender
import com.bcm.messenger.common.ARouterConstants
import com.bcm.messenger.common.AccountSwipeBaseActivity
import com.bcm.messenger.common.core.Address
import com.bcm.messenger.common.core.AmeGroupMessage
import com.bcm.messenger.common.grouprepository.model.AmeGroupMessageDetail
import com.bcm.messenger.common.provider.IForwardSelectProvider
import com.bcm.messenger.common.recipients.Recipient
import com.bcm.messenger.common.sms.OutgoingLocationMessage
import com.bcm.messenger.common.utils.AmeAppLifecycle
import com.bcm.messenger.common.utils.GroupUtil
import com.bcm.messenger.utility.logger.ALog
import com.bcm.route.annotation.Route
import com.bcm.route.api.BcmRouter
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by wjh on 2019/6/14
*/
@Route(routePath = ARouterConstants.Activity.CONTACT_SHARE_FORWARD)
class ContactCardShareForwardActivity : AccountSwipeBaseActivity() {
private val TAG = "ContactCardShareForwardActivity"
private var mFromAddress: Address? = null
private var mFromRecipient: Recipient? = null
override fun onCreate(savedInstanceState: Bundle?) {
disableDefaultTransitionAnimation()
overridePendingTransition(R.anim.common_slide_from_bottom_fast, 0)
super.onCreate(savedInstanceState)
setContentView(R.layout.chats_activity_forward)
setSwipeBackEnable(false)
val address = intent.getParcelableExtra(ARouterConstants.PARAM.PARAM_ADDRESS) as? Address
if (address == null) {
finish()
return
}
mFromAddress = address
mFromRecipient = Recipient.from(address, true)
initView()
}
private fun initView() {
val forwardProvider = BcmRouter.getInstance().get(ARouterConstants.Fragment.FORWARD_FRAGMENT).navigationWithCast<Fragment>()
if (forwardProvider is IForwardSelectProvider) {
forwardProvider.setCallback(object : IForwardSelectProvider.ForwardSelectCallback {
override fun onClickContact(recipient: Recipient) {
if (recipient.isGroupRecipient) {
doForwardForGroup(GroupUtil.gidFromAddress(recipient.address))
}else {
doForwardForPrivate(recipient)
}
}
})
forwardProvider.setContactSelectContainer(R.id.activity_forward_root)
forwardProvider.setGroupSelectContainer(R.id.activity_forward_root)
}
initFragment(R.id.activity_forward_root, forwardProvider, null)
}
override fun finish() {
super.finish()
overridePendingTransition(0, R.anim.common_slide_to_bottom_fast)
}
private fun doForwardForGroup(toGroupId: Long) {
try {
val recipient = mFromRecipient ?: return
val address = mFromAddress ?: return
AmeAppLifecycle.showLoading()
val contactContent = AmeGroupMessage.ContactContent(recipient.bcmName ?: recipient.address.format(), address.serialize(), "")
GroupMessageLogic.get(accountContext).messageSender.sendContactMessage(toGroupId, contactContent,
object : com.bcm.messenger.chats.group.logic.MessageSender.SenderCallback {
override fun call(messageDetail: AmeGroupMessageDetail?, indexId: Long, isSuccess: Boolean) {
ALog.d(TAG, "doForwardForGroup result: $isSuccess")
AmeAppLifecycle.hideLoading()
if (isSuccess) {
AmeAppLifecycle.succeed(getString(R.string.chats_group_share_forward_success), true) {
finish()
}
} else {
AmeAppLifecycle.failure(getString(R.string.chats_group_share_forward_fail), true)
}
}
})
}catch (ex: Exception) {
ALog.e(TAG, "doForwardForGroup error", ex)
}
}
private fun doForwardForPrivate(toRecipient: Recipient) {
val recipient = mFromRecipient ?: return
val address = mFromAddress ?: return
AmeAppLifecycle.showLoading()
val ameGroupMessage = AmeGroupMessage(AmeGroupMessage.CONTACT, AmeGroupMessage.ContactContent(recipient.bcmName ?: recipient.address.format(), address.serialize(), "")).toString()
val message = OutgoingLocationMessage(toRecipient, ameGroupMessage, (toRecipient.expireMessages * 1000).toLong())
Observable.create(ObservableOnSubscribe<Long> {
it.onNext(MessageSender.send(this, accountContext, message, -1L, null))
it.onComplete()
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
AmeAppLifecycle.hideLoading()
AmeAppLifecycle.succeed(getString(R.string.chats_group_share_forward_success), true) {
finish()
}
}, {
ALog.e(TAG, "doForwardForPrivate error", it)
AmeAppLifecycle.hideLoading()
AmeAppLifecycle.failure(getString(R.string.chats_group_share_forward_fail), true)
})
}
} | 1 | null | 1 | 1 | 65a11e5f009394897ddc08f4252969458454d052 | 5,660 | cyberland-android | Apache License 2.0 |
strings/src/test/kotlin/PigLatinTest.kt | gyoge0 | 528,445,664 | false | {"Java": 231909, "Kotlin": 26585} | // <NAME> APCS 2022-23
package com.gyoge.apcs
import com.gyoge.apcs.PigLatin.pig
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
@Suppress("SpellCheckingInspection")
class PigLatinTest {
@Test
fun `pig to igpay`() = assertEquals(
"igpay",
pig("pig"),
)
@Test
fun `latin to atinlay`() = assertEquals(
"atinlay",
pig("latin"),
)
@Test
fun `this to isthay`() = assertEquals(
"isthay",
pig("this"),
)
@Test
fun `strange to angestray`() = assertEquals(
"angestray",
pig("strange"),
)
@Test
fun `invalid test`() = assertEquals(
"**** INVALID ****",
pig("bcdfgh"),
)
@Nested
inner class QuCase {
@Test
fun `question to estionquay`() = assertEquals(
"estionquay",
pig("question"),
)
@Test
fun `squeeze to eezesquay`() = assertEquals(
"eezesquay",
pig("squeeze"),
)
}
@Nested
inner class YCases {
@Test
fun `yes to esyay`() = assertEquals(
"esyay",
pig("yes"),
)
@Test
fun `rhyme to ymerhay`() = assertEquals(
"ymerhay",
pig("rhyme"),
)
@Test
fun `try to ytray`() = assertEquals(
"ytray",
pig("try"),
)
}
@Nested
inner class Capitalization {
@Test
fun `Thomas to Omasthay`() = assertEquals(
"Omasthay",
pig("Thomas"),
)
@Test
fun `Jefferson to Effersonjay`() = assertEquals(
"Effersonjay",
pig("Jefferson"),
)
@Test
fun `McDonald to OnaldmcDay`() = assertEquals(
"OnaldmcDay",
pig("McDonald"),
)
@Test
fun `McArthur to Arthurmcay`() = assertEquals(
"Arthurmcay",
pig("McArthur"),
)
}
@Suppress("DANGEROUS_CHARACTERS")
@Nested
inner class Punctuation {
@Test
fun `What? to Atwhay?`() = assertEquals(
"Atwhay?",
pig("What?"),
)
@Test
fun `Oh! to Ohway!`() = assertEquals(
"Ohway!",
pig("Oh!"),
)
@Test
fun `"hello" to "ellohay"`() = assertEquals(
"ellohay",
pig("hello"),
)
@Test
fun `"Hello!!!!" to "Ellohay!!!!"`() = assertEquals(
"Ellohay!!!!",
pig("Hello!!!!"),
)
@Test
fun `don't to on'tday`() = assertEquals(
"on'tday",
pig("don't"),
)
}
}
| 1 | null | 1 | 1 | 9c97d3e36e32f319700f346f627b0ebfc7c23509 | 2,774 | APCS | MIT License |
server/engine/src/main/kotlin/io/rsbox/server/engine/net/http/HttpUtil.kt | qatar-prog | 758,639,769 | false | {"INI": 3, "Gradle Kotlin DSL": 14, "Shell": 1, "Java Properties": 1, "Git Attributes": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Kotlin": 122, "Java": 546, "XML": 5} | package io.rsbox.server.engine.net.http
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.DefaultFullHttpResponse
import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.handler.codec.http.HttpVersion
fun ChannelHandlerContext.writeHttpError(status: HttpResponseStatus, error: String = "Failed: $status\r\n") {
val response = DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
status,
Unpooled.copiedBuffer(error, Charsets.UTF_8)
)
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8")
writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
}
fun ChannelHandlerContext.writeHttpFile(file: ByteArray, name: String) {
val response = DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.wrappedBuffer(file)
)
response.headers().set(HttpHeaderNames.SERVER, "JaGeX/3.1")
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream")
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, file.size)
response.headers().set(HttpHeaderNames.CONTENT_DISPOSITION, name)
response.headers().set(HttpHeaderNames.CONTENT_ENCODING, "lzma")
channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
}
fun ChannelHandlerContext.writeHttpText(text: ByteArray) {
val response = DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.wrappedBuffer(text)
)
response.headers().set(HttpHeaderNames.SERVER, "JaGeX/3.1")
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=ISO-8859-1")
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, text.size)
channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
} | 1 | null | 1 | 1 | 58d6086e3318170a069c9a4985d06e068b853535 | 1,953 | rsbox | Apache License 2.0 |
server/engine/src/main/kotlin/io/rsbox/server/engine/net/http/HttpUtil.kt | qatar-prog | 758,639,769 | false | {"INI": 3, "Gradle Kotlin DSL": 14, "Shell": 1, "Java Properties": 1, "Git Attributes": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Kotlin": 122, "Java": 546, "XML": 5} | package io.rsbox.server.engine.net.http
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.DefaultFullHttpResponse
import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.handler.codec.http.HttpVersion
fun ChannelHandlerContext.writeHttpError(status: HttpResponseStatus, error: String = "Failed: $status\r\n") {
val response = DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
status,
Unpooled.copiedBuffer(error, Charsets.UTF_8)
)
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8")
writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
}
fun ChannelHandlerContext.writeHttpFile(file: ByteArray, name: String) {
val response = DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.wrappedBuffer(file)
)
response.headers().set(HttpHeaderNames.SERVER, "JaGeX/3.1")
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream")
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, file.size)
response.headers().set(HttpHeaderNames.CONTENT_DISPOSITION, name)
response.headers().set(HttpHeaderNames.CONTENT_ENCODING, "lzma")
channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
}
fun ChannelHandlerContext.writeHttpText(text: ByteArray) {
val response = DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.wrappedBuffer(text)
)
response.headers().set(HttpHeaderNames.SERVER, "JaGeX/3.1")
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=ISO-8859-1")
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, text.size)
channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
} | 1 | null | 1 | 1 | 58d6086e3318170a069c9a4985d06e068b853535 | 1,953 | rsbox | Apache License 2.0 |
compose-designer/src/com/android/tools/idea/compose/preview/animation/AnimationInspectorPanel.kt | TrellixVulnTeam | 571,897,700 | true | {"Text": 355, "EditorConfig": 2, "Markdown": 64, "Shell": 32, "Ignore List": 193, "XML": 13507, "Starlark": 142, "Kotlin": 6746, "Java": 8085, "Gradle": 2753, "Proguard": 169, "INI": 72, "JSON": 80, "Graphviz (DOT)": 1, "Ant Build System": 2, "Protocol Buffer": 8, "Java Properties": 166, "HTML": 67, "Batchfile": 20, "Gradle Kotlin DSL": 1655, "CMake": 19, "C": 29, "Checksums": 339, "C++": 14, "TOML": 2, "Smali": 5, "SVG": 1329, "AIDL": 9, "JFlex": 8, "Prolog": 6, "QMake": 2, "RenderScript": 1, "NSIS": 4, "GraphQL": 5, "Python": 10, "Makefile": 8, "YAML": 1, "HAProxy": 1, "Org": 2, "JavaScript": 3} | /*
* 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.android.tools.idea.compose.preview.animation
import androidx.compose.animation.tooling.ComposeAnimatedProperty
import androidx.compose.animation.tooling.ComposeAnimation
import androidx.compose.animation.tooling.ComposeAnimationType
import androidx.compose.animation.tooling.TransitionInfo
import com.android.tools.adtui.TabularLayout
import com.android.tools.adtui.actions.DropDownAction
import com.android.tools.adtui.util.ActionToolbarUtil
import com.android.tools.idea.common.surface.DesignSurface
import com.android.tools.idea.common.util.ControllableTicker
import com.android.tools.idea.compose.preview.ComposePreviewBundle.message
import com.android.tools.idea.compose.preview.analytics.AnimationToolingEvent
import com.android.tools.idea.compose.preview.analytics.AnimationToolingUsageTracker
import com.android.tools.idea.compose.preview.animation.AnimationInspectorPanel.TransitionDurationTimeline
import com.android.tools.idea.compose.preview.util.layoutlibSceneManagers
import com.android.tools.idea.flags.StudioFlags.COMPOSE_INTERACTIVE_ANIMATION_CURVES
import com.google.common.annotations.VisibleForTesting
import com.google.common.util.concurrent.MoreExecutors
import com.google.wireless.android.sdk.stats.ComposeAnimationToolingEvent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.ui.AnActionButton
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.tabs.TabInfo
import com.intellij.ui.tabs.TabsListener
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.ui.UIUtil
import icons.StudioIcons
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.MouseEvent
import java.awt.geom.Path2D
import java.time.Duration
import java.util.Dictionary
import java.util.Hashtable
import java.util.concurrent.TimeUnit
import javax.swing.JPanel
import javax.swing.JSlider
import javax.swing.LayoutFocusTraversalPolicy
import javax.swing.border.MatteBorder
import kotlin.math.ceil
import kotlin.math.max
private val LOG = Logger.getInstance(AnimationInspectorPanel::class.java)
/**
* Height of the animation inspector timeline header, i.e. Transition Properties panel title and timeline labels.
*/
private const val TIMELINE_HEADER_HEIGHT = 25
/**
* Height of the animation inspector footer.
*/
private const val TIMELINE_FOOTER_HEIGHT = 20
/**
* Default max duration (ms) of the animation preview when it's not possible to get it from Compose.
*/
private const val DEFAULT_MAX_DURATION_MS = 10000L
/** Height of one row for animation. */
private const val TIMELINE_ROW_HEIGHT = 70
/** Offset between animation curves. */
private const val TIMELINE_CURVE_OFFSET = 45
/** Offset from the top of timeline to the first animation curve. */
private const val TIMELINE_TOP_OFFSET = 20
/** Offset between the curve and the label. */
private const val LABEL_OFFSET = 10
//TODO(b/161344747) This value could be dynamic depending on the curve type.
/** Number of points for one curve. */
private const val DEFAULT_CURVE_POINTS_NUMBER = 200
/**
* Displays details about animations belonging to a Compose Preview. Allows users to see all the properties (e.g. `ColorPropKeys`) being
* animated grouped by animation (e.g. `TransitionAnimation`, `AnimatedValue`). In addition, [TransitionDurationTimeline] is a timeline view
* that can be controlled by scrubbing or through a set of controllers, such as play/pause and jump to end. The [AnimationInspectorPanel]
* therefore allows a detailed inspection of Compose animations.
*/
class AnimationInspectorPanel(internal val surface: DesignSurface) : JPanel(TabularLayout("Fit,*", "Fit,*")), Disposable {
/**
* Animation transition for selected from/to states.
* @param properties - map of properties for this Animation, it maps the index of the property to an [AnimatedProperty].
*/
class Transition(val properties: Map<Int, AnimatedProperty<Double>?> = mutableMapOf()) {
private val numberOfSubcomponents by lazy {
properties.map { it.value?.dimension }.filterNotNull().sum()
}
val transitionTimelineHeight by lazy {
numberOfSubcomponents * TIMELINE_ROW_HEIGHT + TIMELINE_HEADER_HEIGHT + TIMELINE_FOOTER_HEIGHT
}
}
val logger = { type: ComposeAnimationToolingEvent.ComposeAnimationToolingEventType -> logAnimationInspectorEvent(type) }
/**
* Tabs panel where each tab represents a single animation being inspected. All tabs share the same [TransitionDurationTimeline], but have
* their own playback toolbar, from/to state combo boxes and animated properties panel.
*/
@VisibleForTesting
val tabbedPane = AnimationTabs(surface).apply {
addListener(TabChangeListener())
}
private inner class TabChangeListener : TabsListener {
override fun selectionChanged(oldSelection: TabInfo?, newSelection: TabInfo?) {
val tab = tabbedPane.selectedInfo?.component as? AnimationTab ?: return
if (newSelection == oldSelection) return
// Load animation when first tab was just created or transition has changed.
tab.loadTransitionFromCacheOrLib()
tab.updateProperties()
// The following callbacks only need to be called when old selection is not null, which excludes the addition/selection of the first
// tab. In that case, the logic will be handled by updateTransitionStates.
if (oldSelection != null) {
// Swing components cannot be placed into different containers, so we add the shared timeline to the active tab on tab change.
tab.addTimeline()
timeline.selectedTab = tab
// Set the clock time when changing tabs to update the current tab's transition properties panel.
timeline.setClockTime(timeline.cachedVal)
}
}
}
/**
* Maps animation objects to the [AnimationTab] that represents them.
*/
private val animationTabs = HashMap<ComposeAnimation, AnimationTab>()
/**
* [tabbedPane]'s tab titles mapped to the amount of tabs using that title. The count is used to differentiate tabs when there are
* multiple tabs with the same name. For example, we should have "tabTitle", "tabTitle (1)", "tabTitle (2)", etc., instead of multiple
* "tabTitle" tabs.
*/
private val tabNamesCount = HashMap<String, Int>()
/**
* Loading panel displayed when the preview has no animations subscribed.
*/
private val noAnimationsPanel = JBLoadingPanel(BorderLayout(), this).apply {
name = "Loading Animations Panel"
setLoadingText(message("animation.inspector.loading.animations.panel.message"))
}
private val timeline = TransitionDurationTimeline()
private val playPauseAction = PlayPauseAction()
private val timelineSpeedAction = TimelineSpeedAction()
private val timelineLoopAction = TimelineLoopAction()
/**
* Wrapper of the `PreviewAnimationClock` that animations inspected in this panel are subscribed to. Null when there are no animations.
*/
internal var animationClock: AnimationClock? = null
private var maxDurationPerIteration = DEFAULT_MAX_DURATION_MS
/**
* Executor responsible for updating animation states off EDT.
*/
private val updateAnimationStatesExecutor =
if (ApplicationManager.getApplication().isUnitTestMode)
MoreExecutors.directExecutor()
else
AppExecutorUtil.createBoundedApplicationPoolExecutor("Animation States Updater", 1)
init {
name = "Animation Preview"
noAnimationsPanel.startLoading()
add(noAnimationsPanel, TabularLayout.Constraint(1, 0, 2))
}
/**
* Updates the `from` and `to` state combo boxes to display the states of the given animation, and resets the timeline. Invokes a given
* callback once everything is populated.
*/
fun updateTransitionStates(animation: ComposeAnimation, states: Set<Any>, callback: () -> Unit) {
animationTabs[animation]?.let { tab ->
tab.stateComboBox.updateStates(states)
val transition = animation.animationObject
transition::class.java.methods.singleOrNull { it.name == "getCurrentState" }?.let {
it.isAccessible = true
it.invoke(transition)?.let { state ->
tab.stateComboBox.setStartState(state)
}
}
// Call updateAnimationStartAndEndStates directly here to set the initial animation states in PreviewAnimationClock
updateAnimationStatesExecutor.execute {
// Use a longer timeout the first time we're updating the start and end states. Since we're running off EDT, the UI will not freeze.
// This is necessary here because it's the first time the animation mutable states will be written, when setting the clock, and
// read, when getting its duration. These operations take longer than the default 30ms timeout the first time they're executed.
tab.updateAnimationStartAndEndStates(longTimeout = true)
// Set up the combo box listeners so further changes to the selected state will trigger a call to updateAnimationStartAndEndStates.
// Note: this is called only once per tab, in this method, when creating the tab.
tab.stateComboBox.setupListeners()
callback.invoke()
}
}
}
/**
* Updates the combo box that displays the possible states of an `AnimatedVisibility` animation, and resets the timeline. Invokes a given
* callback once the combo box is populated.
*/
fun updateAnimatedVisibilityStates(animation: ComposeAnimation, callback: () -> Unit) {
animationTabs[animation]?.let { tab ->
tab.stateComboBox.updateStates(animation.states)
updateAnimationStatesExecutor.execute {
// Update the animated visibility combo box with the correct initial state, obtained from PreviewAnimationClock.
var state: Any? = null
executeOnRenderThread(useLongTimeout = true) {
val clock = animationClock ?: return@executeOnRenderThread
// AnimatedVisibilityState is an inline class in Compose that maps to a String. Therefore, calling `getAnimatedVisibilityState`
// via reflection will return a String rather than an AnimatedVisibilityState. To work around that, we select the initial combo
// box item by checking the display value.
state = clock.getAnimatedVisibilityStateFunction.invoke(clock.clock, animation)
}
tab.stateComboBox.setStartState(state)
// Use a longer timeout the first time we're updating the AnimatedVisiblity state. Since we're running off EDT, the UI will not
// freeze. This is necessary here because it's the first time the animation mutable states will be written, when setting the clock,
// and read, when getting its duration. These operations take longer than the default 30ms timeout the first time they're executed.
tab.updateAnimatedVisibility(longTimeout = true)
// Set up the combo box listener so further changes to the selected state will trigger a call to updateAnimatedVisibility.
// Note: this is called only once per tab, in this method, when creating the tab.
tab.stateComboBox.setupListeners()
callback.invoke()
}
}
}
/**
* Update the timeline window size, which is usually the duration of the longest animation being tracked. However, repeatable animations
* are handled differently because they can have a large number of iterations resulting in a unrealistic duration. In that case, we take
* the longest iteration instead to represent the window size and set the timeline max loop count to be large enough to display all the
* iterations.
*/
fun updateTimelineWindowSize(longTimeout: Boolean = false) {
val clock = animationClock ?: return
if (!executeOnRenderThread(longTimeout) {
maxDurationPerIteration = clock.getMaxDurationPerIteration.invoke(clock.clock) as Long
}) return
timeline.updateMaxDuration(maxDurationPerIteration)
var maxDuration = DEFAULT_MAX_DURATION_MS
if (!executeOnRenderThread(longTimeout) { maxDuration = clock.getMaxDurationFunction.invoke(clock.clock) as Long }) return
timeline.maxLoopCount = if (maxDuration > maxDurationPerIteration) {
// The max duration is longer than the max duration per iteration. This means that a repeatable animation has multiple iterations,
// so we need to add as many loops to the timeline as necessary to display all the iterations.
ceil(maxDuration / maxDurationPerIteration.toDouble()).toLong()
}
// Otherwise, the max duration fits the window, so we just need one loop that keeps repeating when loop mode is active.
else 1
}
/**
* Remove all tabs from [tabbedPane], replace it with [noAnimationsPanel], and clears the cached animations.
*/
internal fun invalidatePanel() {
tabbedPane.removeAllTabs()
animationTabs.clear()
showNoAnimationsPanel()
}
/**
* Replaces the [tabbedPane] with [noAnimationsPanel].
*/
private fun showNoAnimationsPanel() {
remove(tabbedPane.component)
noAnimationsPanel.startLoading()
add(noAnimationsPanel, TabularLayout.Constraint(1, 0, 2))
// Reset tab names, so when new tabs are added they start as #1
tabNamesCount.clear()
timeline.cachedVal = -1 // Reset the timeline cached value, so when new tabs are added, any new value will trigger an update
// The animation panel might not have the focus when the "No animations" panel is displayed, i.e. when a live literal is changed in the
// editor and we need to refresh the animation preview so it displays the most up-to-date animations. For that reason, we need to make
// sure the animation panel is repainted correctly.
repaint()
playPauseAction.pause()
}
/**
* Adds an [AnimationTab] corresponding to the given [animation] to [tabbedPane].
*/
internal fun addTab(animation: ComposeAnimation) {
val animationTab = animationTabs[animation] ?: return
val isAddingFirstTab = tabbedPane.tabCount == 0
tabbedPane.addTab(TabInfo(animationTab).apply {
text = animationTab.tabTitle
})
if (isAddingFirstTab) {
// There are no tabs and we're about to add one. Replace the placeholder panel with the TabbedPane.
noAnimationsPanel.stopLoading()
remove(noAnimationsPanel)
add(tabbedPane.component, TabularLayout.Constraint(1, 0, 2))
}
}
/**
* Creates an [AnimationTab] corresponding to the given [animation] and add it to the [animationTabs] map.
* Note: this method does not add the tab to [tabbedPane]. For that, [addTab] should be used.
*/
internal fun createTab(animation: ComposeAnimation) {
val tabName = animation.label
?: when (animation.type) {
ComposeAnimationType.ANIMATED_VALUE -> message("animation.inspector.tab.animated.value.default.title")
ComposeAnimationType.ANIMATED_VISIBILITY -> message("animation.inspector.tab.animated.visibility.default.title")
ComposeAnimationType.TRANSITION_ANIMATION -> message("animation.inspector.tab.transition.animation.default.title")
else -> message("animation.inspector.tab.default.title")
}
val count = tabNamesCount.getOrDefault(tabName, 0)
tabNamesCount[tabName] = count + 1
val animationTab = AnimationTab(animation, "$tabName${if (count > 0) " ($count)" else ""}")
if (animationTabs.isEmpty()) {
// We need to make sure the timeline is added to a tab. Since there are no tabs yet, this will be the chosen one.
animationTab.addTimeline()
timeline.selectedTab = animationTab
}
animationTabs[animation] = animationTab
}
/**
* Removes the [AnimationTab] corresponding to the given [animation] from [tabbedPane].
*/
internal fun removeTab(animation: ComposeAnimation) {
tabbedPane.tabs.find { (it.component as? AnimationTab)?.animation === animation }?.let { tabbedPane.removeTab(it) }
animationTabs.remove(animation)
if (tabbedPane.tabCount == 0) {
// There are no more tabs. Replace the TabbedPane with the placeholder panel.
showNoAnimationsPanel()
}
}
override fun dispose() {
playPauseAction.dispose()
animationTabs.clear()
tabNamesCount.clear()
}
private fun logAnimationInspectorEvent(type: ComposeAnimationToolingEvent.ComposeAnimationToolingEventType) {
AnimationToolingUsageTracker.getInstance(surface).logEvent(AnimationToolingEvent(type))
}
/**
* Content of a tab representing an animation. All the elements that aren't shared between tabs and need to be exposed should be defined
* in this class, e.g. from/to state combo boxes.
*/
private inner class AnimationTab(val animation: ComposeAnimation, val tabTitle: String) : JPanel(TabularLayout("Fit,*,Fit", "Fit,*")) {
val stateComboBox: InspectorPainter.StateComboBox
private val timelinePanelWithCurves = JBScrollPane().apply {
border = MatteBorder(1, 1, 0, 0, JBColor.border())
}
private val timelinePanelNoCurves = JPanel(BorderLayout())
private val cachedTransitions: MutableMap<Int, Transition> = mutableMapOf()
private val playbackControls = createPlaybackControllers()
private val playPauseComponent: Component?
get() = playbackControls.component?.components?.elementAtOrNull(2)
init {
add(playbackControls.component, TabularLayout.Constraint(0, 0))
stateComboBox = when (animation.type) {
ComposeAnimationType.TRANSITION_ANIMATION -> InspectorPainter.StartEndComboBox(surface, logger) {
updateAnimationStartAndEndStates()
loadTransitionFromCacheOrLib()
updateProperties()
}
ComposeAnimationType.ANIMATED_VISIBILITY -> InspectorPainter.AnimatedVisibilityComboBox(logger) {
updateAnimatedVisibility()
loadTransitionFromCacheOrLib()
updateProperties()
}
ComposeAnimationType.ANIMATED_VALUE -> InspectorPainter.EmptyComboBox()
}
add(stateComboBox.component, TabularLayout.Constraint(0, 2))
val splitterWrapper = JPanel(BorderLayout())
if (COMPOSE_INTERACTIVE_ANIMATION_CURVES.get())
splitterWrapper.add(timelinePanelWithCurves)
else
splitterWrapper.add(timelinePanelNoCurves, BorderLayout.CENTER)
add(splitterWrapper, TabularLayout.Constraint(1, 0, 3))
isFocusable = false
focusTraversalPolicy = LayoutFocusTraversalPolicy()
}
/**
* Updates the actual animation in Compose to set its start and end states to the ones selected in the respective combo boxes.
*/
fun updateAnimationStartAndEndStates(longTimeout: Boolean = false) {
val clock = animationClock ?: return
val startState = stateComboBox.getState(0)
val toState = stateComboBox.getState(1)
if (!executeOnRenderThread(longTimeout) {
clock.updateFromAndToStatesFunction.invoke(clock.clock, animation, startState, toState)
}) return
resetTimelineAndUpdateWindowSize(longTimeout)
}
/**
* Updates the actual animation in Compose to set its start and end states based on the selected value of [animatedVisibilityComboBox].
*/
fun updateAnimatedVisibility(longTimeout: Boolean = false) {
val clock = animationClock ?: return
if (!executeOnRenderThread(longTimeout) {
clock.updateAnimatedVisibilityStateFunction.invoke(clock.clock, animation, stateComboBox.getState())
}) return
resetTimelineAndUpdateWindowSize(longTimeout)
}
private fun resetTimelineAndUpdateWindowSize(longTimeout: Boolean) {
// Set the timeline to 0
timeline.setClockTime(0, longTimeout)
updateTimelineWindowSize(longTimeout)
// Update the cached value manually to prevent the timeline to set the clock time to 0 using the short timeout.
timeline.cachedVal = 0
// Move the timeline slider to 0.
UIUtil.invokeLaterIfNeeded { timeline.jumpToStart() }
}
/**
* Load transition for current start and end state. If transition was loaded before, the cached result is used.
*/
fun loadTransitionFromCacheOrLib(longTimeout: Boolean = false) {
if (!COMPOSE_INTERACTIVE_ANIMATION_CURVES.get()) return
val stateHash = stateComboBox.stateHashCode()
cachedTransitions[stateHash]?.let {
timeline.updateTransition(cachedTransitions[stateHash]!!)
timelinePanelWithCurves.doLayout()
return@loadTransitionFromCacheOrLib
}
val clock = animationClock ?: return
executeOnRenderThread(longTimeout) {
val transition = loadTransitionsFromLib(clock)
cachedTransitions[stateHash] = transition
timeline.updateTransition(transition)
timelinePanelWithCurves.doLayout()
}
}
private fun loadTransitionsFromLib(clock: AnimationClock): Transition {
val builders: MutableMap<Int, AnimatedProperty.Builder> = mutableMapOf()
val clockTimeMsStep = max(1, maxDurationPerIteration / DEFAULT_CURVE_POINTS_NUMBER)
fun getTransitions() {
val composeTransitions = clock.getTransitionsFunction?.invoke(clock.clock, animation, clockTimeMsStep) as List<TransitionInfo>
for ((index, composeTransition) in composeTransitions.withIndex()) {
val builder = AnimatedProperty.Builder()
.setStartTimeMs(composeTransition.startTimeMillis.toInt())
.setEndTimeMs(composeTransition.endTimeMillis.toInt())
composeTransition.values.mapValues {
ComposeUnit.parseValue(it.value)
}.forEach { (ms, unit) ->
unit?.let {
builder.add(ms.toInt(), unit)
}
}
builders[index] = builder
}
}
fun getAnimatedProperties() {
for (clockTimeMs in 0..maxDurationPerIteration step clockTimeMsStep) {
clock.setClockTimeFunction.invoke(clock.clock, clockTimeMs)
val properties = clock.getAnimatedPropertiesFunction.invoke(clock.clock, animation) as List<ComposeAnimatedProperty>
for ((index, property) in properties.withIndex()) {
ComposeUnit.parse(property)?.let { unit ->
builders.getOrPut(index) { AnimatedProperty.Builder() }.add(clockTimeMs.toInt(), unit)
}
}
}
}
try {
if (clock.getTransitionsFunction != null) getTransitions()
else getAnimatedProperties()
}
catch (e: Exception) {
LOG.warn("Failed to load the Compose Animation properties", e)
}
builders.mapValues { it.value.build() }.let {
return Transition(it)
}
}
/**
* Create a toolbar panel with actions to control the animation, e.g. play, pause and jump to start/end.
*
* TODO(b/157895086): Update action icons when we have the final Compose Animation tooling icons
* TODO(b/157895086): Disable toolbar actions while build is in progress
*/
private fun createPlaybackControllers() = ActionManager.getInstance().createActionToolbar(
"Animation Preview",
DefaultActionGroup(listOf(
timelineLoopAction,
GoToStartAction(),
playPauseAction,
GoToEndAction(),
timelineSpeedAction
)),
true).apply {
setTargetComponent(surface)
ActionToolbarUtil.makeToolbarNavigable(this)
}
/**
* Adds [timeline] to this tab's [timelinePanel]. The timeline is shared across all tabs, and a Swing component can't be added as a
* child of multiple components simultaneously. Therefore, this method needs to be called everytime we change tabs.
*/
fun addTimeline() {
if (COMPOSE_INTERACTIVE_ANIMATION_CURVES.get()) {
timelinePanelWithCurves.setViewportView(timeline)
timelinePanelWithCurves.doLayout()
}
else timelinePanelNoCurves.add(timeline)
}
fun updateProperties() {
val animClock = animationClock ?: return
if (!COMPOSE_INTERACTIVE_ANIMATION_CURVES.get()) return
try {
val properties = animClock.getAnimatedPropertiesFunction.invoke(animClock.clock, animation) as List<ComposeAnimatedProperty>
timeline.updateSelectedProperties(properties.map { ComposeUnit.TimelineUnit(it, ComposeUnit.parse(it)) })
}
catch (e: Exception) {
LOG.warn("Failed to get the Compose Animation properties", e)
}
}
/**
* Snap the animation to the start state.
*/
private inner class GoToStartAction
: AnActionButton(message("animation.inspector.action.go.to.start"), StudioIcons.LayoutEditor.Motion.GO_TO_START) {
override fun actionPerformed(e: AnActionEvent) {
timeline.jumpToStart()
logAnimationInspectorEvent(ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.TRIGGER_JUMP_TO_START_ACTION)
// Switch focus to Play button if animation is not playing at the moment.
// If animation is playing - no need to switch focus as GoToStart button will be enabled again.
if (!playPauseAction.isPlaying)
playPauseComponent?.requestFocus()
}
override fun updateButton(e: AnActionEvent) {
super.updateButton(e)
e.presentation.isEnabled = !timeline.isAtStart()
}
}
/**
* Snap the animation to the end state.
*/
private inner class GoToEndAction
: AnActionButton(message("animation.inspector.action.go.to.end"), StudioIcons.LayoutEditor.Motion.GO_TO_END) {
override fun actionPerformed(e: AnActionEvent) {
timeline.jumpToEnd()
logAnimationInspectorEvent(ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.TRIGGER_JUMP_TO_END_ACTION)
// Switch focus to Play button if animation is not playing in the loop at the moment.
// If animation is playing in the loop - no need to switch focus as GoToEnd button will be enabled again.
if (!playPauseAction.isPlaying || !timeline.playInLoop)
playPauseComponent?.requestFocus()
}
override fun updateButton(e: AnActionEvent) {
super.updateButton(e)
e.presentation.isEnabled = !timeline.isAtEnd()
}
}
}
/**
* Action to play and pause the animation. The icon and tooltip gets updated depending on the playing state.
*/
private inner class PlayPauseAction : AnActionButton(message("animation.inspector.action.play"), StudioIcons.LayoutEditor.Motion.PLAY) {
private val tickPeriod = Duration.ofMillis(30)
/**
* Ticker that increment the animation timeline while it's playing.
*/
private val ticker =
ControllableTicker({
if (isPlaying) {
UIUtil.invokeLaterIfNeeded { timeline.incrementClockBy(tickPeriod.toMillis().toInt()) }
if (timeline.isAtEnd()) {
if (timeline.playInLoop) {
handleLoopEnd()
}
else {
pause()
}
}
}
}, tickPeriod)
var isPlaying = false
private set
override fun actionPerformed(e: AnActionEvent) = if (isPlaying) {
pause()
logAnimationInspectorEvent(ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.TRIGGER_PAUSE_ACTION)
}
else {
play()
logAnimationInspectorEvent(ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.TRIGGER_PLAY_ACTION)
}
override fun updateButton(e: AnActionEvent) {
super.updateButton(e)
e.presentation.isEnabled = true
e.presentation.apply {
if (isPlaying) {
icon = StudioIcons.LayoutEditor.Motion.PAUSE
text = message("animation.inspector.action.pause")
}
else {
icon = StudioIcons.LayoutEditor.Motion.PLAY
text = message("animation.inspector.action.play")
}
}
}
private fun play() {
if (timeline.isAtEnd()) {
// If playing after reaching the timeline end, we should go back to start so the animation can be actually played.
timeline.jumpToStart()
}
isPlaying = true
ticker.start()
}
fun pause() {
isPlaying = false
ticker.stop()
}
private fun handleLoopEnd() {
UIUtil.invokeLaterIfNeeded { timeline.jumpToStart() }
timeline.loopCount++
if (timeline.loopCount == timeline.maxLoopCount) {
timeline.loopCount = 0
}
}
fun dispose() {
ticker.dispose()
}
}
private enum class TimelineSpeed(val speedMultiplier: Float, val displayText: String) {
X_0_1(0.1f, "0.1x"),
X_0_25(0.25f, "0.25x"),
X_0_5(0.5f, "0.5x"),
X_0_75(0.75f, "0.75x"),
X_1(1f, "1x"),
X_2(2f, "2x")
}
/**
* Action to speed up or slow down the timeline. The clock runs faster/slower depending on the value selected.
*
* TODO(b/157895086): Add a proper icon for the action.
*/
private inner class TimelineSpeedAction : DropDownAction(message("animation.inspector.action.speed"),
message("animation.inspector.action.speed"),
null) {
init {
enumValues<TimelineSpeed>().forEach { addAction(SpeedAction(it)) }
}
override fun update(e: AnActionEvent) {
e.presentation.text = timeline.speed.displayText
}
override fun displayTextInToolbar() = true
private inner class SpeedAction(private val speed: TimelineSpeed) : ToggleAction("${speed.displayText}", "${speed.displayText}", null) {
override fun isSelected(e: AnActionEvent) = timeline.speed == speed
override fun setSelected(e: AnActionEvent, state: Boolean) {
timeline.speed = speed
val changeSpeedEvent = AnimationToolingEvent(ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.CHANGE_ANIMATION_SPEED)
.withAnimationMultiplier(speed.speedMultiplier)
AnimationToolingUsageTracker.getInstance(surface).logEvent(changeSpeedEvent)
}
}
}
/**
* Action to keep the timeline playing in loop. When active, the timeline will keep playing indefinitely instead of stopping at the end.
* When reaching the end of the window, the timeline will increment the loop count until it reaches its limit. When that happens, the
* timelines jumps back to start.
*
* TODO(b/157895086): Add a proper icon for the action.
*/
private inner class TimelineLoopAction : ToggleAction(message("animation.inspector.action.loop"),
message("animation.inspector.action.loop"),
StudioIcons.LayoutEditor.Motion.LOOP) {
override fun isSelected(e: AnActionEvent) = timeline.playInLoop
override fun setSelected(e: AnActionEvent, state: Boolean) {
timeline.playInLoop = state
if (!state) {
// Reset the loop when leaving playInLoop mode.
timeline.loopCount = 0
}
logAnimationInspectorEvent(
if (state) ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.ENABLE_LOOP_ACTION
else ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.DISABLE_LOOP_ACTION
)
}
}
/**
* Timeline panel ranging from 0 to the max duration (in ms) of the animations being inspected, listing all the animations and their
* corresponding range as well. The timeline should respond to mouse commands, allowing users to jump to specific points, scrub it, etc.
*/
private inner class TransitionDurationTimeline : JPanel(BorderLayout()) {
var selectedTab: AnimationTab? = null
var cachedVal = -1
/**
* Speed multiplier of the timeline clock. [TimelineSpeed.X_1] by default (normal speed).
*/
var speed: TimelineSpeed = TimelineSpeed.X_1
/**
* Whether the timeline should play in loop or stop when reaching the end.
*/
var playInLoop = false
/**
* 0-based count representing the current loop the timeline is in. This should be used as a multiplier of the |windowSize| (slider
* maximum) offset applied when setting the clock time.
*/
var loopCount = 0L
/**
* The maximum amount of loops the timeline has. When [loopCount] reaches this value, it needs to be reset.
*/
var maxLoopCount = 1L
override fun getPreferredSize(): Dimension {
return Dimension(width - 50, transition.transitionTimelineHeight)
}
private val slider = object : JSlider(0, DEFAULT_MAX_DURATION_MS.toInt(), 0) {
private var cachedSliderWidth = 0
private var cachedMax = 0
override fun updateUI() {
setUI(TimelineSliderUI(this))
updateLabelUIs()
}
override fun setMaximum(maximum: Int) {
super.setMaximum(maximum)
updateMajorTicks()
}
fun updateMajorTicks() {
if (width == cachedSliderWidth && maximum == cachedMax) return
cachedSliderWidth = width
cachedMax = maximum
val tickIncrement = InspectorPainter.Slider.getTickIncrement(this)
// First, calculate where the labels are going to be painted, based on the maximum. We won't paint the major ticks themselves, as
// minor ticks will be painted instead. The major ticks spacing is only set so the labels are painted in the right place.
setMajorTickSpacing(tickIncrement)
// Now, add the "ms" suffix to each label.
labelTable = if (tickIncrement == 0) {
// Handle the special case where maximum == 0 and we only have the "0ms" label.
createMsLabelTable(labelTable)
}
else {
createMsLabelTable(createStandardLabels(tickIncrement))
}
}
}.apply {
paintTicks = false
paintLabels = true
updateMajorTicks()
setUI(TimelineSliderUI(this))
addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) = updateMajorTicks()
})
}
init {
add(slider, BorderLayout.CENTER)
slider.addChangeListener {
if (slider.value == cachedVal) return@addChangeListener // Ignore repeated values
val newValue = slider.value
cachedVal = newValue
setClockTime(newValue)
}
}
var transition = Transition()
/**
* List of [ComposeUnit.TimelineUnit] for the clockTime set in [AnimationClock].
* Corresponds to the selected time in the timeline.
*/
var selectedProperties: List<ComposeUnit.TimelineUnit> = mutableListOf()
/**
* Update currently selected transition.
*/
fun updateTransition(newTransition: Transition) {
transition = newTransition
preferredSize = Dimension(width - 50, transition.transitionTimelineHeight)
repaint()
}
/**
* Update currently selected properties in the timeline.
*/
fun updateSelectedProperties(animatedPropKeys: List<ComposeUnit.TimelineUnit>) {
selectedProperties = animatedPropKeys
}
fun updateMaxDuration(durationMs: Long) {
slider.maximum = durationMs.toInt()
}
fun setClockTime(newValue: Int, longTimeout: Boolean = false) {
val clock = animationClock ?: return
val tab = selectedTab ?: return
var clockTimeMs = newValue.toLong()
if (playInLoop) {
// When playing in loop, we need to add an offset to slide the window and take repeatable animations into account when necessary
clockTimeMs += slider.maximum * loopCount
}
if (!executeOnRenderThread(longTimeout) { clock.setClockTimeFunction.invoke(clock.clock, clockTimeMs) }) return
tab.updateProperties()
}
/**
* Increments the clock by the given value, taking the current [speed] into account.
*/
fun incrementClockBy(increment: Int) {
slider.value += (increment * speed.speedMultiplier).toInt()
}
fun jumpToStart() {
slider.value = 0
}
fun jumpToEnd() {
slider.value = slider.maximum
}
fun isAtStart() = slider.value == 0
fun isAtEnd() = slider.value == slider.maximum
/**
* Rewrite the labels by adding a `ms` suffix indicating the values are in milliseconds.
*/
private fun createMsLabelTable(table: Dictionary<*, *>): Hashtable<Any, JBLabel> {
val keys = table.keys()
val labelTable = Hashtable<Any, JBLabel>()
while (keys.hasMoreElements()) {
val key = keys.nextElement()
labelTable[key] = object : JBLabel("$key ms") {
// Setting the enabled property to false is not enough because BasicSliderUI will check if the slider itself is enabled when
// painting the labels and set the label enable status to match the slider's. Thus, we force the label color to the disabled one.
override fun getForeground() = UIUtil.getLabelDisabledForeground()
}
}
return labelTable
}
/**
* Modified [JSlider] UI to simulate a timeline-like view. In general lines, the following modifications are made:
* * The horizontal track is hidden, so only the vertical thumb is shown
* * The vertical thumb is a vertical line that matches the parent height
* * The tick lines also match the parent height
*/
private inner class TimelineSliderUI(slider: JSlider) : TimelinePanel(slider) {
fun createCurveInfo(animation: AnimatedProperty<Double>, componentId: Int, minY: Int, maxY: Int): InspectorPainter.CurveInfo =
animation.components[componentId].let { component ->
val curve: Path2D = Path2D.Double()
val animationYMin = component.minValue
val isZeroDuration = animation.endMs == animation.startMs
val zeroDurationXOffset = if (isZeroDuration) 1 else 0
val minX = xPositionForValue(animation.startMs)
val maxX = xPositionForValue(animation.endMs)
val stepY = (maxY - minY) / (component.maxValue - animationYMin)
curve.moveTo(minX.toDouble() - zeroDurationXOffset, maxY.toDouble())
if (isZeroDuration) {
// If animation duration is zero, for example for snap animation - draw a vertical line,
// It gives a visual feedback what animation is happened at that point and what graph is not missing where.
curve.lineTo(minX.toDouble() - zeroDurationXOffset, minY.toDouble())
curve.lineTo(maxX.toDouble() + zeroDurationXOffset, minY.toDouble())
}
else {
component.points.forEach { (ms, value) ->
curve.lineTo(xPositionForValue(ms).toDouble(), maxY - (value.toDouble() - animationYMin) * stepY)
}
}
curve.lineTo(maxX.toDouble() + zeroDurationXOffset, maxY.toDouble())
curve.lineTo(minX.toDouble() - zeroDurationXOffset, maxY.toDouble())
return InspectorPainter.CurveInfo(minX = minX, maxX = maxX, y = maxY, curve = curve, linkedToNextCurve = component.linkToNext)
}
override fun paintTrack(g: Graphics) {
super.paintTrack(g)
g as Graphics2D
// Leave the track empty if feature is not enabled
if (!COMPOSE_INTERACTIVE_ANIMATION_CURVES.get()) return
if (selectedProperties.isEmpty()) return
var rowIndex = 0
for ((index, animation) in transition.properties) {
if (animation == null) continue
for (componentId in 0 until animation.dimension) {
val minY = TIMELINE_HEADER_HEIGHT - 1 + TIMELINE_ROW_HEIGHT * rowIndex + TIMELINE_TOP_OFFSET
val maxY = minY + TIMELINE_ROW_HEIGHT
val curveInfo = createCurveInfo(animation, componentId, minY, (maxY - TIMELINE_CURVE_OFFSET))
InspectorPainter.paintCurve(g, curveInfo, index, TIMELINE_ROW_HEIGHT)
if (selectedProperties.size > index) {
InspectorPainter.BoxedLabel.paintBoxedLabel(g, selectedProperties[index], componentId, animation.grouped,
xPositionForValue(animation.startMs),
maxY - TIMELINE_CURVE_OFFSET + LABEL_OFFSET)
}
rowIndex++
}
}
return
}
override fun createTrackListener(slider: JSlider) = TimelineTrackListener()
/**
* [Tracklistener] to allow setting [slider] value when clicking and scrubbing the timeline.
*/
private inner class TimelineTrackListener : TrackListener() {
private var isDragging = false
override fun mousePressed(e: MouseEvent) {
// We override the parent class behavior completely because it executes more operations than we need, being less performant than
// this method. Since it recalculates the geometry of all components, the resulting UI on mouse press is not what we aim for.
currentMouseX = e.getX()
updateThumbLocationAndSliderValue()
timeline.requestFocus() // Request focus to the timeline, so the selected tab actually gets the focus
}
override fun mouseDragged(e: MouseEvent) {
super.mouseDragged(e)
updateThumbLocationAndSliderValue()
isDragging = true
}
override fun mouseReleased(e: MouseEvent?) {
super.mouseReleased(e)
logAnimationInspectorEvent(
if (isDragging) ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.DRAG_ANIMATION_INSPECTOR_TIMELINE
else ComposeAnimationToolingEvent.ComposeAnimationToolingEventType.CLICK_ANIMATION_INSPECTOR_TIMELINE
)
isDragging = false
}
fun updateThumbLocationAndSliderValue() {
val halfWidth = thumbRect.width / 2
// Make sure the thumb X coordinate is within the slider's min and max. Also, subtract half of the width so the center is aligned.
val thumbX = Math.min(Math.max(currentMouseX, xPositionForValue(slider.minimum)), xPositionForValue(slider.maximum)) - halfWidth
setThumbLocation(thumbX, thumbRect.y)
slider.value = valueForXPosition(currentMouseX)
}
}
}
}
private fun executeOnRenderThread(useLongTimeout: Boolean, callback: () -> Unit): Boolean {
val (time, timeUnit) = if (useLongTimeout) {
// Make sure we don't block the UI thread when setting a large timeout
ApplicationManager.getApplication().assertIsNonDispatchThread()
5L to TimeUnit.SECONDS
}
else {
30L to TimeUnit.MILLISECONDS
}
return surface.layoutlibSceneManagers.singleOrNull()?.executeCallbacksAndRequestRender(time, timeUnit) {
callback()
} ?: false
}
} | 0 | null | 0 | 0 | b373163869f676145341d60985cdbdaca3565c0b | 44,086 | android_74FW | Apache License 2.0 |
m2-h1/src/test/kotlin/ru/yegorpilipenko/otus/spring/m2h1/controller/BookControllerTest.kt | nao4j | 158,942,958 | false | {"Java": 372709, "Kotlin": 153881, "HTML": 56806, "Dockerfile": 710} | package ru.yegorpilipenko.otus.spring.m2h1.controller
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.WithAssertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import ru.yegorpilipenko.otus.spring.m2h1.entity.Author
import ru.yegorpilipenko.otus.spring.m2h1.entity.Book
import ru.yegorpilipenko.otus.spring.m2h1.entity.BookComment
import ru.yegorpilipenko.otus.spring.m2h1.entity.Genre
import ru.yegorpilipenko.otus.spring.m2h1.service.BookService
import java.io.ByteArrayInputStream
import java.util.Scanner
@ExtendWith(MockitoExtension::class)
class BookControllerTest : WithAssertions {
@Mock
lateinit var bookService: BookService
lateinit var scanner: Scanner
lateinit var controller: BookController
@BeforeEach
fun setup() {
scanner = Scanner(ByteArrayInputStream("""
2 3
4 5
""".trimIndent().toByteArray()))
controller = BookController(bookService, scanner)
}
@Nested
inner class BooksTest {
@Test
fun shouldPassForMoreBooks() {
doReturn(listOf(Book(1, "b1"), Book(2, "b2"))).whenever(bookService).findAll()
assertThat(controller.books()).containsExactlyInAnyOrder("1: b1", "2: b2")
}
@Test
fun shouldPassWithoutBooks() {
doReturn(emptyList<Book>()).whenever(bookService).findAll()
assertThat(controller.books()).isEmpty()
}
}
@Nested
inner class BookTest {
@Test
fun shouldPassForExistsBook() {
val id = 1L
val author = Author(2, "af", "al")
val genre = Genre(3, "g")
val comment = BookComment(4, id, "[email protected]", "text")
doReturn(Book(id, "b", listOf(author), listOf(genre), listOf(comment))).whenever(bookService).findById(id)
assertThat(controller.book(id)).isEqualTo("""
1: b
Авторы:
2: af al
Жанры:
3: g
Комментарии:
4: [email protected]
text
""".trimIndent())
}
@Test
fun shouldPassForExistsShortBook() {
val id = 1L
doReturn(Book(id, "b", emptyList(), emptyList(), emptyList())).whenever(bookService).findById(id)
assertThat(controller.book(id)).isEqualTo("1: b")
}
@Test
fun shouldPassForNotExistsBook() {
val id = 1L
doReturn(null).whenever(bookService).findById(id)
assertThat(controller.book(id)).isEqualTo("Not found")
}
}
@Nested
inner class BookSaveTest {
@Test
fun shouldPassForSaveFullBook() {
doReturn(Book(
1,
"b",
listOf(Author(2, "af1", "al1"), Author(3, "af2", "al2")),
listOf(Genre(4, "g1"), Genre(5, "g2")),
emptyList()
)).whenever(bookService).save(any(), any(), any())
assertThat(controller.bookSave("b")).isEqualTo("""
1: b
Авторы:
2: af1 al1
3: af2 al2
Жанры:
4: g1
5: g2
""".trimIndent())
verify(bookService).save("b", listOf(2L, 3L), listOf(4L, 5L))
}
}
@Nested
inner class BookRemoveTest {
@Test
fun shouldPassForExistsBook() {
val id = 1L
doReturn(true).whenever(bookService).removeById(id)
assertThat(controller.bookRemove(id)).isEqualTo("Removed")
}
@Test
fun shouldPassForNotExistsBook() {
val id = 1L
doReturn(false).whenever(bookService).removeById(id)
assertThat(controller.bookRemove(id)).isEqualTo("Not found")
}
}
}
| 1 | null | 1 | 1 | a3074a5e1d999a64703dd644df9a354d15ad531b | 4,213 | spring-otus | MIT License |
app/src/main/java/com/bitwindow/aacpaginginfinitescrollingwithnetworksample/repository/MovieRepository.kt | asheshb | 150,709,173 | false | {"Gradle": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Text": 1, "INI": 1, "Proguard": 1, "Kotlin": 20, "XML": 13, "Java": 1} | package com.bitwindow.aacpaginginfinitescrollingwithnetworksample.repository
import android.arch.paging.DataSource
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.data.database.MovieDao
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.data.vo.ErrorCode
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.data.vo.LoadingStatus
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.data.vo.Movie
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.network.TmdbService
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.utility.AppExecutors
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.utility.Util
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
import java.util.*
class MovieRepository private constructor(
private val appExecutors: AppExecutors,
private val movieDao: MovieDao,
private val tmdbService: TmdbService
) {
private var loading = false
companion object {
@Volatile
private var INSTANCE: MovieRepository? = null
fun getInstance(
appExecutors: AppExecutors,
movieDao: MovieDao,
tmdbService: TmdbService
): MovieRepository =
INSTANCE ?: synchronized(this) {
INSTANCE ?: (MovieRepository(appExecutors, movieDao, tmdbService)).also {
INSTANCE = it
}
}
}
fun getMovieDataSourceFactory(): DataSource.Factory<Int, Movie> {
return movieDao.loadMovies()
}
fun fetchMore(fetchDate: Date, loadingStatusListener: (LoadingStatus) -> Unit) {
loadingStatusListener(LoadingStatus.loading())
if (loading) {
Timber.d("fetchMore already loading %s", fetchDate)
return
}
val dateDiff = Util.dateDiff(fetchDate, Date())
if (dateDiff > 0) {
loadingStatusListener(LoadingStatus.success())
Timber.d("fetchMore future date %s", fetchDate)
return
}
loading = true
Timber.d("fetchMore starting: %s", fetchDate)
fetchItems(fetchDate, loadingStatusListener)
}
private fun fetchItems(fetchDate: Date, loadingStatusListener: (LoadingStatus) -> Unit) {
val call = tmdbService.getMovies(Util.getSimpleDate(fetchDate))
call.enqueue(object : Callback<List<Movie>?> {
override fun onResponse(call: Call<List<Movie>?>?, response: Response<List<Movie>?>?) {
if (response != null) {
if (response.body()?.size == 0 && Util.dateDiff(fetchDate, Date()) < 0) {
loadingStatusListener(LoadingStatus.error(ErrorCode.NO_DATA))
} else {
appExecutors.diskIO().execute {
response.body()?.let {
movieDao.insertMovies(it.filter { m -> m.posterPath != null })
Timber.d("fetchMore saved: %s", fetchDate)
}
}
loadingStatusListener(LoadingStatus.success())
}
}
loading = false
}
override fun onFailure(call: Call<List<Movie>?>?, t: Throwable?) {
if (t is IOException) {
loadingStatusListener(LoadingStatus.error(ErrorCode.NETWORK_ERROR, t.message))
} else {
loadingStatusListener(LoadingStatus.error(ErrorCode.UNKNOWN_ERROR, null))
}
loading = false
}
})
}
}
| 0 | Kotlin | 18 | 75 | 8f49aa7338bf5899d07a65dfeea1ad933a089bb9 | 3,739 | AACPagingInfiniteScrollingWithNetworkSample | Apache License 2.0 |
app/src/main/java/com/ly/wvp/record/CloudRecordListViewModel.kt | orchingly | 712,343,355 | false | {"Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 61, "XML": 91, "Java": 34} | package com.ly.wvp.record
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.ly.wvp.auth.HttpConnectionClient
import com.ly.wvp.auth.NetError
import com.ly.wvp.auth.NetError.Companion.OK
import com.ly.wvp.auth.ResponseBody
import com.ly.wvp.auth.ServerUrl
import com.ly.wvp.data.model.LoadDeviceChannel
import com.ly.wvp.data.model.MediaServerItem
import com.ly.wvp.data.model.PageInfo
import com.ly.wvp.data.storage.SettingsConfig
import com.ly.wvp.util.JsonParseUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Request
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
/**
*
* 请求app+stream录像列表
* "http://localhost:18080/record_proxy/FQ3TF8yT83wh5Wvz/api/record/list?page=1&count=15"
*
* 请求server列表
* /record_proxy/FQ3TF8yT83wh5Wvz/api/record/date/list
*
*/
class CloudRecordListViewModel : ViewModel() {
companion object{
private const val TAG = "CloudRecordListViewModel"
}
private var _mediaServerList = MutableLiveData<List<MediaServerItem>>()
private var _cloudRecordPageInfo = MutableLiveData<PageInfo<Map<String, String>>>()
private var _netError = MutableLiveData<NetError>()
private var config: SettingsConfig? = null
fun getMediaServerLiveData(): LiveData<List<MediaServerItem>> = _mediaServerList
fun getCloudRecordPageInfo(): LiveData<PageInfo<Map<String, String>>> = _cloudRecordPageInfo
fun getError(): LiveData<NetError> = _netError
fun setConfig(config: SettingsConfig){
this.config = config
}
fun requestCloudRecord(mediaServerId: String){
val page = "1"
val count = "15"
CoroutineScope(Dispatchers.IO).launch {
try {
val recordInfo = loadCloudRecordForServerPage(mediaServerId, page, count)
launch(Dispatchers.Main){
_cloudRecordPageInfo.value = recordInfo
}
}
catch (e: IOException){
Log.w(TAG, "requestCloudRecord: error ${e.message}" )
_netError.postValue( NetError(NetError.APP_ERROR, e.message?:"IOException"))
}
catch (e: IllegalStateException){
_netError.postValue(NetError(NetError.APP_ERROR, e.message?:"IllegalStateException"))
}
catch (e: Exception){
_netError.postValue(NetError(NetError.INTERNET_INVALID, e.message?:"Exception"))
}
}
}
private fun loadCloudRecordForServerPage(mediaServerId: String, page: String, count: String): PageInfo<Map<String, String>>{
val httpUrl = HttpConnectionClient.buildPublicHeader(config!!)
.addPathSegments(ServerUrl.CLOUD_PROXY)
.addPathSegment(mediaServerId)
.addPathSegments(ServerUrl.API_RECORD)
.addPathSegment(ServerUrl.LIST)
.addQueryParameter(ServerUrl.PARAM_KEY_PAGE, page)
.addQueryParameter(ServerUrl.PARAM_KEY_COUNT, count)
.build()
val request = Request.Builder()
.url(httpUrl)
.get()
.build()
HttpConnectionClient.request(request).run {
this.body?.let {
try {
val jsonObj = JSONObject(it.string())
val code = jsonObj.getInt(ResponseBody.CODE)
val msg = jsonObj.getString(ResponseBody.MSG)
when (code){
0 -> {
return JsonParseUtil.parseCloudRecordList(jsonObj)
}
else ->{
_netError.postValue(NetError(code, msg))
}
}
}
catch (e: JSONException){
//wvp-assist未启动/未配置返回结果为空状态200
if (this.code == OK && it.string().isEmpty()){
_netError.postValue(NetError(NetError.JSON_ERROR, "请检查wvp-assist"))
}
else{
_netError.postValue(NetError(NetError.JSON_ERROR, e.message ?: "JSONException"))
}
}
catch (e: Exception){
_netError.postValue(NetError(NetError.OTHER_EXCEPTION, e.message ?: "Exception"))
}
} ?: kotlin.run {
_netError.postValue(NetError(NetError.OTHER_EXCEPTION, "Http response body is null"))
}
}
return PageInfo()
}
fun requestRemoteMediaServer(){
CoroutineScope(Dispatchers.IO).launch {
try {
val serverList = loadMediaServer()
launch(Dispatchers.Main){
_mediaServerList.value = serverList
}
}
catch (e: IOException){
Log.w(TAG, "requestRemoteMediaServer: error ${e.message}" )
_netError.postValue( NetError(NetError.APP_ERROR, e.message?:"IOException"))
}
catch (e: IllegalStateException){
_netError.postValue(NetError(NetError.APP_ERROR, e.message?:"IllegalStateException"))
}
catch (e: Exception){
_netError.postValue(NetError(NetError.INTERNET_INVALID, e.message?:"Exception"))
}
}
}
private fun loadMediaServer(): ArrayList<MediaServerItem>{
val httpUrl = HttpConnectionClient.buildPublicHeader(config!!)
.addPathSegments(ServerUrl.API_SERVER)
.addPathSegments(ServerUrl.MEDIA_ONLINE)
.build()
val request = Request.Builder()
.url(httpUrl)
.get()
.build()
HttpConnectionClient.request(request).run {
this.body?.let {
try {
val jsonObj = JSONObject(it.string())
val code = jsonObj.getInt(ResponseBody.CODE)
val msg = jsonObj.getString(ResponseBody.MSG)
when (code){
0 -> {
return JsonParseUtil.parseMediaServerList(jsonObj)
}
else ->{
_netError.postValue(NetError(code, msg))
}
}
}
catch (e: JSONException){
_netError.postValue(NetError(NetError.JSON_ERROR, e.message ?: "JSONException"))
}
catch (e: Exception){
_netError.postValue(NetError(NetError.OTHER_EXCEPTION, e.message ?: "Exception"))
}
} ?: kotlin.run {
_netError.postValue(NetError(NetError.OTHER_EXCEPTION, "Http response body is null"))
}
}
return ArrayList()
}
} | 0 | Java | 2 | 6 | 4e901264076aad188b00e524bd69db5a8f432c18 | 7,029 | wvp-android | MIT License |
transektcount/src/main/java/com/wmstein/transektcount/DummyActivity.kt | wistein | 54,684,722 | false | {"Gradle": 3, "Java Properties": 2, "Text": 43, "Markdown": 4, "Proguard": 1, "XML": 77, "Java": 8, "Kotlin": 53, "SQL": 8} | /*
* Copyright (c) 2016 - 2023. <NAME>, Bonn, Germany.
*/
package com.wmstein.transektcount
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
/*************************************************************************************
* Dummy activity to overcome Spinner deficiency
* Re-initializes Spinner to work as expected when repeatedly used in CountingActivity
* Created by wmstein on 2016-12-28,
* last edited in Java on 2022-04-30,
* converted to Kotlin on 2023-07-01,
* last edited on 2023-12-08
*/
class DummyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// get values from calling activity
var autoSection = false
val extras = intent.extras
if (extras != null)
autoSection = extras.getBoolean("auto_section")
if (MyDebug.LOG)
Log.d(TAG, "30, Dummy")
// recall CountingActivity(A) with variable autoSection from Extras
val intent: Intent = if (autoSection)
Intent(this@DummyActivity, CountingActivityA::class.java)
else
Intent(this@DummyActivity, CountingActivity::class.java)
startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
exit()
}
private fun exit() {
super.finish()
}
companion object {
private const val TAG = "DummyAct"
}
}
| 0 | Java | 2 | 5 | 98247ec88090e1fcefba1052aea99773a2db7ce6 | 1,496 | TransektCount_1.2.1 | Apache License 2.0 |
carddrawer/src/test/java/com/meli/android/carddrawer/model/LabelTest.kt | mercadolibre | 188,052,798 | false | {"Gradle": 7, "YAML": 3, "Markdown": 2, "Text": 2, "Java Properties": 1, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "INI": 2, "Proguard": 2, "Kotlin": 96, "XML": 83, "Java": 29} | package com.meli.android.carddrawer.model
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class LabelTest {
private lateinit var label: Label
private val text by lazy { "test" }
private val backgroundColor by lazy { "#FFFFFF" }
private val color by lazy { "#000000" }
private val weight by lazy { "200" }
private val animate by lazy { true }
@Before
fun setUp() {
label = returnLabel()
}
private fun returnLabel(): Label {
return Label(
text = text,
backgroundColor = backgroundColor,
color = color,
weight = weight,
animate = animate
)
}
@Test
fun `when getting the value of the label text then return value that was set`() {
Assert.assertEquals(label.text, text)
}
@Test
fun `when getting the value of the label backgroundColor then return value that was set`() {
Assert.assertEquals(label.backgroundColor, backgroundColor)
}
@Test
fun `when getting the value of the label color then return value that was set`() {
Assert.assertEquals(label.color, color)
}
@Test
fun `when getting the value of the label weight then return value that was set`() {
Assert.assertEquals(label.weight, weight)
}
@Test
fun `when getting the value of the animate weight then return value that was set`() {
Assert.assertEquals(label.animate, animate)
}
} | 1 | null | 1 | 1 | ceae49fefe8e358a8a86620416a5c653aa49389b | 1,493 | meli-card-drawer-android | Apache License 2.0 |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/GamepadTrigger.kt | Harshiv15 | 687,957,027 | false | {"Java": 96570, "Kotlin": 24864} | package org.firstinspires.ftc.teamcode.util.extractions
import com.arcrobotics.ftclib.command.button.Trigger
import com.arcrobotics.ftclib.gamepad.GamepadEx
import com.arcrobotics.ftclib.gamepad.GamepadKeys
class GamepadTrigger(gamepad: GamepadEx, vararg triggers: GamepadKeys.Trigger) : Trigger() {
private val m_gamepad: GamepadEx
private val m_triggers: Array<out GamepadKeys.Trigger>
init {
m_gamepad = gamepad
m_triggers = triggers
}
override fun get(): Boolean {
var res = true
for(trigger : GamepadKeys.Trigger in m_triggers) {
res = res && m_gamepad.getTrigger(trigger) > 0.5
}
return res
}
} | 1 | null | 1 | 1 | 7e2e65cb34555d8112d3dc5c3852c658326ff315 | 688 | FGCGB23 | BSD 3-Clause Clear License |
app/src/main/java/com/ruideraj/secretelephant/match/MatchAppSettingsDialog.kt | ruideraj | 153,840,048 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 48, "XML": 34, "Java": 1} | package com.ruideraj.secretelephant.match
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.ruideraj.secretelephant.R
class MatchAppSettingsDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return requireActivity().let {
AlertDialog.Builder(it)
.setMessage(R.string.match_settings_text)
.setPositiveButton(R.string.action_settings) { _, _ ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", it.packageName, null)).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
startActivity(intent)
}.setNegativeButton(R.string.action_cancel) { _, _ ->
// Do nothing other than close the dialog.
}.create()
}
}
} | 0 | Kotlin | 0 | 0 | 63480ca46fb7511268a65813da42dc75ef3d4166 | 1,146 | SecretElephant | Apache License 2.0 |
app/src/main/java/com/payu/android/front/sdk/demo/ui/base/binding/BindingUtils.kt | PayU-EMEA | 752,993,019 | false | {"Gradle": 18, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 15, "Batchfile": 1, "XML": 100, "Proguard": 13, "Java": 454, "YAML": 2, "Kotlin": 85, "INI": 1} | package com.payu.android.front.sdk.demo.ui.base.binding
import androidx.databinding.Observable
import io.reactivex.disposables.Disposables
inline fun <reified T : Observable> T.addOnPropertyChanged(crossinline callback: (T) -> Unit) =
object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(observable: Observable?, i: Int) = callback(observable as T)
}.also { addOnPropertyChangedCallback(it) }.let {
Disposables.fromAction { removeOnPropertyChangedCallback(it) }
} | 0 | Java | 0 | 0 | 9e55091062f6d942abeeeebc77bf05108849aead | 541 | PayU-Android | Apache License 2.0 |
android/src/main/java-v10/com/mapbox/rctmgl/components/mapview/RCTMGLAndroidTextureMapViewManager.kt | SethArchambault | 691,662,818 | true | {"JavaScript": 116, "Markdown": 57, "Ruby": 4, "Java Properties": 3, "Proguard": 1, "Java": 157, "Kotlin": 90, "TypeScript": 44, "Shell": 3, "Batchfile": 2, "INI": 4, "C++": 7, "Makefile": 1, "Objective-C": 186, "Swift": 76, "C": 1} | package com.mapbox.rctmgl.components.mapview
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewManagerDelegate
import com.facebook.react.viewmanagers.MBXAndroidTextureMapViewManagerDelegate
import com.facebook.react.viewmanagers.MBXAndroidTextureMapViewManagerInterface
import com.facebook.react.viewmanagers.MBXMapViewManagerDelegate
import com.mapbox.maps.MapInitOptions
class RCTMGLAndroidTextureMapViewManager(context: ReactApplicationContext) : RCTMGLMapViewManager(
context
), MBXAndroidTextureMapViewManagerInterface<RCTMGLMapView> {
private val mDelegate: ViewManagerDelegate<RCTMGLMapView>
init {
mDelegate = MBXAndroidTextureMapViewManagerDelegate<RCTMGLMapView, RCTMGLAndroidTextureMapViewManager>(this)
}
override fun getDelegate(): ViewManagerDelegate<RCTMGLMapView>? {
return mDelegate
}
override fun getName(): String {
return REACT_CLASS
}
override fun createViewInstance(themedReactContext: ThemedReactContext): RCTMGLMapView {
val context = getMapViewContext(themedReactContext)
val options = MapInitOptions(context = context, textureView= true)
return RCTMGLMapView(context, this, options)
}
companion object {
const val REACT_CLASS = "MBXAndroidTextureMapView"
}
} | 0 | null | 0 | 0 | d7936936bab2edea6cc803092c5f96bd56806d61 | 1,397 | maps | MIT License |
app/src/main/java/br/com/renancsdev/dtiblog/api/model/Postagem.kt | RenanCostaSilva | 805,452,810 | false | {"Gradle Kotlin DSL": 3, "Java Properties": 5, "Shell": 1, "Text": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "Ignore List": 2, "Kotlin": 36, "XML": 39, "INI": 3, "Java": 2, "PureBasic": 2} | package br.com.renancsdev.dtiblog.api.model
import java.util.Date
data class Postagem (
val id : Long,
val title : String,
val postText : String,
val dateCreationPost : Date
) | 0 | Java | 0 | 0 | c7d4d383be74b652bfda2242f06e8c2e7a33cec7 | 193 | DTIBlog | Apache License 2.0 |
src/main/kotlin/no/digdir/fdk/mqa/dcatvalidator/configuration/KafkaProducerConfig.kt | Informasjonsforvaltning | 615,214,940 | false | {"YAML": 15, "Ignore List": 2, "Maven POM": 1, "Dockerfile": 1, "Text": 2, "Markdown": 1, "Shell": 3, "JSON": 2, "Turtle": 6, "Kotlin": 15, "Java": 4, "XML": 1} | package no.digdir.fdk.mqa.dcatvalidator.configuration
import no.fdk.mqa.MQAEvent
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.core.ProducerFactory
@Configuration
open class KafkaProducerConfig {
@Bean
open fun kafkaTemplate(producerFactory: ProducerFactory<String, MQAEvent>): KafkaTemplate<String, MQAEvent> {
return KafkaTemplate(producerFactory)
}
}
| 5 | Java | 0 | 0 | dd18b813fd2ab0cc00405790515a222d45c448ee | 526 | fdk-mqa-dcat-validator | Apache License 2.0 |
app/src/main/java/com/erif/quickstates/helper/adapter/AdapterList.kt | eriffanani | 490,252,694 | false | {"Java": 27838, "Kotlin": 15184} | package com.erif.quickstates.helper.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.erif.quickstates.R
class AdapterList: RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var list: MutableList<Int> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return Holder(
LayoutInflater.from(parent.context).inflate(R.layout.item_list, parent, false)
)
}
override fun getItemCount(): Int = list.size
@SuppressLint("NotifyDataSetChanged")
fun setList(list: MutableList<Int>) {
this.list = list
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {}
private class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind() {}
}
} | 1 | null | 1 | 1 | 40a14f2cee94f10c37728b316485f7db22f413d8 | 998 | QuickState | Apache License 2.0 |
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/CreateModerationRequestTest.kt | oapicf | 529,246,487 | false | {"Markdown": 6348, "YAML": 73, "Text": 16, "Ignore List": 52, "JSON": 1138, "Makefile": 3, "JavaScript": 1042, "F#": 585, "XML": 468, "Shell": 47, "Batchfile": 10, "Scala": 2313, "INI": 31, "Dockerfile": 17, "Maven POM": 22, "Java": 6356, "Emacs Lisp": 1, "Haskell": 39, "Swift": 263, "Ruby": 555, "OASv3-yaml": 19, "Cabal Config": 2, "Go": 1036, "Go Checksums": 1, "Go Module": 4, "CMake": 11, "C++": 3617, "TOML": 5, "Rust": 268, "Nim": 253, "Perl": 252, "Microsoft Visual Studio Solution": 2, "C#": 778, "HTML": 257, "Xojo": 507, "Gradle": 20, "R": 503, "JSON with Comments": 8, "QMake": 1, "Kotlin": 1548, "Python": 1600, "Crystal": 486, "ApacheConf": 2, "PHP": 1715, "Gradle Kotlin DSL": 1, "Protocol Buffer": 250, "C": 752, "Ada": 16, "Objective-C": 522, "Java Properties": 2, "Erlang": 521, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 501, "SQL": 242, "AsciiDoc": 1, "CSS": 3, "PowerShell": 507, "Elixir": 5, "Apex": 426, "Gemfile.lock": 1, "Option List": 2, "Eiffel": 277, "Gherkin": 1, "Dart": 500, "Groovy": 251, "Elm": 13} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import org.openapitools.client.models.CreateModerationRequest
import org.openapitools.client.models.CreateModerationRequestInput
import org.openapitools.client.models.CreateModerationRequestModel
class CreateModerationRequestTest : ShouldSpec() {
init {
// uncomment below to create an instance of CreateModerationRequest
//val modelInstance = CreateModerationRequest()
// to test the property `input`
should("test input") {
// uncomment below to test the property
//modelInstance.input shouldBe ("TODO")
}
// to test the property `model`
should("test model") {
// uncomment below to test the property
//modelInstance.model shouldBe ("TODO")
}
}
}
| 2 | Java | 0 | 4 | c04dc03fa17b816be6e9a262c047840301c084b6 | 1,153 | openapi-openai | MIT License |
src/test/java/tech/aroma/data/sql/SQLActivityRepositoryIT.kt | RedRoma | 49,801,579 | false | {"Java": 611943, "Kotlin": 356709} | package tech.aroma.data.sql
/*
* Copyright 2017 RedRoma, 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.
*/
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.isEmpty
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.jdbc.core.JdbcOperations
import tech.aroma.data.notNull
import tech.aroma.data.sql.serializers.EventSerializer
import tech.aroma.thrift.User
import tech.aroma.thrift.events.Event
import tech.aroma.thrift.exceptions.DoesNotExistException
import tech.aroma.thrift.generators.EventGenerators.events
import tech.aroma.thrift.generators.UserGenerators.users
import tech.sirwellington.alchemy.annotations.testing.IntegrationTest
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.one
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(AlchemyTestRunner::class)
@IntegrationTest
class SQLActivityRepositoryIT
{
private companion object
{
@JvmStatic
lateinit var database: JdbcOperations
@JvmStatic
@BeforeClass
fun setupClass()
{
database = TestingResources.connectToDatabase()
}
}
private lateinit var event: Event
private lateinit var user: User
private val userId get() = user.userId
private val eventId get() = event.eventId
private val serializer = EventSerializer()
private lateinit var instance: SQLActivityRepository
@Before
fun setUp()
{
setupData()
setupMocks()
instance = SQLActivityRepository(database, serializer)
}
@After
fun cleanUp()
{
try
{
instance.deleteAllEventsFor(user)
}
catch (ex: Exception)
{
print(ex)
}
}
@Test
fun testSaveEvent()
{
instance.saveEvent(event, user)
assertTrue { instance.containsEvent(eventId, user) }
}
@Test
fun testSaveEventTwice()
{
instance.saveEvent(event, user)
assertThrows { instance.saveEvent(event, user) }
}
@Test
fun testContainsEvent()
{
assertFalse { instance.containsEvent(eventId, user) }
instance.saveEvent(event, user)
assertTrue { instance.containsEvent(eventId, user) }
}
@Test
fun testGetEvent()
{
instance.saveEvent(event, user)
val result = instance.getEvent(eventId, user)
assertThat(result, equalTo(event))
}
@Test
fun testGetEventWhenNotExists()
{
assertThrows {
instance.getEvent(eventId, user)
}.isInstanceOf(DoesNotExistException::class.java)
}
@Test
fun testGetAllEventsFor()
{
val events = CollectionGenerators.listOf(events(), 20)
events.forEach { instance.saveEvent(it, user) }
val results = instance.getAllEventsFor(user)
assertThat(results.toSet(), equalTo(events.toSet()))
}
@Test
fun testGetAllEventsWhenNone()
{
val result = instance.getAllEventsFor(user)
assertThat(result, notNull)
assertThat(result, isEmpty)
}
@Test
fun testDeleteEvent()
{
instance.saveEvent(event, user)
instance.deleteEvent(eventId, user)
assertFalse { instance.containsEvent(eventId, user) }
}
@Test
fun testDeleteEventWhenNone()
{
instance.deleteEvent(eventId, user)
}
@Test
fun testDeleteAllEventsFor()
{
val events = CollectionGenerators.listOf(events(), 40)
events.forEach { instance.saveEvent(it, user) }
var results = instance.getAllEventsFor(user)
assertThat(results, !isEmpty)
assertThat(results.size, equalTo(events.size))
instance.deleteAllEventsFor(user)
results = instance.getAllEventsFor(user)
assertThat(results, isEmpty)
events.forEach { assertFalse { instance.containsEvent(it.eventId, user) } }
}
private fun setupData()
{
user = one(users())
event = one(events())
}
private fun setupMocks()
{
}
} | 1 | null | 1 | 1 | 4c8818c6a85c6f70b819ad86482fef058d0c0fd4 | 4,938 | aroma-data-operations | Apache License 2.0 |
filepickerlib/src/main/java/com/zql/filepickerlib/picker/FileListViewModel.kt | lzqnet | 342,170,311 | false | {"Java": 182286, "Kotlin": 63156} | package com.zql.filepickerlib.picker
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import com.airbnb.mvrx.MvRxViewModelFactory
import com.airbnb.mvrx.ViewModelContext
import com.zql.filepickerlib.DefaultIconProvider
import com.zql.filepickerlib.BaseViewModel
import com.zql.filepickerlib.command.ListCommand
import com.zql.filepickerlib.config.DisplayRestrictions
import com.zql.filepickerlib.model.FileModel
import com.zql.filepickerlib.model.FileSystemObject
import com.zql.filepickerlib.util.RestrictionHelper
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlin.collections.HashMap
open class FileListViewModel(state: FileListState) : BaseViewModel<FileListState>(state) {
val mListCommand = ListCommand()
val mDefaultIconProvider = DefaultIconProvider()
// var atomicInteger: AtomicInteger = AtomicInteger(0)
init {
logStateChanges()
}
@SuppressLint("CheckResult")
fun fetchFileList(context: Context, path: String, mRestrictions: Map<DisplayRestrictions?, Any?>?) {
// val test = atomicInteger.incrementAndGet()
Log.d("lzqtest", "FileListViewModel.fetchFileList: enter ")
withState {
Observable.just(it).observeOn(Schedulers.io())
.map { state ->
val fileSystemObjectList = mListCommand.execute(path)
Log.d("lzqtest", "FileListViewModel.fetchFileList:fileSystemObjectList size= ${fileSystemObjectList.size} get list thread=${Thread.currentThread().name} ")
val sortedFiles = RestrictionHelper.applyUserPreferences(fileSystemObjectList, mRestrictions, false, context)
Log.d("lzqtest", "FileListViewModel.fetchFileList:sortedFiles size= ${sortedFiles.size} ")
Log.d("lzqtest", "FileListViewModel.fetchFileList: before convertFileModel ")
val ret = convertFileModel(sortedFiles, context, state.selectedFileList)
Log.d("lzqtest", "FileListViewModel.fetchFileList: after convertFileModel ")
ret
}.observeOn(AndroidSchedulers.mainThread())
.subscribe({
Log.d("lzqtest", "FileListViewModel.fetchFileList: subscribe ")
setState { copy(currentFileList = it) }
}, {
Log.d("lzqtest", "FileListViewModel.fetchFileList: subscribe throwable ", it)
setState { copy(currentFileList = null) }
})
}
}
private fun convertFileModel(fileSystemObjects: List<FileSystemObject>, context: Context, selectedItems: HashMap<String, FileModel>?): FileList<FileModel> {
val fileModelList = FileList<FileModel>()
Log.d("lzqtest", "FileListViewModel.convertFileModel:size= ${fileSystemObjects.size} thread=${Thread.currentThread()} ")
Log.d("lzqtest", "FileListViewModel.convertFileModel: withstate thread=${Thread.currentThread().name} ")
for (fso in fileSystemObjects) {
val model: FileModel = FileModel(fso)
val resourceId = mDefaultIconProvider.getDefaultIconResId(context, fso)
model.setResourceIconId(resourceId)
val selectModel: FileModel? = selectedItems?.get(fso.getFullPath())
if (selectModel != null) {
model.setSelected(true)
} else {
model.setSelected(false)
}
fileModelList.add(model)
}
Log.d("lzqtest", "FileListViewModel.convertFileModel:size ${fileModelList.size} ")
return fileModelList
}
fun setSelectedAllFile(isAdd: Boolean) {
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: is add=$isAdd")
withState {
val newState = it.copy(selectedFileList = HashMap())
val currentlist = newState.currentFileList
if (currentlist.isNullOrEmpty()) {
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: currentlist is null ")
return@withState
}
val itr = currentlist.iterator()
if (isAdd) {
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: size=${currentlist.size} ")
while (itr.hasNext()) {
val data = itr.next()
if(!data.isDirectory) {
newState.selectedFileList?.put(data.fileSystemObject.fullPath, data)
}else{
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: is dir $data ")
}
}
it.selectedFileList?.let { it1 -> newState.selectedFileList?.putAll(it1) }
}else{
it.selectedFileList?.let { it1 -> newState.selectedFileList?.putAll(it1) }
while (itr.hasNext()) {
val data = itr.next()
if(!data.isDirectory) {
newState.selectedFileList?.remove(data.fileSystemObject.fullPath)
}else{
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: isadd=$isAdd is dir $data ")
}
}
}
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: setstate ")
setState { newState }
}
}
fun setSelectedFile(file: FileModel, isAdd: Boolean) {
Log.d("lzqtest", "FileListViewModel.setSelectedFile: $file is add=$isAdd")
if(file.isDirectory){
Log.d("lzqtest", "FileListViewModel.setSelectedFile: file is directory $file ")
return
}
withState {
val newstate = it.copy(selectedFileList = if (!it.selectedFileList.isNullOrEmpty()) {
HashMap(it.selectedFileList)
} else {
HashMap()
})
val seclectedList = newstate.selectedFileList
if (isAdd) {
seclectedList?.put(file.fileSystemObject.fullPath, file)
} else {
seclectedList?.remove(file.fileSystemObject.fullPath)
}
setState { newstate }
}
}
fun applySelectedFiles() {
Log.d("lzqtest", "FileListViewModel.applySelectedFiles: 130 ")
withState {
val newState = it.copy(currentFileList = FileList())
val newList = newState.currentFileList
val oldList = it.currentFileList
if (oldList.isNullOrEmpty()) {
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: currentlist is null ")
return@withState
}
val itr = oldList.iterator()
Log.d("lzqtest", "FileListViewModel.setSelectedAllFile: new state selectedFileList size=${newState.selectedFileList?.size} old select size =${it.selectedFileList?.size}")
while (itr.hasNext()) {
val data = itr.next()
val newData = FileModel(data.fileSystemObject)
newData.isSelected = newState.selectedFileList?.containsKey(data.fileSystemObject.fullPath)
?: false
newData.resourceIconId = data.resourceIconId
newList?.add(newData)
}
Log.d("lzqtest", "FileListViewModel.applySelectedFiles: setState =newstate!=oldState:${newState!=it} ")
setState { newState }
}
}
// fun mergeSelectInfoToList(){
// withState {
// val newList=FileList<FileModel>()
// val newstate = it.copy()
// val list=newstate.currentFileList.invoke()
// if(list.isNullOrEmpty()){
// return@withState
// }
// val itr = list.iterator()
// while (itr.hasNext()){
// val data=itr.next()
// data.isSelected=it.selectedFileList?.containsKey(data.fileSystemObject.fullPath)?:false
// newList.add(data)
// }
// setState { newstate }
//
// }
// }
companion object : MvRxViewModelFactory<FileListViewModel, FileListState> {
override fun create(
viewModelContext: ViewModelContext,
state: FileListState
): FileListViewModel {
return FileListViewModel(state)
}
}
} | 1 | null | 1 | 1 | 9290eea428526c9fb9285e5f7fae6ec011ea9163 | 8,566 | lzqfilepicker | Apache License 2.0 |
Common/src/main/java/at/petrak/hexcasting/api/spell/mishaps/MishapUnescapedValue.kt | floatonfire | 566,158,079 | true | {"Java Properties": 2, "Groovy": 1, "Text": 3, "Gradle": 5, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 1, "Kotlin": 183, "Java": 293, "JSON": 988, "GLSL": 1, "YAML": 1, "HTML": 1, "Python": 1, "INI": 3, "TOML": 1} | package at.petrak.hexcasting.api.spell.mishaps
import at.petrak.hexcasting.api.misc.FrozenColorizer
import at.petrak.hexcasting.api.spell.DatumType
import at.petrak.hexcasting.api.spell.SpellDatum
import at.petrak.hexcasting.api.spell.SpellList
import at.petrak.hexcasting.api.spell.Widget
import at.petrak.hexcasting.api.spell.casting.CastingContext
import net.minecraft.world.item.DyeColor
/**
* The value was a naked iota without being Considered or Retrospected.
*/
class MishapUnescapedValue(
val perpetrator: SpellDatum<*>
) : Mishap() {
override fun accentColor(ctx: CastingContext, errorCtx: Context): FrozenColorizer =
dyeColor(DyeColor.GRAY)
override fun execute(ctx: CastingContext, errorCtx: Context, stack: MutableList<SpellDatum<*>>) {
val idx = stack.indexOfLast { it.getType() == DatumType.LIST }
if (idx != -1) {
val list = stack[idx].payload as SpellList
val idxOfIota = list.indexOfFirst { it == perpetrator }
if (idxOfIota != -1) {
stack[idx] = SpellDatum.make(list.modifyAt(idxOfIota) {
SpellList.LPair(SpellDatum.make(Widget.GARBAGE), it.cdr)
})
}
}
}
override fun errorMessage(ctx: CastingContext, errorCtx: Context) =
error("unescaped", perpetrator.display())
}
| 0 | null | 0 | 0 | c5c7b302d2b34d3fa1367bae390c985bc1bf45c0 | 1,352 | hexmod-fork | MIT License |
Kotiln/security/chapter02/exercise05/src/main/kotlin/com/example/exercise05/Exercise05Application.kt | bekurin | 558,176,225 | false | {"Git Config": 1, "Text": 12, "Ignore List": 96, "Markdown": 58, "YAML": 55, "JSON with Comments": 2, "JSON": 46, "HTML": 104, "robots.txt": 6, "SVG": 10, "TSX": 15, "CSS": 64, "Gradle Kotlin DSL": 107, "Shell": 72, "Batchfile": 71, "HTTP": 15, "INI": 112, "Kotlin": 682, "EditorConfig": 1, "Gradle": 40, "Java": 620, "JavaScript": 53, "Go": 8, "XML": 38, "Go Module": 1, "SQL": 7, "Dockerfile": 1, "Gherkin": 1, "Python": 153, "SCSS": 113, "Java Properties": 3, "AsciiDoc": 5, "Java Server Pages": 6, "Unity3D Asset": 451, "C#": 48, "Objective-C": 51, "C": 8, "Objective-C++": 1, "Smalltalk": 1, "OpenStep Property List": 12, "Dart": 17, "Swift": 8, "Ruby": 1} | package com.example.exercise05
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class Exercise05Application
/**
* authenticationManager 를 사용하여 authenticationProvider 를 임의로 설정할 수 있다.
* AuthenticationManager -> AuthenticationProvider -> (UserDetailsService, PasswordEncoder) 의 계층으로 구성된다.
* 따라서 provider 를 임의로 설정한다는 것은 PasswordEncoder와 UserDetailsService를 한번에 설정하겠다는 것이다.
*/
fun main(args: Array<String>) {
runApplication<Exercise05Application>(*args)
}
| 0 | Java | 0 | 2 | ede7cdb0e164ed1d3d2ee91c7770327b2ee71e4d | 551 | blog_and_study | MIT License |
151004/Bashlikov/rv_task03/publisher/src/main/kotlin/api/dto/request/UpdateTagDto.kt | eucalypt63 | 794,491,864 | true | {"Markdown": 7, "Batchfile": 35, "Java": 2875, "INI": 97, "TypeScript": 88, "SQL": 17, "C#": 1729, "Go": 20, "Java Properties": 17, "Dockerfile": 9, "HTML": 3, "Shell": 9, "PHP": 90, "JavaScript": 4, "Gradle Kotlin DSL": 32, "Kotlin": 519, "Java Server Pages": 19, "CSS": 5, "HTML+Razor": 6} | package by.bashlikovvv.api.dto.request
import by.bashlikovvv.util.inRange
import kotlinx.serialization.Serializable
import kotlin.jvm.Throws
@Serializable
data class UpdateTagDto @Throws(IllegalArgumentException::class) constructor(
val id: Long,
val name: String
) {
init {
require(name.inRange(2, 32))
}
} | 0 | Java | 0 | 0 | f858e2a964bbda47bac057cede8ced3287221573 | 335 | Distributed-Computing | MIT License |
deprecated/Tools/DaggerRxJavaProject/app/src/main/java/ca/six/demo/biz/splash/SplashPresenter.kt | songzhw | 57,045,008 | false | {"Java": 363640, "Kotlin": 128659, "JavaScript": 2528, "Groovy": 417} | package ca.six.demo.biz.splash
class SplashPresenter {
} | 1 | null | 1 | 1 | 8c4d47221a56b2e9d96e20419013900de20ec77c | 58 | AndroidArchitecture | Apache License 2.0 |
app/src/main/java/com/goldze/mvvmhabit/aioui/test/TestBRvBindingAdapter.kt | fengao1004 | 505,038,355 | false | {"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Text": 4, "Ignore List": 4, "Proguard": 3, "Java": 214, "XML": 141, "Kotlin": 158} | package com.goldze.mvvmhabit.aioui.test
import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.Observable
import androidx.databinding.ObservableInt
import androidx.databinding.ViewDataBinding
import com.goldze.mvvmhabit.aioui.Util.delHTMLTag
import com.goldze.mvvmhabit.aioui.bean.list.TestRecord
import com.goldze.mvvmhabit.aioui.common.viewpagerfragment.adapter.AIORvBindingAdapter
import com.goldze.mvvmhabit.aioui.common.viewpagerfragment.viewmodel.AIORecyclerViewItemViewModel
import com.goldze.mvvmhabit.databinding.ItemRvTestBinding
import com.goldze.mvvmhabit.utils.ImageUtil
class TestARvBindingAdapter : AIORvBindingAdapter() {
@SuppressLint("SetTextI18n")
override fun onBindBinding(
binding: ViewDataBinding,
variableId: Int,
layoutRes: Int,
position: Int,
item: AIORecyclerViewItemViewModel?
) {
super.onBindBinding(binding, variableId, layoutRes, position, item)
val record = item?.entity?.get()
if (binding is ItemRvTestBinding && record is TestRecord) {
if (!TextUtils.isEmpty(record.faceImage)) {
ImageUtil.display(
record.faceImage,
binding.ivImage,
0
)
}
binding.tvTitle.text = record.name
binding.tvContent.text = record.brief?.delHTMLTag()
binding.clickCount.text = "点击量:"+record.clickCount
record.clickCountOb = {
binding.clickCount.text = "点击量:" + record.clickCount
}
binding.testCount.text = "题目数量:" + record.quesCount.toString()
}
}
} | 1 | null | 1 | 1 | 1099bd7bfcf8a81d545567ae875b3528aa5fb1cd | 1,697 | AIO | Apache License 2.0 |
app/src/main/java/ru/hse/miem/ros/ui/fragments/intro/IntroViewPagerAdapter.kt | mkolpakov2002 | 713,131,056 | true | {"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 5, "Gradle Kotlin DSL": 2, "Kotlin": 239, "XML": 102, "HTML": 219, "JavaScript": 1, "CSS": 1, "INI": 2, "Proguard": 3, "Java": 160, "JSON": 1} | package ru.hse.miem.ros.ui.fragments.intro
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import ru.hse.miem.ros.R
/**
* TODO: Description
*
* @author Tanya Rykova
* @version 1.0.0
* @created on 19.06.20
* @updated on
* @modified by
*/
class IntroViewPagerAdapter(var mContext: Context?, var mListScreenItem: List<ScreenItem>) :
PagerAdapter() {
public override fun instantiateItem(container: ViewGroup, position: Int): Any {
val inflater: LayoutInflater =
mContext!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val layoutScreen: View = inflater.inflate(R.layout.fragent_onboarding, null)
val imgSlide: ImageView = layoutScreen.findViewById(R.id.introImage)
val title: TextView = layoutScreen.findViewById(R.id.introTitle)
val description: TextView = layoutScreen.findViewById(R.id.introDescription)
title.text = mListScreenItem[position].title
description.text = mListScreenItem[position].description
imgSlide.setImageResource(mListScreenItem[position].screenImage)
container.addView(layoutScreen)
return layoutScreen
}
public override fun getCount(): Int {
return mListScreenItem.size
}
public override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
public override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View?)
}
public fun getListScreenItem(): List<ScreenItem> {
return mListScreenItem
}
}
| 0 | Java | 0 | 0 | 6c12490c1bbc62e3918ea525c51ec188f07dee24 | 1,786 | ROS-Mobile-Android | MIT License |
chats/src/main/java/com/cyberland/messenger/chats/components/CountDownTimerProgressBar.kt | Era-CyberLabs | 576,196,269 | false | {"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472} | package com.bcm.messenger.chats.components
import android.content.Context
import android.os.Build
import android.os.CountDownTimer
import android.util.AttributeSet
import android.widget.ProgressBar
/**
* bcm.social.01 2019/1/25.
*/
class CountDownTimerProgressBar:ProgressBar {
private var countDownTimer: CountDownTimer? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
fun start(fromSecond:Long, toSecond:Long) {
stop()
this.max = 1000
if (fromSecond < toSecond){
setProgressInner(0)
return
}
val toMills = toSecond * 1000
val totalMills = fromSecond*1000
val duration = (fromSecond - toSecond)*1000L
val step = 1000 / 16L
countDownTimer?.cancel()
countDownTimer = object : CountDownTimer(duration, step) {
override fun onTick(millisUntilFinished: Long) {
val progress = ((toMills + duration - millisUntilFinished)*max/totalMills).toInt()
setProgressInner(progress)
}
override fun onFinish() {
setProgressInner(max)
}
}.start()
}
fun stop() {
countDownTimer?.cancel()
countDownTimer = null
setProgressInner(0)
}
private fun setProgressInner(progress:Int){
if (Build.VERSION.SDK_INT > 23){
setProgress(progress, false)
} else {
setProgress(progress)
}
}
} | 1 | null | 1 | 1 | 65a11e5f009394897ddc08f4252969458454d052 | 1,684 | cyberland-android | Apache License 2.0 |
app/ui/legacy/src/test/java/com/mail/ann/ViewTestExtensions.kt | ZhangXinmin528 | 516,242,626 | true | {"INI": 1, "Shell": 6, "Gradle": 30, "EditorConfig": 1, "Markdown": 8, "Git Attributes": 1, "Batchfile": 1, "Text": 44, "Ignore List": 4, "Git Config": 1, "XML": 399, "YAML": 6, "Kotlin": 744, "AIDL": 2, "Java": 433, "Java Properties": 1, "SVG": 67, "PostScript": 1, "JSON": 23, "E-mail": 27, "Proguard": 1} | package com.mail.ann
import android.widget.TextView
val TextView.textString: String
get() = text.toString()
| 0 | Java | 0 | 0 | 3efc82014d57307996329fd057c505d2b88ed044 | 114 | Ann-mail | Apache License 2.0 |
sample/src/main/java/jp/co/cyberagent/android/gpuimage/sample/App.kt | hotdl | 557,762,954 | true | {"Java Properties": 1, "Markdown": 5, "Gradle": 4, "Shell": 1, "Batchfile": 1, "Ignore List": 1, "Python": 1, "INI": 2, "Text": 2, "XML": 9, "CMake": 1, "C": 1, "Java": 96, "GLSL": 3, "Kotlin": 24} | package jp.co.cyberagent.android.gpuimage.sample
import android.app.Application
import jp.co.cyberagent.android.gpuimage.sample.utils.AppUtil
class App : Application() {
override fun onCreate() {
super.onCreate()
AppUtil.app = this
}
} | 0 | Java | 0 | 0 | 8439bd2c15bf69fcd59c99e6b6098eabf313cded | 261 | android-gpuimage | Apache License 2.0 |
src/test/kotlin/com/ort/howlingwolf/domain/model/ability/AbilityTest.kt | t-nonomura | 243,423,460 | false | {"Batchfile": 28, "Markdown": 2, "Kotlin": 198, "INI": 4, "Java": 325, "Java Properties": 4, "Shell": 20, "HTML": 4, "SQL": 4, "Perl": 3, "Python": 1} | package com.ort.howlingwolf.domain.model.ability
import com.ort.dbflute.allcommon.CDef
import com.ort.howlingwolf.HowlingWolfTest
import com.ort.howlingwolf.domain.model.village.VillageDays
import com.ort.howlingwolf.domain.model.village.VillageStatus
import com.ort.howlingwolf.domain.model.village.ability.VillageAbilities
import com.ort.howlingwolf.domain.model.village.ability.VillageAbility
import com.ort.howlingwolf.domain.model.village.participant.VillageParticipants
import com.ort.howlingwolf.dummy.DummyDomainModelCreator
import com.ort.howlingwolf.fw.exception.HowlingWolfBusinessException
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class AbilityTest : HowlingWolfTest() {
// ===================================================================================
// Test
// =========
@Test
fun test_getSelectableTargetList_未参加者() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val village = DummyDomainModelCreator.createDummyVillage()
val participant = null
// ## Act ##
val selectableTargetList = ability.getSelectableTargetList(village, participant)
// ## Assert ##
assertThat(selectableTargetList).`as`("参加していないので選択不可能").isEmpty()
}
@Test
fun test_getSelectableTargetList_終了した村() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val village = DummyDomainModelCreator.createDummyVillage().changeStatus(CDef.VillageStatus.終了)
val participant = DummyDomainModelCreator.createDummyVillageParticipant()
// ## Act ##
val selectableTargetList = ability.getSelectableTargetList(village, participant)
// ## Assert ##
assertThat(selectableTargetList).`as`("村が終了しているので選択不可能").isEmpty()
}
@Test
fun test_getSelectableTargetList_対象あり() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val participant = DummyDomainModelCreator.createDummyVillageParticipant().copy(
id = 1
)
val village = DummyDomainModelCreator.createDummyVillage().copy(
status = VillageStatus(CDef.VillageStatus.進行中),
participant = VillageParticipants(
3,
listOf(
participant.copy(id = 1),
participant.copy(id = 2),
participant.copy(id = 3)
)
)
)
// ## Act ##
val selectableTargetList = ability.getSelectableTargetList(village, participant)
// ## Assert ##
assertThat(selectableTargetList.size).isEqualTo(2)
}
@Test
fun test_getSelectingTarget_未参加者() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val village = DummyDomainModelCreator.createDummyVillage()
val participant = null
val villageAbilities = DummyDomainModelCreator.createDummyVillageAbilities()
// ## Act ##
val target = ability.getSelectingTarget(village, participant, villageAbilities)
// ## Assert ##
assertThat(target).`as`("参加していないのでなし").isNull()
}
@Test
fun test_getSelectingTarget_終了した村() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val village = DummyDomainModelCreator.createDummyVillage().changeStatus(CDef.VillageStatus.終了)
val participant = DummyDomainModelCreator.createDummyVillageParticipant()
val villageAbilities = DummyDomainModelCreator.createDummyVillageAbilities()
// ## Act ##
val target = ability.getSelectingTarget(village, participant, villageAbilities)
// ## Assert ##
assertThat(target).`as`("村が終了しているのでなし").isNull()
}
@Test
fun test_getSelectingTarget_対象あり() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val participant = DummyDomainModelCreator.createDummyVillageParticipant().copy(id = 100)
val targetParticipant = DummyDomainModelCreator.createDummyVillageParticipant().copy(id = 101)
val village = DummyDomainModelCreator.createDummyVillage().copy(
status = VillageStatus(CDef.VillageStatus.進行中),
participant = VillageParticipants(
count = 2,
memberList = listOf(
participant,
targetParticipant
)
),
day = VillageDays(
listOf(
DummyDomainModelCreator.createDummyVillageDay().copy(id = 2)
)
)
)
val villageAbilities = VillageAbilities(
listOf(
VillageAbility(
villageDayId = 2,
myselfId = participant.id,
targetId = targetParticipant.id,
ability = Ability(CDef.AbilityType.占い)
)
)
)
// ## Act ##
val target = ability.getSelectingTarget(village, participant, villageAbilities)
// ## Assert ##
assertThat(target?.id).`as`("").isEqualTo(targetParticipant.id)
}
@Test
fun test_createAbilitySetMessage() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val village = DummyDomainModelCreator.createDummyVillage().copy(
day = VillageDays(
listOf(
DummyDomainModelCreator.createDummyVillageDay()
)
)
)
val chara = DummyDomainModelCreator.createDummyChara()
val targetChara = DummyDomainModelCreator.createDummyChara()
// ## Act ##
val message = ability.createAbilitySetMessage(village, chara, targetChara)
// ## Assert ##
assertThat(message.content.text).isNotEmpty()
}
@Test(expected = HowlingWolfBusinessException::class)
fun test_assertAbility_その能力を持っていない() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.襲撃)
val village = DummyDomainModelCreator.createDummyVillage()
val participant = DummyDomainModelCreator.createDummyAliveSeer()
val targetId = null
// ## Act ##
// ## Assert ##
ability.assertAbility(village, participant, targetId)
}
@Test(expected = HowlingWolfBusinessException::class)
fun test_assertAbility_対象なしにできない能力なのに対象なし() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.占い)
val village = DummyDomainModelCreator.createDummyVillage()
val participant = DummyDomainModelCreator.createDummyAliveSeer()
val targetId = null
// ## Act ##
// ## Assert ##
ability.assertAbility(village, participant, targetId)
}
fun test_assertAbility_対象なしにできる能力で対象なし() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.襲撃)
val village = DummyDomainModelCreator.createDummyVillage()
val participant = DummyDomainModelCreator.createDummyAliveWolf()
val targetId = null
// ## Act ##
// ## Assert ##
ability.assertAbility(village, participant, targetId)
}
@Test(expected = HowlingWolfBusinessException::class)
fun test_assertAbility_対象あり_対象に選べない人を選ぼうとしている() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.襲撃)
val availableTarget = DummyDomainModelCreator.createDummyAliveHunter()
val village = DummyDomainModelCreator.createDummyVillage().copy(
status = VillageStatus(CDef.VillageStatus.進行中),
participant = VillageParticipants(
count = 1,
memberList = listOf(availableTarget)
),
day = VillageDays(listOf(DummyDomainModelCreator.createDummyVillageDay()))
)
val participant = DummyDomainModelCreator.createDummyAliveWolf()
val targetId = 10001
// ## Act ##
// ## Assert ##
ability.assertAbility(village, participant, targetId)
}
@Test
fun test_assertAbility_対象あり_正しい対象() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.襲撃)
val availableTarget = DummyDomainModelCreator.createDummyAliveHunter()
val village = DummyDomainModelCreator.createDummyVillage().copy(
status = VillageStatus(CDef.VillageStatus.進行中),
participant = VillageParticipants(
count = 1,
memberList = listOf(availableTarget)
),
day = VillageDays(listOf(DummyDomainModelCreator.createDummyVillageDay()))
)
val participant = DummyDomainModelCreator.createDummyAliveWolf()
val targetId = availableTarget.id
// ## Act ##
// ## Assert ##
ability.assertAbility(village, participant, targetId)
}
@Test
fun test_isUsable_行使できる() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.襲撃)
val participant = DummyDomainModelCreator.createDummyAliveWolf()
val village = DummyDomainModelCreator.createDummyVillage().copy(
status = VillageStatus(CDef.VillageStatus.進行中),
participant = VillageParticipants(
count = 1,
memberList = listOf(participant)
),
day = VillageDays(listOf(DummyDomainModelCreator.createDummyVillageDay()))
)
// ## Act ##
// ## Assert ##
assertThat(ability.isUsable(village, participant)).isTrue()
}
@Test
fun test_isUsable_行使できない() {
// ## Arrange ##
val ability = Ability(CDef.AbilityType.襲撃)
val participant = DummyDomainModelCreator.createDummyDeadWolf()
val village = DummyDomainModelCreator.createDummyVillage().copy(
status = VillageStatus(CDef.VillageStatus.進行中),
participant = VillageParticipants(
count = 1,
memberList = listOf(participant)
),
day = VillageDays(listOf(DummyDomainModelCreator.createDummyVillageDay()))
)
// ## Act ##
// ## Assert ##
assertThat(ability.isUsable(village, participant)).isFalse()
}
} | 1 | null | 1 | 1 | 5b2222e505cb7ba6c760d8d5a667facfd0998efa | 10,583 | howling-wolf-api | MIT License |
aoc-library/src/main/kotlin/com/capital7software/aoc/lib/graph/path/DigitalPlumber.kt | vjpalodichuk | 732,520,514 | false | {"Gradle Kotlin DSL": 11, "Markdown": 8, "Java Properties": 1, "Shell": 1, "Text": 256, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "INI": 1, "YAML": 2, "Java": 225, "Kotlin": 184, "JSON": 5, "XML": 1} | package com.capital7software.aoc.lib.graph.path
import com.capital7software.aoc.lib.graph.Graph
import com.capital7software.aoc.lib.string.clean
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import java.util.Properties
/**
* Walking along the memory banks of the stream, you find a small village that is experiencing a
* little confusion: some programs can't communicate with each other.
*
* Programs in this village communicate using a fixed system of **pipes**. Messages are passed
* between programs using these pipes, but most programs aren't connected to each other
* directly. Instead, programs pass messages between each other until the message
* reaches the intended recipient.
*
* For some reason, though, some of these messages aren't ever reaching their intended recipient,
* and the programs suspect that some pipes are missing. They would like you to investigate.
*
* You walk through the village and record the ID of each program and the IDs with which it can
* communicate directly (your puzzle input). Each program has one or more programs with which
* it can communicate, and these pipes are bidirectional; if 8 says it can communicate with 11,
* then 11 will say it can communicate with 8.
*
* You need to figure out how many programs are in the group that contains program ID 0.
*
* For example, suppose you go door-to-door like a travelling salesman and record
* the following list:
*
* ```
* 0 <-> 2
* 1 <-> 1
* 2 <-> 0, 3, 4
* 3 <-> 2, 4
* 4 <-> 2, 3, 6
* 5 <-> 6
* 6 <-> 4, 5
* ```
*
* In this example, the following programs are in the group that contains program ID 0:
*
* - Program 0 by definition.
* - Program 2, directly connected to program 0.
* - Program 3 via program 2.
* - Program 4 via program 2.
* - Program 5 via programs 6, then 4, then 2.
* - Program 6 via programs 4, then 2.
*
* Therefore, a total of 6 programs are in this group; all but program 1, which has a pipe
* that connects it to itself.
*
* There are more programs than just the ones in the group containing program ID 0.
* The rest of them have no way of reaching that group, and still might have no way
* of reaching each other.
*
* A **group** is a collection of programs that can all communicate via pipes either
* directly or indirectly. The programs you identified just a moment ago are all
* part of the same group. Now, they would like you to determine the total number
* of groups.
*
* In the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6,
* and the other consisting solely of program 1.
*
* @param input The [List] of [String] that describe the communications graph for the programs.
*/
class DigitalPlumber(input: List<String>) {
private val graph: Graph<Int, Int> = processInput(input)
@SuppressFBWarnings
private fun processInput(input: List<String>): Graph<Int, Int> {
val g = Graph<Int, Int>("program-communications")
input.forEach { line ->
val split = line.split(" <-> ".toRegex())
val sourceId = split[0]
val targets = split[1].split(",").map { it.clean() }
g.add(sourceId, sourceId.toInt())
targets.forEach { targetId ->
g.add(targetId, targetId.toInt())
// Bi-directional communication!
g.add(sourceId, targetId, "$sourceId-$targetId", 1)
g.add(targetId, sourceId, "$targetId-$sourceId", 1)
}
}
return g
}
/**
* Finds and returns the programs that are a part of the specified group. A program is in the
* specified group if there exists a path to that program.
*
* @param id The program ID that we are interested in finding the other programs that are in
* their group
* @return The set of program IDs that are in the specified group.
*/
@SuppressFBWarnings
fun programsInGroup(id: Int): Set<Int> {
val answer = mutableSetOf<Int>()
answer.add(id)
val pathFinder = ExplorerPathfinder<Int, Int>()
val properties = Properties()
properties[PathfinderProperties.STARTING_VERTEX_ID] = id.toString()
properties[PathfinderProperties.MAX_COST] = graph.size()
var distinct: PathfinderResult<Int, Int>? = null
pathFinder.find(
graph,
properties,
{
distinct = it
// Explorer is greedy and only calls the valid handler a single time!
PathfinderStatus.FINISHED
},
null
)
answer.addAll(distinct?.vertices?.mapNotNull { it.get() } ?: listOf())
return answer
}
/**
* Returns the total number of distinct communications groups in the communication network.
*
* @return The total number of distinct communications groups in the communication network.
*/
@SuppressFBWarnings
fun allGroups(): List<Set<Int>> {
val visited = mutableSetOf<Int>()
val answer = mutableListOf<Set<Int>>()
graph.vertices.forEach { vertex ->
if (vertex.get() !in visited) {
val group = programsInGroup(vertex.get())
visited.addAll(group)
answer.add(group)
}
}
return answer
}
}
| 0 | Java | 0 | 0 | da28d59b406f2e7e18cb32ade0d828a590d896c2 | 5,075 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/uten2c/rainstom/damage/DamageScaling.kt | rainbootsmc | 615,412,698 | false | {"Gradle Kotlin DSL": 7, "XML": 2, "Markdown": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Java": 1152, "TOML": 1, "INI": 1, "JSON": 6, "Kotlin": 25, "YAML": 1} | package dev.uten2c.rainstom.damage
enum class DamageScaling(val serializedName: String) {
NEVER("never"),
WHEN_CAUSED_BY_LIVING_NON_PLAYER("when_caused_by_living_non_player"),
ALWAYS("always"),
;
companion object {
@JvmStatic
fun fromSerializedName(serializedName: String): DamageScaling? =
entries.find { it.serializedName == serializedName }
}
}
| 0 | Java | 0 | 0 | ad563506f615e7417a61c112fb8430107a5199e9 | 402 | rainstom.old | Apache License 2.0 |
snowplow-tracker/src/androidTest/java/com/snowplowanalytics/snowplow/screenviews/ScreenSummaryStateMachineTest.kt | snowplow | 20,056,757 | false | {"Gradle": 6, "Java Properties": 1, "Markdown": 5, "Shell": 2, "Text": 1, "Ignore List": 5, "Batchfile": 1, "INI": 2, "YAML": 4, "Proguard": 4, "XML": 28, "Java": 4, "Kotlin": 303} | /*
* Copyright (c) 2015-present Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
import android.content.Context
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.snowplowanalytics.core.constants.TrackerConstants
import com.snowplowanalytics.core.emitter.Executor
import com.snowplowanalytics.core.screenviews.ScreenSummaryState
import com.snowplowanalytics.snowplow.Snowplow
import com.snowplowanalytics.snowplow.Snowplow.removeAllTrackers
import com.snowplowanalytics.snowplow.configuration.Configuration
import com.snowplowanalytics.snowplow.configuration.NetworkConfiguration
import com.snowplowanalytics.snowplow.controller.TrackerController
import com.snowplowanalytics.snowplow.event.*
import com.snowplowanalytics.snowplow.network.HttpMethod
import com.snowplowanalytics.snowplow.util.EventSink
import com.snowplowanalytics.snowplow.util.TimeTraveler
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
import kotlin.time.DurationUnit
import kotlin.time.toDuration
@RunWith(AndroidJUnit4::class)
class ScreenSummaryStateMachineTest {
var timeTraveler = TimeTraveler()
@Before
fun setUp() {
ScreenSummaryState.dateGenerator = { timeTraveler.generateTimestamp() }
}
@After
fun tearDown() {
removeAllTrackers()
Executor.shutdown()
}
// --- TESTS
@Test
fun tracksTransitionToBackgroundAndForeground() {
val eventSink = EventSink()
val tracker = createTracker(listOf(eventSink))
tracker.track(ScreenView(name = "Screen 1"))
timeTraveler.travelBy(10.toDuration(DurationUnit.SECONDS))
tracker.track(Background())
Thread.sleep(200)
timeTraveler.travelBy(5.toDuration(DurationUnit.SECONDS))
tracker.track(Foreground())
Thread.sleep(200)
val events = eventSink.trackedEvents
Assert.assertEquals(3, events.size)
val backgroundSummary = getScreenSummary(events.find { it.schema == Background.schema })
Assert.assertEquals(10.0, backgroundSummary?.get("foreground_sec"))
Assert.assertEquals(0.0, backgroundSummary?.get("background_sec"))
val foregroundSummary = getScreenSummary(events.find { it.schema == Foreground.schema })
Assert.assertEquals(10.0, foregroundSummary?.get("foreground_sec"))
Assert.assertEquals(5.0, foregroundSummary?.get("background_sec"))
}
@Test
fun tracksScreenEndEventWithScreenSummary() {
val eventSink = EventSink()
val tracker = createTracker(listOf(eventSink))
tracker.track(ScreenView(name = "Screen 1"))
Thread.sleep(200)
timeTraveler.travelBy(10.toDuration(DurationUnit.SECONDS))
tracker.track(ScreenView(name = "Screen 2"))
Thread.sleep(200)
val events = eventSink.trackedEvents
Assert.assertEquals(3, events.size)
val screenEnd = events.find { it.schema == TrackerConstants.SCHEMA_SCREEN_END }
val screenSummary = getScreenSummary(screenEnd)
Assert.assertEquals(10.0, screenSummary?.get("foreground_sec"))
Assert.assertEquals(0.0, screenSummary?.get("background_sec"))
// should have the screen name of the first screen view
val screenEndScreen = screenEnd?.entities?.find { it.map["schema"] == TrackerConstants.SCHEMA_SCREEN }
Assert.assertEquals("Screen 1", (screenEndScreen?.map?.get("data") as? Map<*, *>)?.get("name"))
}
@Test
fun updatesListMetrics() {
val eventSink = EventSink()
val tracker = createTracker(listOf(eventSink))
tracker.track(ScreenView(name = "Screen 1"))
Thread.sleep(200)
tracker.track(ListItemView(index = 1, itemsCount = 10))
Thread.sleep(200)
tracker.track(ListItemView(index = 3, itemsCount = 10))
Thread.sleep(200)
tracker.track(ListItemView(index = 2, itemsCount = 10))
Thread.sleep(200)
tracker.track(ScreenView(name = "Screen 2"))
Thread.sleep(200)
val events = eventSink.trackedEvents
Assert.assertEquals(3, events.size)
val screenSummary = getScreenSummary(events.find { it.schema == TrackerConstants.SCHEMA_SCREEN_END })
Assert.assertEquals(3, screenSummary?.get("last_item_index"))
Assert.assertEquals(10, screenSummary?.get("items_count"))
}
@Test
fun updatesScrollMetrics() {
val eventSink = EventSink()
val tracker = createTracker(listOf(eventSink))
tracker.track(ScreenView(name = "Screen 1"))
Thread.sleep(200)
tracker.track(ScrollChanged(yOffset = 10, viewHeight = 20, contentHeight = 100))
Thread.sleep(200)
tracker.track(ScrollChanged(xOffset = 15, yOffset = 30, viewWidth = 15, viewHeight = 20, contentWidth = 150, contentHeight = 100))
Thread.sleep(200)
tracker.track(ScrollChanged(yOffset = 20, viewHeight = 20, contentHeight = 100))
Thread.sleep(200)
tracker.track(ScreenView(name = "Screen 2"))
Thread.sleep(200)
val events = eventSink.trackedEvents
Assert.assertEquals(3, events.size)
val screenSummary = getScreenSummary(events.find { it.schema == TrackerConstants.SCHEMA_SCREEN_END })
Assert.assertEquals(10, screenSummary?.get("min_y_offset"))
Assert.assertEquals(15, screenSummary?.get("min_x_offset"))
Assert.assertEquals(50, screenSummary?.get("max_y_offset"))
Assert.assertEquals(30, screenSummary?.get("max_x_offset"))
Assert.assertEquals(150, screenSummary?.get("content_width"))
Assert.assertEquals(100, screenSummary?.get("content_height"))
}
// --- PRIVATE
private val context: Context
get() = InstrumentationRegistry.getInstrumentation().targetContext
private fun getScreenSummary(event: InspectableEvent?): Map<String, Any?>? {
val entity = event?.entities?.find { it.map["schema"] == TrackerConstants.SCHEMA_SCREEN_SUMMARY }
return entity?.map?.get("data") as? Map<String, Any?>
}
private fun createTracker(configurations: List<Configuration>): TrackerController {
val networkConfig = NetworkConfiguration(MockNetworkConnection(HttpMethod.POST, 200))
return Snowplow.createTracker(
context,
namespace = "ns" + Math.random().toString(),
network = networkConfig,
configurations = configurations.toTypedArray()
)
}
}
| 1 | null | 1 | 1 | fa694a5687e5eee6536f2e79a8eb105f622ce9e3 | 7,267 | snowplow-android-tracker | Apache License 2.0 |
app/src/main/java/com/hudson/wanandroid/data/entity/wrapper/BaseResult.kt | HudsonAndroid | 278,809,991 | false | {"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 6, "Kotlin": 99, "XML": 36, "Java": 10} | package com.hudson.wanandroid.data.entity.wrapper
/**
* Created by Hudson on 2020/7/11.
*/
open class BaseResult {
var errorCode : Int = -1
var errorMsg: String = ""
override fun toString(): String {
return "BaseResult(errorCode=$errorCode, errorMsg='$errorMsg')"
}
open fun isSuccess():Boolean{
return errorCode == 0
}
} | 1 | Kotlin | 1 | 0 | 815bc87fb476849295faeff10dba60a55ac1c25b | 368 | WanAndroidJetpack | Apache License 2.0 |
app/src/main/java/com/etologic/pointscorer/app/main/activity/MainActivityViewModelFactory.kt | ernestovega | 131,583,223 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 47, "Kotlin": 33} | package com.etologic.pointscorer.app.main.activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.etologic.pointscorer.data.repositories.players.PlayersRepository
import javax.inject.Inject
class MainActivityViewModelFactory
@Inject internal constructor(private val playersRepository: PlayersRepository) : ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T = MainActivityViewModel(playersRepository,) as T
}
| 0 | Kotlin | 0 | 0 | a711f9cafd7c4785f1c5562ec75004a0f748d9c8 | 546 | PointScorer | MIT License |
yandex_smart_home/src/main/java/ru/hse/miem/yandex_smart_home/capabilities/Toggle.kt | mkolpakov2002 | 713,131,056 | true | {"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 5, "Gradle Kotlin DSL": 2, "Kotlin": 239, "XML": 102, "HTML": 219, "JavaScript": 1, "CSS": 1, "INI": 2, "Proguard": 3, "Java": 160, "JSON": 1} | package ru.hse.miem.yandex_smart_home.capabilities
data class Toggle(var value: Boolean, var instance: ToggleFunctions) : BaseCapability("toggle") {
val state: Map<String, Any>
get() = mapOf("instance" to instance, "value" to value)
operator fun invoke(): Map<String, Any> {
return mapOf("type" to _type, "state" to state)
}
} | 0 | Java | 0 | 0 | 6c12490c1bbc62e3918ea525c51ec188f07dee24 | 356 | ROS-Mobile-Android | MIT License |
src/main/java/net/ccbluex/liquidbounce/features/module/modules/combat/FastBow.kt | 2946257770 | 693,652,489 | false | {"Java": 1812636, "Kotlin": 1801560, "GLSL": 13689, "JavaScript": 9199, "HTML": 850} | /*
* LiquidBounce+ Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/WYSI-Foundation/LiquidBouncePlus/
*/
package net.ccbluex.liquidbounce.features.module.modules.combat
import net.ccbluex.liquidbounce.event.EventTarget
import net.ccbluex.liquidbounce.event.UpdateEvent
import net.ccbluex.liquidbounce.event.PacketEvent
import net.ccbluex.liquidbounce.features.module.Module
import net.ccbluex.liquidbounce.features.module.ModuleCategory
import net.ccbluex.liquidbounce.features.module.ModuleInfo
import net.ccbluex.liquidbounce.utils.PacketUtils
import net.ccbluex.liquidbounce.utils.RotationUtils
import net.ccbluex.liquidbounce.utils.timer.MSTimer
import net.ccbluex.liquidbounce.value.IntegerValue
import net.minecraft.item.ItemBow
import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook
import net.minecraft.network.play.client.C07PacketPlayerDigging
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement
import net.minecraft.util.BlockPos
import net.minecraft.util.EnumFacing
@ModuleInfo(name = "FastBow", spacedName = "Fast Bow", description = "Turns your bow into a machine gun.", category = ModuleCategory.COMBAT)
class FastBow : Module() {
private val packetsValue = IntegerValue("Packets", 20, 3, 20)
private val delay = IntegerValue("Delay", 0, 0, 500, "ms")
val timer = MSTimer()
var packetCount = 0
@EventTarget
fun onUpdate(event: UpdateEvent) {
if (!mc.thePlayer.isUsingItem) {
packetCount = 0
return
}
if (mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().item is ItemBow) {
if (packetCount == 0)
PacketUtils.sendPacketNoEvent(C08PacketPlayerBlockPlacement(BlockPos.ORIGIN, 255, mc.thePlayer.currentEquippedItem, 0F, 0F, 0F))
val yaw = if (RotationUtils.targetRotation != null)
RotationUtils.targetRotation.yaw
else
mc.thePlayer.rotationYaw
val pitch = if (RotationUtils.targetRotation != null)
RotationUtils.targetRotation.pitch
else
mc.thePlayer.rotationPitch
if (delay.get() == 0) {
repeat (packetsValue.get()) {
mc.netHandler.addToSendQueue(C05PacketPlayerLook(yaw, pitch, true))
}
PacketUtils.sendPacketNoEvent(C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN))
} else {
if (timer.hasTimePassed(delay.get().toLong())) {
packetCount++
mc.netHandler.addToSendQueue(C05PacketPlayerLook(yaw, pitch, true))
timer.reset()
}
if (packetCount == packetsValue.get())
PacketUtils.sendPacketNoEvent(C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN))
}
mc.thePlayer.itemInUseCount = mc.thePlayer.inventory.getCurrentItem().maxItemUseDuration - 1
}
}
@EventTarget
fun onPacket(event: PacketEvent) {
mc.thePlayer ?: return
mc.thePlayer.inventory ?: return
val packet = event.packet
if (mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().item is ItemBow) {
if (packet is C08PacketPlayerBlockPlacement || (packet is C07PacketPlayerDigging && packet.status == C07PacketPlayerDigging.Action.RELEASE_USE_ITEM))
event.cancelEvent()
}
}
} | 1 | null | 1 | 1 | 4e111df6cd3ca03da3b285eb8572ef79a9ff8695 | 3,711 | VulgarSense | Apache License 2.0 |
core/src/main/kotlin/luckytree/poom/core/CoreApplication.kt | lucky-treee | 597,659,992 | false | {"Java": 84158, "Kotlin": 28435} | package luckytree.poom.core
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
@ConfigurationPropertiesScan
@SpringBootApplication
class CoreApplication
fun main(args: Array<String>) {
runApplication<CoreApplication>(*args)
}
| 1 | null | 1 | 1 | 52415d08b02b89dfaf3ef5c1f8d4ee37ac2530eb | 373 | diamond | MIT License |
library/src/main/java/com/applandeo/materialcalendarview/CalendarDay.kt | Applandeo | 92,400,879 | false | {"Gradle": 5, "Markdown": 2, "Java Properties": 3, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "XML": 43, "Java": 7, "Kotlin": 32} | package com.applandeo.materialcalendarview
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import java.util.Calendar
data class CalendarDay(
val calendar: Calendar
) {
@ColorRes
var labelColor: Int? = null
@DrawableRes
var backgroundResource: Int? = null
var backgroundDrawable: Drawable? = null
@ColorRes
var selectedLabelColor: Int? = null
@DrawableRes
var selectedBackgroundResource: Int? = null
var selectedBackgroundDrawable: Drawable? = null
@DrawableRes
var imageResource: Int? = null
var imageDrawable: Drawable? = null
} | 30 | Kotlin | 314 | 952 | 8abaf104966ea3a76a060998ce5f74ed2589a9ee | 660 | Material-Calendar-View | Apache License 2.0 |
SDKChallengeProject/TAAS/android_basic/business/src/main/java/com/framing/business/data/BusinessApplication.kt | softwarekk | 285,520,801 | true | {"Markdown": 10, "Java Properties": 2, "Gradle": 12, "Shell": 1, "Batchfile": 1, "Ignore List": 10, "INI": 9, "Proguard": 9, "Kotlin": 104, "XML": 64, "Java": 40, "JSON": 28} | package com.framing.business.data
import com.framing.commonlib.base.CommonApplication
/*
* Des
* Author Young
* Date
*/class BusinessApplication :CommonApplication {
constructor() : super()
} | 0 | Java | 0 | 2 | 7bcadf38900d8ce23ebfdc4f69a716cd926595e8 | 204 | RTE-Innovation-Challenge-2020 | MIT License |
app/src/main/java/de/p72b/mocklation/service/setting/Setting.kt | xaxasemail | 505,387,056 | true | {"Java Properties": 2, "SVG": 2, "Gradle": 3, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 48, "Proguard": 1, "Java": 37, "Kotlin": 5} | package de.p72b.mocklation.service.setting
import android.Manifest
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
class Setting(context: Context) : ISetting {
companion object {
private const val PERMISSION_LOCATION = "PERMISSION_LOCATION"
private const val SHARED_PREFS_FILE = "omagu.settings"
private const val LAST_POSITION_LAT = "LAST_POSITION_LAT"
private const val LAST_POSITION_LNG = "LAST_POSITION_LNG"
private const val ACTIVE_MOCK_LOCATION_CODE = "ACTIVE_MOCK_LOCATION_CODE"
private const val LAST_SELECTED_LOCATION_CODE = "LAST_SELECTED_LOCATION_CODE"
private const val PRIVACY_UPDATE_ACCEPTED = "PRIVACY_UPDATE_ACCEPTED"
private const val ANALYTICS_TRACKING_ENABLED = "ANALYTICS_TRACKING_ENABLED"
}
private val preferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)
private val preferencesDefault = PreferenceManager.getDefaultSharedPreferences(context)
override fun saveLocation(latitude: Double, longitude: Double) {
val edit = preferences.edit()
edit.putFloat(LAST_POSITION_LAT, latitude.toFloat())
edit.putFloat(LAST_POSITION_LNG, longitude.toFloat())
edit.apply()
}
override fun setPermissionDecision(permissionKey: String, decision: Boolean) {
val edit = preferences.edit()
edit.putBoolean(permissionKey, decision)
edit.apply()
}
override fun getPermissionDecision(permission: String): Boolean {
return preferences.getBoolean(resolvePermissionPreferencesKey(permission), false)
}
private fun resolvePermissionPreferencesKey(permission: String): String? {
return when (permission) {
Manifest.permission.ACCESS_FINE_LOCATION -> PERMISSION_LOCATION
else -> null
}
}
override fun setMockLocationItemCode(code: String?) {
val edit = preferences.edit()
edit.putString(ACTIVE_MOCK_LOCATION_CODE, code)
edit.apply()
}
override fun saveLastPressedLocation(code: String) {
val edit = preferences.edit()
edit.putString(LAST_SELECTED_LOCATION_CODE, code)
edit.apply()
}
override fun getLastPressedLocationCode(): String? {
return preferences.getString(LAST_SELECTED_LOCATION_CODE, null)
}
override fun getMockLocationItemCode(): String? {
return preferences.getString(ACTIVE_MOCK_LOCATION_CODE, null)
}
override fun isPrivacyStatementAccepted(): Boolean {
return preferencesDefault.getBoolean(PRIVACY_UPDATE_ACCEPTED, false)
}
override fun acceptCurrentPrivacyStatement(value: Boolean) {
val edit = preferences.edit()
edit.putBoolean(PRIVACY_UPDATE_ACCEPTED, value)
edit.apply()
}
override fun isAnalyticsCollectionEnabled(): Boolean {
return preferences.getBoolean(ANALYTICS_TRACKING_ENABLED, false)
}
override fun setAnalyticsCollectionEnabled(value: Boolean) {
val edit = preferences.edit()
edit.putBoolean(ANALYTICS_TRACKING_ENABLED, value)
edit.apply()
}
}
| 0 | null | 0 | 0 | e70cdac9bbbfa51312f091b65287d4efc92d15d3 | 3,209 | Mocklation | MIT License |
151004/Bashlikov/rv_task01/src/main/kotlin/by/bashlikovvv/api/dto/request/CreateEditorDto.kt | IlyaSubtilnyj | 787,986,594 | true | {"Markdown": 7, "Batchfile": 32, "Java": 2815, "INI": 93, "TypeScript": 88, "SQL": 17, "C#": 1468, "Go": 20, "Java Properties": 11, "Dockerfile": 9, "HTML": 3, "Shell": 9, "PHP": 177, "JavaScript": 4, "Gradle Kotlin DSL": 32, "Kotlin": 519, "Java Server Pages": 19, "CSS": 5, "HTML+Razor": 6} | package by.bashlikovvv.api.dto.request
import by.bashlikovvv.util.inRange
import kotlinx.serialization.Serializable
import kotlin.jvm.Throws
@Serializable
class CreateEditorDto @Throws(IllegalStateException::class) constructor(
val login: String,
val password: String,
val firstname: String,
val lastname: String
) {
init {
if (!login.inRange(2, 64)) {
throw IllegalStateException()
}
if (!password.inRange(8, 128)) {
throw IllegalStateException()
}
if (!firstname.inRange(2, 64)) {
throw IllegalStateException()
}
if (!lastname.inRange(2, 64)) {
throw IllegalStateException()
}
}
} | 0 | Java | 0 | 0 | 40891cce5d18a78c46dd1b44f5e5b2ab4cef51ad | 722 | DC2024-01-27 | MIT License |
app/src/main/java/top/niunaijun/blackboxa/view/main/BlackBoxLoader.kt | dvc890 | 516,308,492 | true | {"Java Properties": 1, "Gradle": 10, "Shell": 1, "Markdown": 5, "Git Attributes": 1, "Batchfile": 1, "Text": 5, "Ignore List": 8, "YAML": 1, "INI": 5, "Proguard": 8, "XML": 48, "Java": 519, "HTML": 7, "AIDL": 61, "CMake": 2, "C++": 62, "C": 9, "Kotlin": 57, "Unix Assembly": 3} | package top.niunaijun.blackboxa.view.main
import android.app.Application
import android.content.Context
import android.util.Log
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedHelpers
import top.niunaijun.blackbox.BlackBoxCore
import top.niunaijun.blackbox.app.BActivityThread
import top.niunaijun.blackbox.app.configuration.AppLifecycleCallback
import top.niunaijun.blackbox.app.configuration.ClientConfiguration
import top.niunaijun.blackboxa.app.App
import top.niunaijun.blackboxa.biz.cache.AppSharedPreferenceDelegate
import top.niunaijun.blackboxa.util.HookHelper
import java.io.File
/**
*
* @Description:
* @Author: wukaicheng
* @CreateDate: 2021/5/6 23:38
*/
class BlackBoxLoader {
private var mHideRoot by AppSharedPreferenceDelegate(App.getContext(), false)
private var mHideXposed by AppSharedPreferenceDelegate(App.getContext(), false)
private var mDaemonEnable by AppSharedPreferenceDelegate(App.getContext(), false)
private var mShowShortcutPermissionDialog by AppSharedPreferenceDelegate(App.getContext(), true)
fun hideRoot(): Boolean {
return mHideRoot
}
fun invalidHideRoot(hideRoot: Boolean) {
this.mHideRoot = hideRoot
}
fun hideXposed(): Boolean {
return mHideXposed
}
fun invalidHideXposed(hideXposed: Boolean) {
this.mHideXposed = hideXposed
}
fun daemonEnable(): Boolean {
return mDaemonEnable
}
fun invalidDaemonEnable(enable: Boolean) {
this.mDaemonEnable = enable
}
fun showShortcutPermissionDialog(): Boolean {
return mShowShortcutPermissionDialog
}
fun invalidShortcutPermissionDialog(show: Boolean) {
this.mShowShortcutPermissionDialog = show
}
fun getBlackBoxCore(): BlackBoxCore {
return BlackBoxCore.get()
}
fun addLifecycleCallback() {
BlackBoxCore.get().addAppLifecycleCallback(object : AppLifecycleCallback() {
override fun beforeCreateApplication(
packageName: String?,
processName: String?,
context: Context?,
userId: Int
) {
Log.d(
TAG,
"beforeCreateApplication: pkg $packageName, processName $processName,userID:${BActivityThread.getUserId()}"
)
//HookHelper.dumpDex(packageName)
if(packageName.equals("xyz.aethersx2.android")) {
HookHelper.hookClassAllMethods(context!!.classLoader,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam?) {
super.beforeHookedMethod(param)
var argsstr = "("
for (item in param!!.args) {
argsstr += item.toString()
argsstr += ","
}
if(param.args.size > 0) {
argsstr = argsstr.subSequence(0,argsstr.length-1) as String
}
argsstr += ")"
Log.d(
"Pipedvc",
"beforeHookedMethod:" +
param.thisObject.javaClass.name + "->" + param.method.name + "" + argsstr
)
}
}, "android.app.ContextImpl\$ApplicationContentResolver", "android.content.ContentResolver", "android.content.ContentInterface", "android.app.Application");
// HookHelper.hookClassAllMethods(context!!.classLoader,
// object : XC_MethodHook() {
// override fun beforeHookedMethod(param: MethodHookParam?) {
// super.beforeHookedMethod(param)
// var argsstr = "("
// for (item in param!!.args) {
// argsstr += item.toString()
// argsstr += ","
// }
// if(param.args.size > 0) {
// argsstr = argsstr.subSequence(0,argsstr.length-1) as String
// }
// argsstr += ")"
// Log.d(
// "Pipedvc",
// "beforeHookedMethod:" +
// "NativeLibrary" + "->" + param.method.name + "" + argsstr
// )
// }
// override fun afterHookedMethod(param: MethodHookParam?) {
// super.afterHookedMethod(param)
// var argsstr = "("
// for (item in param!!.args) {
// argsstr += item.toString()
// argsstr += ","
// }
// if(param.args.size > 0) {
// argsstr = argsstr.subSequence(0,argsstr.length-1) as String
// }
// argsstr += ")"
// var result = ""
// if (param.result is String) {
// result = param.result as String
// } else if (param.result is Array<*>) {
// val r = param.result as Array<*>
// result += "["
// for (t in r) {
// if (t is String) {
// result += t
// } else {
// result += t.toString()
// }
// result += "|"
// }
// if(r.size > 0) {
// result = result.subSequence(0,result.length-1) as String
// }
// result += "]"
// } else if(param.result == null) {
// result = "void"
// } else {
// result = param.result.toString()
// }
// Log.d(
// "Pipedvc",
// "callafterHooked:" +
// "NativeLibrary" + "->" + param.method.name + "" + argsstr + "=" + result
// )
//
// }
// }, "xyz.aethersx2.android.NativeLibrary")
}
}
override fun beforeApplicationOnCreate(
packageName: String?,
processName: String?,
application: Application?,
userId: Int
) {
// if(packageName.equals("xyz.aethersx2.android")) {
// HookHelper.hookPackageSign(application, "3082058830820370a00302010202146746c609cd52b92de49eb65a6e41524e5a33e41c300d06092a864886f70d01010b05003074310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630140603550407130d4d6f756e7461696e205669657731143012060355040a130b476f6f676c6520496e632e3110300e060355040b1307416e64726f69643110300e06035504031307416e64726f69643020170d3231313130373039353431325a180f32303531313130373039353431325a3074310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630140603550407130d4d6f756e7461696e205669657731143012060355040a130b476f6f676c6520496e632e3110300e060355040b1307416e64726f69643110300e06035504031307416e64726f696430820222300d06092a864886f70d01010105000382020f003082020a0282020100cd6d83dca90298abd53480aecfc72e693ae300ecaca46057de1b5b8172bb777b20d0eaa6854fe3a9f8765a50fccfb1ee113894b103991aa59c978577e4a79e2bf5ef7eaeccf2a63ec42c61bdfbb4ba903a7d8cb7cb496e0de20267a8b6eaab17d62e74afbc4975b5eeb2f8b93f8ca01aee1307a40300952a4e744423041259be00b1e055c5e8055ee805084298d31b0851dcf5e82be5c5972fa0a8848a14ae6c0a4ab854a7970c6b39b02a1283fe24b5b521786e56dddd34499455d0b726be6115e0f680b0949373ac7b8356443894847a9805a72be4ba268041715602ad4f51a733d1d25736ee2cec9a45025da4375f76dca7bae133a83f35e890005ccf7ecc07fdcfb42b1c76145c8379b8c9d65bf5b2da5439b3c9fa855817e7de4109367462c797132db9cfa2018de9d7e9da76769cc3df2a149651c425161a8b5aeeeda10fb167b7f34d80eed43406522dbf18880e0fe67d3bd70f6dacb009dea0f4fbf15f2a37da4765f80a4c8bded02cd05699b23ec9c52c6d193261b61b3d5af604b2fee5f09d933ddecd399587f6f8e6a2292012e5cb1ffd9d7842846efb3636bd175acac159956b36c9ca04fd8745f6865cd0de1189e4edffefb11c3463debd18ca7d473663d855f3497f7fa55982415b76de87c2b1314d8461785f206f5d2e718084c2ab7529b7922f64319db52f5ec3770fbffae4a03ffcd25ba0194f69eb40a10203010001a310300e300c0603551d13040530030101ff300d06092a864886f70d01010b050003820201001396bba44d9535eebe4d1a3a0ccbcdd5f9d2015161bca29d9ccf419baf59a0f6d90935ef8ba4349aa1e29304e79142394b13d547a0bef63444badab35f60d89d0073d27c9afd470b953f696743570a042057ea350297dd06958882fa71791bab455ff57163aafc94fe73a3a5477f90e32c54bb7e296721d91a69f34297b40a85bb040f895c26be5a0f5f175a3790120f3c75e2d451d1ddf3644ed74696d450161daddfc4c6aaa7e691bdf78b32cecbfc3b461bddeb1e521fbf525b24f03835a6d01c6c3d536821d918193491afa6c6b622b7871b5e04bbbeafeff5aec3d0430cc9827ce7d76d0fd8e4a395f39f93db6a9c20710271fa67ea4feb30d899195838a833c82365c477db37c47aaa1f6d427fa30bb302c5dcc13afdbb267190490609dc6ba17b3e505fe3682875c1789eb30928c214fcc23ac71eedc9730e763d120ea3301fa4b366f10bf340b3f3843c03001b191e7bfee04a25dfd69c9cf92c563dd96241c9d77ca62c271594369e9b67864d2bdd578cd68ed879dce6fc818c44d61daa6da711341fc93a94199dc5db2e599e4216f8f793a0a537ff7b6168fc6ffd185d5a7894975754275c05b09dbc59184d619e20e56f01d8acf8f9a4fb34814782254205811bca490e280bc9495b1c62342af3ab6d53d702da7186bfa7bd26335e57710a5eb8e9937df5033c9754b8bcacd1afaf29e2be8f54dfa01d35fc3f53")
// }
Log.d(TAG, "beforeApplicationOnCreate: pkg $packageName, processName $processName")
}
override fun afterApplicationOnCreate(
packageName: String?,
processName: String?,
application: Application?,
userId: Int
) {
Log.d(TAG, "afterApplicationOnCreate: pkg $packageName, processName $processName")
// RockerManager.init(application,userId)
}
})
}
fun attachBaseContext(context: Context) {
BlackBoxCore.get().doAttachBaseContext(context, object : ClientConfiguration() {
override fun getHostPackageName(): String {
return context.packageName
}
override fun isHideRoot(): Boolean {
return mHideRoot
}
override fun isHideXposed(): Boolean {
return mHideXposed
}
override fun isEnableDaemonService(): Boolean {
return mDaemonEnable
}
override fun requestInstallPackage(file: File?, userId: Int): Boolean {
val packageInfo =
context.packageManager.getPackageArchiveInfo(file!!.absolutePath, 0)
return false
}
})
}
fun doOnCreate(context: Context) {
BlackBoxCore.get().doCreate()
}
companion object {
val TAG: String = BlackBoxLoader::class.java.simpleName
}
} | 0 | Java | 2 | 2 | d076a60a30bfe1c2070420e102623b149eae172b | 12,049 | BlackBox | Apache License 2.0 |
editor/src/main/com/mbrlabs/mundus/editor/core/helperlines/HelperLineShape.kt | study-game-engines | 661,136,846 | true | {"INI": 2, "YAML": 2, "Gradle": 5, "Shell": 1, "XML": 3, "SVG": 1, "Markdown": 4, "Batchfile": 1, "Text": 1, "Ignore List": 1, "JSON": 2, "Java": 212, "Kotlin": 167, "GLSL": 17, "Wavefront Material": 2, "Wavefront Object": 1, "Unity3D Asset": 1} | /*
* Copyright (c) 2023. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.core.helperlines
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Mesh
import com.badlogic.gdx.graphics.VertexAttribute
import com.badlogic.gdx.graphics.VertexAttributes
import com.badlogic.gdx.graphics.g3d.Material
import com.badlogic.gdx.graphics.g3d.ModelInstance
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute
import com.badlogic.gdx.graphics.g3d.model.MeshPart
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.Pool
import com.mbrlabs.mundus.commons.scene3d.components.TerrainComponent
import com.mbrlabs.mundus.commons.terrain.Terrain
abstract class HelperLineShape(val width: Int,
val counterOffsetX: Int,
val counterOffsetY: Int,
val terrainComponent: TerrainComponent) : Disposable {
companion object {
val helperLineCenterObjectPool = object : Pool<HelperLineCenterObject>() {
override fun newObject(): HelperLineCenterObject = HelperLineCenterObject()
}
val tmpV3 = Vector3()
}
val mesh: Mesh
val modelInstance: ModelInstance
val centerOfHelperObjects: Array<HelperLineCenterObject>
init {
val attribs = VertexAttributes(
VertexAttribute.Position(),
VertexAttribute.Normal(),
VertexAttribute(VertexAttributes.Usage.Tangent, 4, ShaderProgram.TANGENT_ATTRIBUTE),
VertexAttribute.TexCoords(0)
)
val terrain = terrainComponent.terrainAsset.terrain
val numVertices = terrain.vertexResolution * terrain.vertexResolution
val numIndices = calculateIndicesNum(width, terrain)
mesh = Mesh(true, numVertices, numIndices, attribs)
val indices = buildIndices(width, numIndices, terrain)
val material = Material(ColorAttribute.createDiffuse(Color.RED))
mesh.setIndices(indices)
mesh.setVertices(terrain.vertices)
val meshPart = MeshPart(null, mesh, 0, numIndices, GL20.GL_LINES)
meshPart.update()
val mb = ModelBuilder()
mb.begin()
mb.part(meshPart, material)
val model = mb.end()
modelInstance = ModelInstance(model)
modelInstance.transform = terrainComponent.modelInstance.transform
centerOfHelperObjects = calculateCenterOfHelperObjects()
}
abstract fun calculateIndicesNum(width: Int, terrain: Terrain): Int
abstract fun fillIndices(width: Int, indices: ShortArray, vertexResolution: Int)
abstract fun calculateCenterOfHelperObjects(): Array<HelperLineCenterObject>
fun updateVertices() {
mesh.setVertices(terrainComponent.terrainAsset.terrain.vertices)
}
fun findNearestCenterObject(pos: Vector3): HelperLineCenterObject {
var nearest = centerOfHelperObjects.first()
var nearestDistance = pos.dst(nearest.position.x, 0f, nearest.position.z)
for (helperLineCenterObject in centerOfHelperObjects) {
val distance = pos.dst(helperLineCenterObject.position.x, 0f, helperLineCenterObject.position.z)
if (distance < nearestDistance) {
nearest = helperLineCenterObject
nearestDistance = distance
}
}
return nearest
}
private fun buildIndices(width: Int, numIndices: Int, terrain: Terrain): ShortArray {
val indices = ShortArray(numIndices)
val vertexResolution = terrain.vertexResolution
fillIndices(width, indices, vertexResolution)
return indices
}
override fun dispose() {
while (centerOfHelperObjects.notEmpty()) {
helperLineCenterObjectPool.free(centerOfHelperObjects.removeIndex(0))
}
modelInstance.model!!.dispose()
}
}
| 0 | Java | 0 | 1 | 007d14af3f0389594f8ad3cedf488032f994e4ee | 4,676 | mundus | Apache License 2.0 |
app/src/main/java/pl/mg6/likeornot/Status.kt | mg6maciej | 81,643,752 | false | {"Gradle": 3, "INI": 2, "Shell": 7, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 28, "XML": 10, "Java": 1, "JSON": 1} | package pl.mg6.likeornot
import android.support.annotation.DrawableRes
enum class Status(@DrawableRes val imageId: Int) {
REALLY_LIKE(R.drawable.really_like),
LIKE(R.drawable.like),
MEH(R.drawable.meh),
DONT_LIKE(R.drawable.dont_like),
HATE(R.drawable.hate),
}
| 0 | Kotlin | 1 | 4 | bc19e74dd9c7ef17174eec2097fe7d50540828d8 | 284 | fluffy-octo-rotary-phone | Apache License 2.0 |
idea/testData/completion/basic/common/ExtensionInsideFunction.kt | pjvds | 11,950,273 | true | {"Markdown": 16, "XML": 473, "Ant Build System": 7, "YAML": 1, "Ignore List": 7, "Maven POM": 26, "Kotlin": 5846, "Java": 3201, "CSS": 10, "Java Properties": 10, "Gradle": 8, "Shell": 7, "Batchfile": 7, "INI": 4, "JavaScript": 47, "HTML": 42, "Text": 649, "Roff": 53, "Roff Manpage": 8, "JFlex": 3, "Makefile": 1, "JAR Manifest": 1} | class StrSome {
class StrOther
fun more() {
class StrInFun
fun Str<caret>
}
}
class StrMore {
class StrAbsent
}
// TIME: 1
// EXIST: String~(jet)
// EXIST: StrSome
// EXIST: StrMore
// EXIST: StrInFun
// EXIST_JAVA_ONLY: StringBuilder
// EXIST_JAVA_ONLY: StringBuffer
// ABSENT: StrAbsent | 0 | Java | 0 | 0 | aa16f0f0e8aa839cf13d07fb717df2dacf0f8082 | 308 | kotlin | Apache License 2.0 |
dsl/camel-kotlin-api/src/generated/kotlin/org/apache/camel/kotlin/components/GoogleFunctionsUriDsl.kt | orpiske | 166,656,227 | true | {"Text": 251, "Git Config": 1, "XML": 1790, "Batchfile": 4, "Shell": 21, "YAML": 70, "Maven POM": 593, "JSON": 2573, "Dockerfile": 5, "Markdown": 26, "Ignore List": 19, "Groovy": 164, "Git Attributes": 1, "Java": 21665, "Java Properties": 1066, "AsciiDoc": 1315, "INI": 22, "HTML": 151, "CSS": 2, "JavaScript": 32, "XSLT": 61, "OASv3-yaml": 8, "OASv3-json": 20, "OASv2-json": 6, "OASv2-yaml": 1, "Protocol Buffer": 5, "ASN.1": 1, "Thrift": 2, "SQL": 38, "GraphQL": 4, "Fluent": 9, "Public Key": 16, "Jsonnet": 2, "TOML": 2, "Rust": 1, "Apex": 3, "Erlang": 1, "Tcl": 5, "Mustache": 7, "XQuery": 5, "Ruby": 1, "RobotFramework": 7, "JAR Manifest": 47, "SVG": 2, "Kotlin": 497} | /*
* 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 org.apache.camel.kotlin.components
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import org.apache.camel.kotlin.CamelDslMarker
import org.apache.camel.kotlin.UriDsl
/**
* Manage and invoke Google Cloud Functions
*/
public fun UriDsl.`google-functions`(i: GoogleFunctionsUriDsl.() -> Unit) {
GoogleFunctionsUriDsl(this).apply(i)
}
@CamelDslMarker
public class GoogleFunctionsUriDsl(
it: UriDsl,
) {
private val it: UriDsl
init {
this.it = it
this.it.component("google-functions")
}
private var functionName: String = ""
/**
* The user-defined name of the function
*/
public fun functionName(functionName: String) {
this.functionName = functionName
it.url("$functionName")
}
/**
* Service account key to authenticate an application as a service account
*/
public fun serviceAccountKey(serviceAccountKey: String) {
it.property("serviceAccountKey", serviceAccountKey)
}
/**
* The Google Cloud Location (Region) where the Function is located
*/
public fun location(location: String) {
it.property("location", location)
}
/**
* The operation to perform on the producer.
*/
public fun operation(operation: String) {
it.property("operation", operation)
}
/**
* Specifies if the request is a pojo request
*/
public fun pojoRequest(pojoRequest: String) {
it.property("pojoRequest", pojoRequest)
}
/**
* Specifies if the request is a pojo request
*/
public fun pojoRequest(pojoRequest: Boolean) {
it.property("pojoRequest", pojoRequest.toString())
}
/**
* The Google Cloud Project name where the Function is located
*/
public fun project(project: String) {
it.property("project", project)
}
/**
* Whether the producer should be started lazy (on the first message). By starting lazy you can
* use this to allow CamelContext and routes to startup in situations where a producer may otherwise
* fail during starting and cause the route to fail being started. By deferring this startup to be
* lazy then the startup failure can be handled during routing messages via Camel's routing error
* handlers. Beware that when the first message is processed then creating and starting the producer
* may take a little time and prolong the total processing time of the processing.
*/
public fun lazyStartProducer(lazyStartProducer: String) {
it.property("lazyStartProducer", lazyStartProducer)
}
/**
* Whether the producer should be started lazy (on the first message). By starting lazy you can
* use this to allow CamelContext and routes to startup in situations where a producer may otherwise
* fail during starting and cause the route to fail being started. By deferring this startup to be
* lazy then the startup failure can be handled during routing messages via Camel's routing error
* handlers. Beware that when the first message is processed then creating and starting the producer
* may take a little time and prolong the total processing time of the processing.
*/
public fun lazyStartProducer(lazyStartProducer: Boolean) {
it.property("lazyStartProducer", lazyStartProducer.toString())
}
/**
* The client to use during service invocation.
*/
public fun client(client: String) {
it.property("client", client)
}
}
| 0 | Java | 1 | 1 | 30bcf8b84555a952d5122db74f1aff57762946cc | 4,156 | camel | Apache License 2.0 |
idea-plugin/src/main/kotlin/com/chutneytesting/idea/runner/ChutneyJsonToTestEventConverter.kt | owerfelli | 791,217,559 | true | {"Markdown": 64, "Batchfile": 2, "Shell": 2, "Gradle Kotlin DSL": 6, "INI": 5, "Java": 984, "HTML": 64, "JavaScript": 6, "Kotlin": 241, "SQL": 4, "Java Properties": 1, "Dockerfile": 3, "CSS": 1, "TypeScript": 250} | package com.chutneytesting.idea.runner
import com.chutneytesting.idea.ChutneyUtil
import com.chutneytesting.idea.server.ChutneyServer
import com.chutneytesting.idea.server.ChutneyServerRegistry
import com.chutneytesting.idea.util.WaitUntilUtils
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.testframework.TestConsoleProperties
import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter
import com.intellij.json.JsonFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.compiler.CompilerManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.task.ProjectTaskManager
import com.intellij.testFramework.LightVirtualFile
import java.util.concurrent.TimeUnit
fun moduleIsUpToDate(module: Module): Boolean {
val compilerManager = CompilerManager.getInstance(module.project)
val compilerScope = compilerManager.createModuleCompileScope(module, true)
return compilerManager.isUpToDate(compilerScope)
}
class ChutneyJsonToTestEventConverter(
testFrameworkName: String,
consoleProperties: TestConsoleProperties,
val configuration: ChutneyRunConfiguration,
val project: Project,
val processHandler: ProcessHandler,
val jsonFiles: List<VirtualFile?>
) : OutputToGeneralTestEventsConverter(testFrameworkName, consoleProperties) {
companion object{
private val LOG = Logger.getInstance(OutputToGeneralTestEventsConverter::class.java)
}
override fun onStartTesting() {
ApplicationManager.getApplication().executeOnPooledThread {
val server = ChutneyServerRegistry.instance.myServer
WaitUntilUtils.waitUntil({ getServerUrl(server) != null }, 60000)
//processHandler.startNotify()
val cacheEvaluation = mutableMapOf<Int, Any>()
jsonFiles.filterNotNull().forEachIndexed { index, virtualFile ->
if (ChutneyUtil.isChutneyDsl(virtualFile)) {
//ProjectTaskManager.getInstance(project).build(ModuleUtil.findModuleForFile(virtualFile, project)).blockingGet(60)
val module = ModuleUtil.findModuleForFile(virtualFile, project) ?: error("cannot find module")
if (!moduleIsUpToDate(module = module)) {
ProjectTaskManager.getInstance(project).build(module).blockingGet(60, TimeUnit.SECONDS)
}
val script = """
import com.chutneytesting.kotlin.dsl.*
${configuration.getRunSettings().methodName}()
""".trimIndent()
LOG.info("evaluating script = $script")
val eval =
ChutneyKotlinJsr223JvmLocalScriptEngineFactory(virtualFile, project).scriptEngine.eval(
script
)
cacheEvaluation[index] = eval
if (eval is List<*>) {
eval.forEachIndexed { s_index, any ->
val lightVirtualFile = LightVirtualFile("test.chutney.json", JsonFileType.INSTANCE, "$any")
val parser =
JsonTestScenariosParser(configuration, project, processHandler, lightVirtualFile)
parser.parseScenarios(s_index + 1)
}
} else {
val lightVirtualFile = LightVirtualFile("test.chutney.json", JsonFileType.INSTANCE, "$eval")
val parser = JsonTestScenariosParser(configuration, project, processHandler, lightVirtualFile)
parser.parseScenarios(index + 1)
}
} else {
val parser = JsonTestScenariosParser(configuration, project, processHandler, virtualFile)
parser.parseScenarios(index + 1)
}
}
jsonFiles.filterNotNull().forEachIndexed { index, virtualFile ->
if (ChutneyUtil.isChutneyDsl(virtualFile)) {
val eval = cacheEvaluation.get(index)
if (eval is List<*>) {
eval.forEachIndexed { s_index, any ->
val lightVirtualFile = LightVirtualFile("test.chutney.json", JsonFileType.INSTANCE, "$any")
val parser = JsonTestReportsParser(
configuration,
project,
getServerUrl(ChutneyServerRegistry.instance.myServer)!!,
processHandler,
lightVirtualFile
)
parser.parseReports(s_index + 1)
}
} else {
val lightVirtualFile = LightVirtualFile("test.chutney.json", JsonFileType.INSTANCE, "$eval")
val parser = JsonTestReportsParser(
configuration,
project,
getServerUrl(ChutneyServerRegistry.instance.myServer)!!,
processHandler,
lightVirtualFile
)
parser.parseReports(index + 1)
}
} else {
val parser = JsonTestReportsParser(
configuration,
project,
getServerUrl(ChutneyServerRegistry.instance.myServer)!!,
processHandler,
virtualFile
)
parser.parseReports(index + 1)
}
}
processHandler.detachProcess()
}
}
private fun getServerUrl(ideServer: ChutneyServer?): String? {
if (configuration.getRunSettings().isExternalServerType()) {
return configuration.getRunSettings().serverAddress
}
return if (ideServer != null && ideServer.isReadyForRunningTests) {
ideServer.serverUrl
} else null
}
}
| 0 | null | 0 | 0 | a7b0bf69921fd29f846763ba4e67e271dbfaad13 | 6,450 | chutney | Apache License 2.0 |
src/main/java/com/pharmacy/controllers/UserController.kt | Paul-Harold | 579,331,994 | true | {"Markdown": 1, "Kotlin": 18, "Java": 14, "INI": 1, "SQL": 1} | package com.pharmacy.controllers
import com.pharmacy.database.DatabaseInstance
import com.pharmacy.models.UserModel
import com.pharmacy.utils.EncryptionUtils
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Statement
import javax.swing.JOptionPane
class UserController(private var logId: Int) {
private var connection: Connection? = null
private var statement: Statement? = null
init {
try {
connection = DatabaseInstance().getConnection()
statement = connection!!.createStatement()
} catch (e: SQLException) {
throw SQLException(e)
}
}
val users: ResultSet?
get() {
val resultSet: ResultSet?
try {
val query = "SELECT id, name, username, phone, user_type FROM users"
resultSet = statement!!.executeQuery(query)
} catch (e: SQLException) {
throw SQLException(e)
}
return resultSet
}
// Methods to add new user
fun addUser(userModel: UserModel) {
val resultSet: ResultSet?
try {
val duplicateQuery = """
SELECT * FROM users
WHERE name=?
AND phone=?
AND user_type=?
""".trimIndent()
val duplicateStatement = connection!!.prepareStatement(duplicateQuery)
duplicateStatement.setString(1, userModel.name)
duplicateStatement.setString(2, userModel.phone)
duplicateStatement.setString(3, userModel.type)
resultSet = duplicateStatement.executeQuery()
if (resultSet!!.next()) {
JOptionPane.showMessageDialog(null, "User already exists")
} else {
val encryptionUtils = EncryptionUtils()
val secretKey = encryptionUtils.generateKeyBytes()
val insertQuery = """
INSERT INTO users (name,phone,username,password,user_type,secret_key)
VALUES(?,?,?,?,?,?);
""".trimIndent()
val prepStatement: PreparedStatement = connection!!.prepareStatement(insertQuery)
prepStatement.setString(1, userModel.name)
prepStatement.setString(2, userModel.phone)
prepStatement.setString(3, userModel.username)
prepStatement.setBytes(4, encryptionUtils.encrypt(userModel.password!!, secretKey))
prepStatement.setString(5, userModel.type)
prepStatement.setBytes(6, secretKey)
prepStatement.executeUpdate()
LogsController().addLogEntry(
logId,
"Added new user: ${userModel.name} (${userModel.username})"
)
}
} catch (e: SQLException) {
throw SQLException(e)
}
}
/**
* Update existing user (password excluded!)
* See [.updatePass] for updating password
*
* @param userModel populated UserModel
*/
fun updateUser(userModel: UserModel) {
try {
val query = "UPDATE users SET username=?,name=?,phone=?,user_type=? WHERE id=?"
val prepStatement: PreparedStatement = connection!!.prepareStatement(query)
prepStatement.setString(1, userModel.username)
prepStatement.setString(2, userModel.name)
prepStatement.setString(3, userModel.phone)
prepStatement.setString(4, userModel.type)
prepStatement.setInt(5, userModel.id!!)
prepStatement.executeUpdate()
LogsController().addLogEntry(
logId,
"Updated user: ${userModel.name} (${userModel.username})"
)
} catch (e: SQLException) {
throw SQLException(e)
}
}
// Method to delete existing user
fun deleteUser(id: Int, username: String) {
try {
val query = "DELETE FROM users WHERE id=?"
val prepStatement: PreparedStatement = connection!!.prepareStatement(query)
prepStatement.setInt(1, id)
prepStatement.executeUpdate()
LogsController().addLogEntry(logId, "Deleted user: $username")
} catch (e: SQLException) {
throw SQLException(e)
}
}
fun searchUsers(search: String): ResultSet? {
val resultSet: ResultSet?
try {
val query = """
SELECT id, name, username, phone, user_type
FROM users
WHERE name LIKE ?
OR username LIKE ?
OR phone LIKE ?
OR user_type LIKE ?;
""".trimIndent()
val prepStatement: PreparedStatement = connection!!.prepareStatement(query)
prepStatement.setString(1, "%$search%")
prepStatement.setString(2, "%$search%")
prepStatement.setString(3, "%$search%")
prepStatement.setString(4, "%$search%")
resultSet = prepStatement.executeQuery()
} catch (e: SQLException) {
throw SQLException(e)
}
return resultSet
}
fun getUserId(username: String): Int {
val resultSet: ResultSet?
var id = 0
try {
val q = """
SELECT id
FROM users
WHERE username=?
""".trimIndent()
val prepStatement: PreparedStatement = connection!!.prepareStatement(q)
prepStatement.setString(1, username)
resultSet = prepStatement.executeQuery()
if (resultSet!!.next()) {
id = resultSet.getInt("id")
}
} catch (e: SQLException) {
throw SQLException(e)
}
return id
}
fun findUser(username: String): ResultSet? {
val resultSet: ResultSet?
try {
val q = """
SELECT id, username, name, phone, user_type
FROM users
WHERE username=?
""".trimIndent()
val prepStatement: PreparedStatement = connection!!.prepareStatement(q)
prepStatement.setString(1, username)
resultSet = prepStatement.executeQuery()
} catch (e: SQLException) {
throw SQLException(e)
}
return resultSet
}
fun matchPasswords(username: String, password: String): Boolean {
val resultSet: ResultSet?
try {
val q = """
SELECT password, secret_key
FROM users
WHERE username=?
""".trimIndent()
val prepStatement: PreparedStatement = connection!!.prepareStatement(q)
prepStatement.setString(1, username)
resultSet = prepStatement.executeQuery()
if (resultSet!!.next()) {
val secretKey = resultSet.getBytes("secret_key")
val encryptedPassword = resultSet.getBytes("password")
val decryptedPass = EncryptionUtils().decrypt(encryptedPassword, secretKey)
return decryptedPass == password
}
} catch (e: SQLException) {
throw SQLException(e)
}
return false
}
fun updatePass(id: Int, username: String, password: String?) {
try {
// encryption
val encryptionUtils = EncryptionUtils()
val secretKey = encryptionUtils.generateKeyBytes()
val encryptedPass = encryptionUtils.encrypt(password!!, secretKey)
// db query
val query = "UPDATE users SET password=?, secret_key=? WHERE id=?"
val prepStatement: PreparedStatement = connection!!.prepareStatement(query)
prepStatement.setBytes(1, encryptedPass)
prepStatement.setBytes(2, secretKey)
prepStatement.setInt(3, id)
prepStatement.executeUpdate()
LogsController().addLogEntry(logId, "Password updated for user: $username")
} catch (e: SQLException) {
throw SQLException(e)
}
}
}
| 0 | null | 0 | 0 | dba07143d1505f7495b4be6bcdbc996176f66f71 | 8,274 | DD-Pharmacy | MIT License |
fxgl-achievement/src/main/kotlin/com/almasb/fxgl/achievement/AchievementManager.kt | shareef-ragab | 187,150,772 | true | {"Markdown": 5, "Kotlin": 223, "Java": 237, "Java Properties": 7, "CSS": 4, "JavaScript": 11, "Shell": 1} | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (<EMAIL>).
* See LICENSE for details.
*/
package com.almasb.fxgl.achievement
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.Inject
import com.almasb.fxgl.core.collection.PropertyChangeListener
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.sslogger.Logger
import javafx.collections.FXCollections
import javafx.collections.ObservableList
/**
* Responsible for registering and updating achievements.
*
* @author <NAME> (AlmasB) (<EMAIL>)
*/
class AchievementManager : EngineService {
private val log = Logger.get(javaClass)
@Inject("achievementStores")
private lateinit var achievementStores: List<AchievementStore>
private val achievements = FXCollections.observableArrayList<Achievement>()
private val achievementsReadOnly by lazy { FXCollections.unmodifiableObservableList(achievements) }
/**
* Registers achievement in the system.
* Note: this method can only be called from initAchievements() to function properly.
*
* @param a the achievement
*/
fun registerAchievement(a: Achievement) {
require(achievements.none { it.name == a.name }) {
"Achievement with name [${a.name}] exists"
}
achievements.add(a)
log.debug("Registered new achievement: ${a.name}")
}
/**
* @param name achievement name
* @return registered achievement
* @throws IllegalArgumentException if achievement is not registered
*/
fun getAchievementByName(name: String): Achievement {
return achievements.find { it.name == name }
?: throw IllegalArgumentException("Achievement with name [$name] is not registered!")
}
/**
* @return unmodifiable list of achievements
*/
fun getAchievements(): ObservableList<Achievement> = achievementsReadOnly
override fun onMainLoopStarting() {
achievementStores.forEach { it.initAchievements(this) }
// TODO: cleanup
achievements.forEach {
when(it.varValue) {
is Int -> {
var listener: PropertyChangeListener<Int>? = null
listener = object : PropertyChangeListener<Int> {
var halfReached = false
override fun onChange(prev: Int, now: Int) {
if (!halfReached && now >= it.varValue / 2) {
halfReached = true
//FXGL.getEventBus().fireEvent(AchievementProgressEvent(it, now.toDouble(), it.varValue.toDouble()))
}
if (now >= it.varValue) {
it.setAchieved()
//FXGL.getEventBus().fireEvent(AchievementEvent(AchievementEvent.ACHIEVED, it))
//FXGL.getApp().gameState.removeListener(it.varName, listener!!)
}
}
}
//FXGL.getApp().gameState.addListener<Int>(it.varName, listener)
}
is Double -> {
var listener: PropertyChangeListener<Double>? = null
listener = object : PropertyChangeListener<Double> {
var halfReached = false
override fun onChange(prev: Double, now: Double) {
if (!halfReached && now >= it.varValue / 2) {
halfReached = true
//FXGL.getEventBus().fireEvent(AchievementProgressEvent(it, now, it.varValue))
}
if (now >= it.varValue) {
it.setAchieved()
//FXGL.getEventBus().fireEvent(AchievementEvent(AchievementEvent.ACHIEVED, it))
//FXGL.getApp().gameState.removeListener(it.varName, listener!!)
}
}
}
//FXGL.getApp().gameState.addListener<Double>(it.varName, listener)
}
is Boolean -> {
var listener: PropertyChangeListener<Boolean>? = null
listener = object : PropertyChangeListener<Boolean> {
override fun onChange(prev: Boolean, now: Boolean) {
if (now) {
it.setAchieved()
//FXGL.getEventBus().fireEvent(AchievementEvent(AchievementEvent.ACHIEVED, it))
//FXGL.getApp().gameState.removeListener(it.varName, listener!!)
}
}
}
//FXGL.getApp().gameState.addListener<Boolean>(it.varName, listener)
}
else -> throw IllegalArgumentException("Unknown value type for achievement: " + it.varValue)
}
}
}
override fun onExit() {
}
override fun onUpdate(tpf: Double) {
}
override fun write(bundle: Bundle) {
// log.debug("Saving data to profile")
//
// val bundle = Bundle("achievement")
//
// achievements.forEach { a -> bundle.put(a.name, a.isAchieved) }
// bundle.log()
//
// profile.putBundle(bundle)
}
override fun read(bundle: Bundle) {
// log.debug("Loading data from profile")
//
// val bundle = profile.getBundle("achievement")
// bundle.log()
//
// achievements.forEach { a ->
// val achieved = bundle.get<Boolean>(a.name)
// if (achieved)
// a.setAchieved()
// }
}
} | 0 | Java | 0 | 0 | 5b374d5d2183ec1a5adbf9c8008cde8811f781cb | 5,858 | FXGL | MIT License |
src/dorkbox/console/output/AnsiRenderWriter.kt | dorkbox | 25,707,709 | false | {"Gradle Kotlin DSL": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 27, "INI": 1, "Java": 9} | /*
* Copyright 2023 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2009 the original author(s).
*
* 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 dorkbox.console.output
import java.io.OutputStream
import java.io.PrintWriter
import java.io.Writer
import java.util.*
/**
* Print writer which supports automatic ANSI color rendering via [AnsiRenderer].
*
* @author [Jason Dillon](mailto:[email protected])
* @author [Hiram Chirino](http://hiramchirino.com)
*/
class AnsiRenderWriter : PrintWriter {
constructor(out: OutputStream) : super(out)
constructor(out: OutputStream, autoFlush: Boolean) : super(out, autoFlush)
constructor(out: Writer) : super(out)
constructor(out: Writer, autoFlush: Boolean) : super(out, autoFlush)
override fun write(s: String) {
if (s.contains(AnsiRenderer.BEGIN_TOKEN)) {
super.write(AnsiRenderer.render(s))
}
else {
super.write(s)
}
}
override fun format(format: String, vararg args: Any): PrintWriter {
flush() // prevents partial output from being written while formatting or we will get rendering exceptions
print(String.format(format, *args))
return this
}
override fun format(l: Locale, format: String, vararg args: Any): PrintWriter {
flush() // prevents partial output from being written while formatting or we will get rendering exceptions
print(String.format(l, format, *args))
return this
}
}
| 1 | null | 1 | 1 | 30b800de83d7cb06ecf33b0829120aea2c848e08 | 2,551 | Console | Creative Commons Zero v1.0 Universal |
platform/lang-impl/src/com/intellij/ide/workspace/configuration/NewWorkspaceWizard.kt | JetBrains | 2,489,216 | false | {"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.workspace.configuration
import com.intellij.icons.ExpUiIcons
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.*
import com.intellij.ide.wizard.NewProjectWizardChainStep.Companion.nextStep
import com.intellij.ide.wizard.comment.CommentNewProjectWizardStep
import com.intellij.ide.workspace.addToWorkspace
import com.intellij.ide.workspace.isWorkspaceSupportEnabled
import com.intellij.ide.workspace.setWorkspace
import com.intellij.lang.LangBundle
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.ui.dsl.builder.Align
import com.intellij.ui.dsl.builder.Panel
import org.jetbrains.annotations.Nls
import javax.swing.Icon
class NewWorkspaceWizard: GeneratorNewProjectWizard {
override val id: String = "jb.workspace"
override val name: @Nls(capitalization = Nls.Capitalization.Title) String = LangBundle.message("workspace.project.type.name")
override val icon: Icon = ExpUiIcons.Nodes.Workspace
override fun createStep(context: WizardContext): NewProjectWizardStep =
RootNewProjectWizardStep(context)
.nextStep(::CommentStep)
.nextStep { parent -> newProjectWizardBaseStepWithoutGap(parent).apply { defaultName = "workspace" } }
.nextStep(::GitNewProjectWizardStep)
.nextStep(::Step)
override fun isEnabled(): Boolean = isWorkspaceSupportEnabled
private class CommentStep(parent: NewProjectWizardStep) : CommentNewProjectWizardStep(parent) {
override val comment: @Nls(capitalization = Nls.Capitalization.Sentence) String =
LangBundle.message("workspace.project.type.comment")
}
private class Step(parent: NewProjectWizardStep) : AbstractNewProjectWizardStep(parent) {
private val subprojectList = SubprojectList(ProjectUtil.getActiveProject())
override fun setupUI(builder: Panel) {
builder.row {
cell(subprojectList.decoratorPanel).align(Align.FILL)
}
}
override fun setupProject(project: Project) {
setWorkspace(project)
StartupManager.getInstance(project).runAfterOpened {
addToWorkspace(project, subprojectList.projectPaths)
}
}
}
} | 1 | null | 1 | 1 | 0d546ea6a419c7cb168bc3633937a826d4a91b7c | 2,357 | intellij-community | Apache License 2.0 |
common/src/main/java/ink/anur/pojo/rpc/meta/RpcRequestMeta.kt | anurnomeru | 253,847,320 | false | {"Maven POM": 6, "Text": 1, "Ignore List": 1, "Markdown": 2, "Kotlin": 160, "Java Properties": 4, "Java": 19, "XML": 2} | package ink.anur.pojo.rpc.meta
import java.io.Serializable
/**
* Created by <NAME> on 2020/4/7
*
* 进行一个请求
*/
class RpcRequestMeta(
/**
* 请求时直接指定 bean 名字来 RPC_REQUEST,可以不指定
*/
val requestBean: String?,
/**
* 此请求的接口
*/
val requestInterface: String,
/**
* 此请求的方法唯一标志
*/
val requestMethodSign: String,
/**
* 此请求的参数
*/
val requestParams: Array<out Any>?,
/**
* 此请求的请求标志,用于区分回复
*/
val msgSign: Long) : Serializable | 1 | null | 1 | 1 | e4a8d8115ce62d829e7462664b3475640db98643 | 504 | Kanashi-RPC | MIT License |
database/database-symbol-processor/src/test/kotlin/ru/tinkoff/kora/database/symbol/processor/jdbc/repository/AllowedResultsRepository.kt | slutmaker | 577,901,564 | true | {"Java Properties": 1, "YAML": 7, "Gradle": 79, "Shell": 2, "EditorConfig": 1, "Markdown": 23, "Batchfile": 1, "Text": 2, "Ignore List": 1, "Java": 989, "Kotlin": 358, "XML": 7, "JSON": 17, "INI": 10, "SQL": 3, "OASv3-yaml": 6, "OASv2-yaml": 1, "Mustache": 31, "Protocol Buffer": 1, "JavaScript": 2, "CSS": 1} | package ru.tinkoff.kora.database.symbol.processor.jdbc.repository
import ru.tinkoff.kora.common.Mapping
import ru.tinkoff.kora.database.common.annotation.Query
import ru.tinkoff.kora.database.common.annotation.Repository
import ru.tinkoff.kora.database.jdbc.JdbcRepository
import ru.tinkoff.kora.database.symbol.processor.entity.TestEntity
import ru.tinkoff.kora.database.symbol.processor.jdbc.TestEntityJdbcRowMapper
import ru.tinkoff.kora.database.symbol.processor.jdbc.TestEntityJdbcRowMapperNonFinal
@Repository
interface AllowedResultsRepository : JdbcRepository {
@Query("INSERT INTO test(test) VALUES ('test')")
fun returnVoid()
@Query("SELECT test")
fun returnPrimitive(): Int
@Query("SELECT test")
fun returnObject(): Int?
@Query("SELECT test")
fun returnNullableObject(): Int?
@Query("SELECT test")
@Mapping(TestEntityJdbcRowMapper::class)
fun returnObjectWithRowMapper(): TestEntity?
@Query("SELECT test")
@Mapping(TestEntityJdbcRowMapperNonFinal::class)
fun returnObjectWithRowMapperNonFinal(): TestEntity?
@Query("SELECT test")
@Mapping(TestEntityJdbcRowMapper::class)
fun returnOptionalWithRowMapper(): TestEntity?
@Query("SELECT test")
@Mapping(TestEntityJdbcRowMapper::class)
fun returnListWithRowMapper(): List<TestEntity>
}
| 0 | Java | 0 | 0 | 9a95a718abe7d7f31c1ff5bab02ef0d34f807504 | 1,331 | kora | Apache License 2.0 |
extensions/leanback/src/main/java/com/google/android/exoplayer2/ext/leanback/package-info.kt | rezaulkhan111 | 589,317,131 | false | {"Java Properties": 1, "Gradle": 47, "Markdown": 91, "Shell": 6, "Batchfile": 1, "Text": 16, "Ignore List": 1, "XML": 480, "Java": 1191, "Kotlin": 302, "YAML": 6, "INI": 1, "JSON": 5, "HTML": 1519, "Ruby": 1, "SVG": 43, "JavaScript": 40, "SCSS": 81, "CSS": 5, "GLSL": 15, "Starlark": 1, "Protocol Buffer Text Format": 1, "Makefile": 9, "C++": 10, "CMake": 2} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ext.leanback
import com.google.android.exoplayer2.Player
import androidx.leanback.media.PlayerAdapter
import com.google.android.exoplayer2.util.ErrorMessageProvider
import com.google.android.exoplayer2.PlaybackException
import androidx.leanback.media.SurfaceHolderGlueHost
import androidx.leanback.media.PlaybackGlueHost
import com.google.android.exoplayer2.ext.leanback.LeanbackPlayerAdapter
import android.view.SurfaceHolder
import com.google.android.exoplayer2.Timeline
import com.google.android.exoplayer2.Player.TimelineChangeReason
import com.google.android.exoplayer2.Player.PositionInfo
import com.google.android.exoplayer2.Player.DiscontinuityReason
import com.google.android.exoplayer2.ExoPlayerLibraryInfo
| 1 | null | 1 | 1 | c467e918356f58949e0f7f4205e96f0847f1bcdb | 1,376 | ExoPlayer | Apache License 2.0 |
minicraft/lib/src/main/kotlin/minicraft/gl/RefCount.kt | dest1n1s | 695,841,317 | false | {"Java": 44583, "Kotlin": 18198, "GLSL": 934} | package minicraft.gl
interface Destroyable {
fun destroy()
}
interface Setupable {
fun setup()
}
class RefCount<T>(private val value: T) : Destroyable, Setupable
where T : Destroyable, T : Setupable {
private var refCount = 0
fun get(): T = value
override fun destroy() {
refCount--
if (refCount == 0) {
value.destroy()
}
}
override fun setup() {
refCount++
if (refCount == 1) {
value.setup()
}
}
} | 1 | null | 1 | 1 | c32cf4f57c07a970b266e5d7d5186ea1738e1c4d | 515 | zommie | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/koresframework/kores/bytecode/processor/processors/ForEachProcessor.kt | JonathanxD | 77,163,846 | false | {"Git Config": 1, "Gradle": 4, "YAML": 4, "Markdown": 4, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Java": 63, "Kotlin": 108} | /*
* Kores-BytecodeWriter - Translates Kores Structure to JVM Bytecode <https://github.com/JonathanxD/CodeAPI-BytecodeWriter>
*
* The MIT License (MIT)
*
* Copyright (c) 2021 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.koresframework.kores.bytecode.processor.processors
import com.koresframework.kores.Instructions
import com.koresframework.kores.Types
import com.koresframework.kores.base.*
import com.koresframework.kores.bytecode.processor.METHOD_VISITOR
import com.koresframework.kores.common.KoresNothing
import com.koresframework.kores.factory.*
import com.koresframework.kores.literal.Literals
import com.koresframework.kores.operator.Operators
import com.koresframework.kores.processor.Processor
import com.koresframework.kores.processor.ProcessorManager
import com.koresframework.kores.type
import com.github.jonathanxd.iutils.data.TypedData
import com.github.jonathanxd.iutils.kt.require
object ForEachProcessor : Processor<ForEachStatement> {
override fun process(
part: ForEachStatement,
data: TypedData,
processorManager: ProcessorManager<*>
) {
val mvHelper = METHOD_VISITOR.require(data)
val iterationType = part.iterationType
val stm = when (iterationType) {
IterationType.ARRAY -> {
val arrayName = mvHelper.getUniqueVariableName("\$array#")
val name = mvHelper.getUniqueVariableName("\$arrayIndex#")
val arrayVariable = variable(
modifiers = setOf(KoresModifier.FINAL),
type = part.iterableElement.type, name = arrayName, value = part.iterableElement
)
val indexVariable = variable(type = Types.INT, name = name, value = Literals.INT(0))
val accessArray = accessVariable(arrayVariable)
val arrayType = arrayVariable.type
ForStatement.Builder.builder()
.forInit(listOf(arrayVariable, indexVariable))
.forExpression(
check(
accessVariable(indexVariable),
Operators.LESS_THAN,
arrayLength(arrayType, accessArray)
)
)
.forUpdate(
listOf(
operateAndAssign(
indexVariable,
Operators.ADD,
Literals.INT(1)
)
)
)
.body(
Instructions.fromPart(
variable(
name = part.variable.name,
type = part.variable.type,
value = accessArrayValue(
arrayType = arrayType,
target = accessArray,
index = accessVariable(indexVariable),
valueType = part.variable.type
)
)
) + part.body
)
.build()
}
else -> {
val iterableType = iterationType.iteratorMethodSpec.localization
val iteratorType = iterationType.iteratorMethodSpec.typeSpec.returnType
val iteratorGetterName = iterationType.iteratorMethodSpec.methodName
val name = mvHelper.getUniqueVariableName("\$iteratorInstance#")
val iteratorVariable = variable(
type = iteratorType,
name = name,
value = invoke(
invokeType = InvokeType.get(iterableType),
localization = iterableType,
name = iteratorGetterName,
target = part.iterableElement,
spec = iterationType.iteratorMethodSpec.typeSpec,
arguments = emptyList()
)
)
ForStatement.Builder.builder()
.forInit(iteratorVariable)
.forExpression(
check(
invoke(
invokeType = InvokeType.get(iteratorType),
localization = iteratorType,
name = iterationType.hasNextName,
target = accessVariable(iteratorVariable),
spec = TypeSpec(Types.BOOLEAN),
arguments = emptyList()
),
Operators.EQUAL_TO,
Literals.TRUE
)
)
.forUpdate(KoresNothing)
.body(
Instructions.fromPart(
variable(
name = part.variable.name,
type = part.variable.type,
value = cast(
from = iterationType.nextMethodSpec.typeSpec.returnType,
to = part.variable.type,
part = invoke(
invokeType = InvokeType.get(iteratorType),
localization = iteratorType,
name = iterationType.nextMethodSpec.methodName,
target = accessVariable(iteratorVariable),
spec = iterationType.nextMethodSpec.typeSpec,
arguments = emptyList()
)
)
)
) + part.body
)
.build()
}
}
mvHelper.enterNewFrame()
processorManager.process(stm::class.java, stm, data)
mvHelper.exitFrame()
}
}
| 7 | Kotlin | 0 | 1 | 8324bd03a52ddf5f12dd54c8d7459f83a000ed9a | 7,610 | CodeAPI-BytecodeWriter | MIT License |
compiler/fir/java/src/org/jetbrains/kotlin/fir/java/scopes/JavaOverridabilityRules.kt | google | 219,902,853 | true | {"Markdown": 177, "Gradle": 404, "Gradle Kotlin DSL": 1123, "Java Properties": 30, "Shell": 43, "Ignore List": 21, "Batchfile": 21, "Git Attributes": 8, "JSON": 199, "XML": 803, "Kotlin": 54041, "INI": 194, "Java": 3633, "Text": 21765, "JavaScript": 315, "JAR Manifest": 2, "Roff": 256, "Roff Manpage": 52, "Protocol Buffer": 15, "Proguard": 14, "TOML": 1, "AsciiDoc": 1, "YAML": 8, "EditorConfig": 2, "OpenStep Property List": 22, "C": 210, "C++": 366, "LLVM": 1, "Pascal": 1, "Python": 3, "CMake": 2, "Objective-C++": 19, "Objective-C": 207, "Groovy": 10, "Dockerfile": 4, "Diff": 4, "EJS": 1, "CSS": 6, "HTML": 11, "Swift": 128, "JSON with Comments": 60, "TypeScript": 8, "CODEOWNERS": 1, "JFlex": 2, "Graphviz (DOT)": 98, "Ant Build System": 32, "Dotenv": 5, "Maven POM": 77, "FreeMarker": 1, "Fluent": 2, "Ruby": 19, "Scala": 1} | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.java.scopes
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirCallableDeclaration
import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
import org.jetbrains.kotlin.fir.declarations.FirProperty
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.scopes.MemberWithBaseScope
import org.jetbrains.kotlin.fir.scopes.PlatformSpecificOverridabilityRules
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
import org.jetbrains.kotlin.fir.unwrapFakeOverrides
class JavaOverridabilityRules(session: FirSession) : PlatformSpecificOverridabilityRules {
// Note: return types (considerReturnTypeKinds) look not important when attempting intersection
// From the other side, they can break relevant tests like intersectionWithJavaVoidNothing.kt
// The similar case exists in bootstrap (see IrSimpleBuiltinOperatorDescriptorImpl)
private val javaOverrideChecker =
JavaOverrideChecker(session, JavaTypeParameterStack.EMPTY, baseScopes = null, considerReturnTypeKinds = false)
override fun isOverriddenFunction(overrideCandidate: FirSimpleFunction, baseDeclaration: FirSimpleFunction): Boolean? {
return if (shouldApplyJavaChecker(overrideCandidate, baseDeclaration)) {
// takeIf is questionable here (JavaOverrideChecker can forbid overriding, but it cannot allow it on own behalf)
// Known influenced tests: supertypeDifferentParameterNullability.kt became partially green without it
javaOverrideChecker.isOverriddenFunction(overrideCandidate, baseDeclaration).takeIf { !it }
} else {
null
}
}
override fun isOverriddenProperty(overrideCandidate: FirCallableDeclaration, baseDeclaration: FirProperty): Boolean? {
return if (shouldApplyJavaChecker(overrideCandidate, baseDeclaration)) {
javaOverrideChecker.isOverriddenProperty(overrideCandidate, baseDeclaration)
} else {
null
}
}
private fun shouldApplyJavaChecker(overrideCandidate: FirCallableDeclaration, baseDeclaration: FirCallableDeclaration): Boolean {
// One candidate with Java original is enough to apply Java checker,
// otherwise e.g. primitive type comparisons do not work.
return overrideCandidate.isOriginallyFromJava() || baseDeclaration.isOriginallyFromJava()
}
private fun FirCallableDeclaration.isOriginallyFromJava(): Boolean = unwrapFakeOverrides().origin == FirDeclarationOrigin.Enhancement
override fun <D : FirCallableSymbol<*>> chooseIntersectionVisibility(
extractedOverrides: Collection<MemberWithBaseScope<D>>,
dispatchClassSymbol: FirRegularClassSymbol?,
): Visibility = javaOverrideChecker.chooseIntersectionVisibility(extractedOverrides, dispatchClassSymbol)
}
| 1 | Kotlin | 51 | 152 | e302420197acfd51c6ffe53866d69fcb5b2bb5c7 | 3,284 | kotlin | Apache License 2.0 |
library/src/main/java/com/alamkanak/weekview/DrawingContext.kt | GeekInCompany | 170,145,948 | false | {"INI": 3, "Markdown": 2, "Gradle": 4, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 3, "Java Properties": 1, "Proguard": 2, "XML": 13, "Java": 19, "Kotlin": 26} | package com.alamkanak.weekview
import java.lang.Math.ceil
import java.util.*
import java.util.Calendar.DATE
class DrawingContext(
val dateRange: List<Calendar>,
val startPixel: Float
) {
/**
* Returns the actually visible date range. This can be different from [dateRange] if the user
* is currently scrolling.
*
* @param firstVisibleDate The first visible date
* @param config The [WeekViewConfig]
*
* @return The list of currently visible dates
*/
fun getVisibleDateRange(firstVisibleDate: Calendar, config: WeekViewConfig): List<Calendar> {
val result = dateRange as MutableList
val isScrolling = config.drawingConfig.currentOrigin.x % config.totalDayWidth != 0f
if (isScrolling) {
// If the user is scrolling, a new view becomes partially visible
val lastVisibleDay = firstVisibleDate.clone() as Calendar
lastVisibleDay.add(DATE, config.numberOfVisibleDays)
dateRange.add(lastVisibleDay)
}
return result
}
fun getDateRangeWithStartPixels(config: WeekViewConfig): List<Pair<Calendar, Float>> {
return dateRange.zip(getStartPixels(config))
}
fun getStartPixels(config: WeekViewConfig): List<Float> {
val results = mutableListOf<Float>()
results.add(startPixel)
var currentStartPixel = startPixel
for (day in dateRange) {
if (config.isSingleDay) {
// Add a margin at the start if we're in day view. Otherwise, screen space is too
// precious and we refrain from doing so.
currentStartPixel += config.eventMarginHorizontal.toFloat()
}
// In the next iteration, start from the next day.
currentStartPixel += config.totalDayWidth
results.add(currentStartPixel)
}
return results
}
companion object {
@JvmStatic
fun create(config: WeekViewConfig): DrawingContext {
val drawConfig = config.drawingConfig
val totalDayWidth = config.totalDayWidth
val leftDaysWithGaps = (ceil((drawConfig.currentOrigin.x / totalDayWidth).toDouble()) * -1).toInt()
val startPixel = (drawConfig.currentOrigin.x
+ totalDayWidth * leftDaysWithGaps
+ drawConfig.timeColumnWidth)
val start = leftDaysWithGaps + 1
val end = start + config.numberOfVisibleDays + 1
val dayRange = DateUtils.getDateRange(start, end)
return DrawingContext(dayRange, startPixel)
}
}
}
| 1 | null | 1 | 1 | 1562da71b9964fcdcf75350444231d91b0038246 | 2,650 | Android-Week-View | Apache License 2.0 |
server/src/main/java/org/apollo/plugins/location/tutorial/rsguide/chat/Chat1a.kt | zeruth | 798,108,985 | false | {"Gradle Kotlin DSL": 6, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Java": 509, "Java Properties": 1, "Kotlin": 55, "XML": 8} | package org.apollo.plugins.location.tutorial.rsguide.chat
import org.apollo.game.model.entity.Npc
import org.apollo.game.model.entity.Player
import org.apollo.plugins.api.ChatEmotes
import org.apollo.plugins.api.dialogue.ChatNpcAction
import org.apollo.plugins.api.dialogue.DialogueResponse
class Chat1a(npc: Npc) : DialogueResponse(npc) {
override fun send(player: Player) {
ChatNpcAction.start(player, npc.position) {
player.sendNpc2Dialogue(
npc, ChatEmotes.DEFAULT,
"You have already learnt the first thing needed to",
"succeed in this world... Talking to other people!", this
)
}
}
override fun continued(player: Player) {
Chat2(npc).send(player)
}
} | 0 | Java | 0 | 0 | c12728852fab22676cf79a8559adb4f99ffb4ba0 | 770 | nulled-377 | BSD Zero Clause License |
cms-bl/src/main/kotlin/com/github/knextsunj/cms/service/validation/impl/CountryValidationServiceImpl.kt | knextsunj | 662,745,409 | false | {"Java": 33791, "Kotlin": 24980} | package com.github.knextsunj.cms.service.validation.impl
import com.github.knextsunj.cms.domain.Country
import com.github.knextsunj.cms.repository.CountryRepository
import com.github.knextsunj.cms.service.validation.GenericValidationService
import com.github.knextsunj.cms.util.CmsUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
@Component("countryValidationService")
open class CountryValidationServiceImpl:GenericValidationService {
@Autowired
open lateinit var countryRepository: CountryRepository
override fun deDup(name: String?): Boolean? {
var country: Country? = countryRepository.findByName(name);
return CmsUtil.isNull(country);
}
} | 1 | null | 1 | 1 | 0f402e9e8885a6480104e26ca072e1692717fb1b | 808 | cms-microservices | Apache License 2.0 |
kotlin/src/main/kotlin/com/impassive/kotlin/basic/LearnException.kt | yangbiny | 548,708,667 | false | {"Gradle": 22, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 2, "Git Attributes": 1, "Markdown": 4, "Java": 134, "INI": 2, "Kotlin": 38, "Scala": 8} | package com.impassive.kotlin.basic
import com.impassive.kotlin.basic.Slf4j.Companion.log
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* @author impassive
*/
class LearnException {
fun test() {
try {
log.info("test")
} catch (e: Exception) {
log.error("exception : ", e)
}
}
}
class LoggerTester {
companion object {
val log: Logger = LoggerFactory.getLogger(LoggerTester::class.java)
}
}
fun main() {
LoggerTester.log.error("error")
val entity = LearnException()
entity.test()
}
| 0 | Java | 0 | 2 | 743c268d6c05c3e74a90586f618f79143fedb3b8 | 590 | learning | Apache License 2.0 |
Frontend/Cymon_v2/app/src/main/java/com/example/cymonbattle/pokemon/Move.kt | GrantPierce94 | 736,100,287 | false | {"Text": 14, "Ignore List": 121, "Markdown": 40, "Gradle": 46, "Java Properties": 90, "Shell": 60, "Batchfile": 53, "Proguard": 28, "Java": 524, "XML": 926, "Kotlin": 121, "JSON": 211, "HTML": 125, "INI": 77, "CSS": 10, "JavaScript": 18, "Maven POM": 45, "Gradle Kotlin DSL": 43, "Mustache": 13, "YAML": 3, "Ant Build System": 2, "SQL": 1} | package com.example.cymonbattle.pokemon
import org.json.JSONObject
data class Move(
val name: String,
val level: Int,
val category: String,
val damageClass: String,
val target: String,
val type: String,
val accuracy: Int?,
val heal: Int,
val power: Int?,
private var pp: Int,
val aliment: String,
val alimentChance: Int
) : java.io.Serializable{
// private var _isUsable: Boolean = true
var isUsable: Boolean = true
internal set
val maxPP: Int = pp
var currentPP: Int = pp
internal set(value) {
if (value <= 0) {
isUsable = false
}
field = value
}
// Make Move unusable if pp is 0.
init {
if(pp <= 0){
isUsable = false
}
}
/**
* This method will reset the currentPP to maxPP
* and set isUsable to true.
*/
fun resetPP() {
currentPP = maxPP
}
}
/**
* This method creates and returns a Move object.
*
* @param moveJson : JSONObject with the move data
* @param moveLevel : Level requirement of move
*/
fun createMove(moveJson: JSONObject, moveLevel: Int): Move {
return Move(
moveJson.getString("name"),
moveLevel,
moveJson.getString("category"),
moveJson.getString("damage_class"),
moveJson.getString("target"),
moveJson.getString("type"),
moveJson.getInt("accuracy"),
moveJson.getInt("healing"),
moveJson.getInt("power"),
moveJson.getInt("maxPP"),
moveJson.getString("ailment"),
moveJson.getInt("ailment_chance")
)
}
| 0 | Java | 0 | 0 | e93f3a04ff68e39189280853476e039e0164800f | 1,645 | cymon | MIT License |
matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreMigrationTest.kt | enterstudio | 160,125,033 | false | {"Java Properties": 2, "YAML": 1, "reStructuredText": 3, "Gradle": 3, "Shell": 4, "Markdown": 2, "Batchfile": 1, "Text": 3, "Ignore List": 2, "Proguard": 1, "Java": 398, "Kotlin": 21, "XML": 41, "JavaScript": 3, "HTML": 1} | /*
* Copyright 2018 New Vector Ltd
*
* 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.matrix.androidsdk.crypto
import android.support.test.InstrumentationRegistry
import android.text.TextUtils
import android.util.Pair
import org.junit.Assert
import org.junit.Assert.*
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runners.MethodSorters
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.common.*
import org.matrix.androidsdk.crypto.data.MXDeviceInfo
import org.matrix.androidsdk.data.RoomState
import org.matrix.androidsdk.data.cryptostore.IMXCryptoStore
import org.matrix.androidsdk.data.cryptostore.MXFileCryptoStore
import org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore
import org.matrix.androidsdk.data.timeline.EventTimeline
import org.matrix.androidsdk.listeners.MXEventListener
import org.matrix.androidsdk.rest.model.Event
import org.matrix.androidsdk.rest.model.MatrixError
import org.matrix.androidsdk.rest.model.RoomMember
import org.matrix.androidsdk.rest.model.crypto.RoomKeyRequestBody
import org.matrix.androidsdk.rest.model.message.Message
import org.matrix.androidsdk.util.JsonUtils
import org.matrix.androidsdk.util.Log
import org.matrix.olm.OlmAccount
import org.matrix.olm.OlmSession
import java.util.concurrent.CountDownLatch
@FixMethodOrder(MethodSorters.JVM)
class CryptoStoreMigrationTest {
private val mTestHelper = CommonTestHelper()
private val cryptoStoreHelper = CryptoStoreHelper()
private val sessionTestParamLegacy = SessionTestParams(withInitialSync = true, withCryptoEnabled = true, withLegacyCryptoStore = true)
private val sessionTestParamRealm = SessionTestParams(withInitialSync = true, withCryptoEnabled = true, withLegacyCryptoStore = false)
@Test
fun test_migrationEmptyStore() {
testMigration(
doOnFileStore = {
// Nothing to do for this test
},
checkOnRealmStore = {
// Compare the two store contents
assertEquals("deviceId_sample", it.deviceId)
assertNull(it.account)
})
}
@Test
fun test_migrationOlmAccount() {
val olmAccount = OlmAccount()
testMigration(
doOnFileStore = {
it.storeAccount(olmAccount)
},
checkOnRealmStore = {
val olmAccountFromRealm = it.account
assertNotNull(olmAccountFromRealm)
assertEquals(olmAccount.identityKeys(), olmAccountFromRealm.identityKeys())
})
}
@Test
fun test_migrationRooms() {
testMigration(
doOnFileStore = {
it.storeRoomAlgorithm("roomId1", "algo1")
it.storeRoomAlgorithm("roomId2", "algo2")
it.roomsListBlacklistUnverifiedDevices = listOf("roomId2")
},
checkOnRealmStore = {
assertEquals("algo1", it.getRoomAlgorithm("roomId1"))
assertEquals("algo2", it.getRoomAlgorithm("roomId2"))
assertEquals(listOf("roomId2"), it.roomsListBlacklistUnverifiedDevices)
})
}
@Test
fun test_migrationUsers() {
val deviceTrackingStatus = HashMap<String, Int>().apply {
put("userId1", MXDeviceList.TRACKING_STATUS_DOWNLOAD_IN_PROGRESS)
}
testMigration(
doOnFileStore = {
it.storeUserDevice("userId1", MXDeviceInfo().apply {
deviceId = "deviceId1"
userId = "userId1"
mVerified = MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED
})
it.saveDeviceTrackingStatuses(deviceTrackingStatus)
},
checkOnRealmStore = {
val deviceFromRealm = it.getUserDevice("deviceId1", "userId1")
assertEquals(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED, deviceFromRealm.mVerified)
assertEquals(deviceTrackingStatus, it.deviceTrackingStatuses)
})
}
@Test
fun test_migrationOutgoingRoomKeyRequest() {
val request = OutgoingRoomKeyRequest(
// Request body
HashMap<String, String>().apply {
put("key", "value")
},
// Recipients
ArrayList<Map<String, String>>().apply {
add(HashMap<String, String>().apply {
put("recipient", "recipientsValue")
})
},
"RequestId",
OutgoingRoomKeyRequest.RequestState.CANCELLATION_PENDING_AND_WILL_RESEND)
.apply {
mCancellationTxnId = "mCancellationTxnId"
}
testMigration(
doOnFileStore = {
it.getOrAddOutgoingRoomKeyRequest(request)
},
checkOnRealmStore = {
val requestFromRealm = it.getOutgoingRoomKeyRequest(request.mRequestBody)
assertNotNull(requestFromRealm)
assertEquals("value", requestFromRealm!!.mRequestBody["key"])
assertEquals("recipientsValue", requestFromRealm.mRecipients[0]["recipient"])
assertEquals("RequestId", requestFromRealm.mRequestId)
assertEquals(OutgoingRoomKeyRequest.RequestState.CANCELLATION_PENDING_AND_WILL_RESEND, requestFromRealm.mState)
assertEquals("mCancellationTxnId", requestFromRealm.mCancellationTxnId)
})
}
@Test
fun test_migrationIncomingRoomKeyRequest() {
val request = IncomingRoomKeyRequest().apply {
mUserId = "userId"
mDeviceId = "DeviceId"
mRequestId = "RequestId"
mRequestBody = RoomKeyRequestBody().apply {
algorithm = "Algo"
room_id = "RoomId"
sender_key = "SenderKey"
session_id = "SessionId"
}
}
testMigration(
doOnFileStore = {
it.storeIncomingRoomKeyRequest(request)
},
checkOnRealmStore = {
assertEquals(1, it.pendingIncomingRoomKeyRequests.size)
val requestFromRealm = it.getIncomingRoomKeyRequest(request.mUserId, request.mDeviceId, request.mRequestId)
assertEquals("userId", requestFromRealm!!.mUserId)
assertEquals("DeviceId", requestFromRealm.mDeviceId)
assertEquals("RequestId", requestFromRealm.mRequestId)
assertEquals("Algo", requestFromRealm.mRequestBody.algorithm)
assertEquals("RoomId", requestFromRealm.mRequestBody.room_id)
assertEquals("SenderKey", requestFromRealm.mRequestBody.sender_key)
assertEquals("SessionId", requestFromRealm.mRequestBody.session_id)
})
}
@Test
fun test_migrationOlmSessions() {
val session = OlmSession()
val sessionId = session.sessionIdentifier()
testMigration(
doOnFileStore = {
it.storeSession(session, "deviceID")
},
checkOnRealmStore = {
val sessionsFromRealm = it.getDeviceSessionIds("deviceID")
assertEquals(1, sessionsFromRealm!!.size)
assertTrue(sessionsFromRealm.contains(sessionId))
val sessionFromRealm = it.getDeviceSession(sessionId, "deviceID")
assertNotNull(sessionFromRealm)
assertEquals(sessionId, sessionFromRealm?.sessionIdentifier())
})
}
@Test
fun test_migrationInboundGroupSessions() {
// This is tested in test_integration_migrationInboundGroupSession
}
/* ==========================================================================================
* Integration tests
* ========================================================================================== */
@Test
fun test_integration_migrationEmptyStore() {
Log.e(LOG_TAG, "test01_testCryptoNoDeviceId")
// Create an account using the file store
val context = InstrumentationRegistry.getContext()
val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, sessionTestParamLegacy)
assertNotNull(bobSession.crypto)
assertNotNull(bobSession.crypto?.cryptoStore)
assertTrue(bobSession.crypto?.cryptoStore is MXFileCryptoStore)
assertNotNull(bobSession.credentials.deviceId)
// Open again the session, with the Realm store. It will trigger the migration
val bobSession2 = mTestHelper.createNewSession(bobSession, sessionTestParamRealm)
// Migration should be ok
assertNotNull(bobSession2.crypto)
assertNotNull(bobSession2.crypto?.cryptoStore)
assertTrue(bobSession2.crypto?.cryptoStore is RealmCryptoStore)
// Crypto store should contains device
assertEquals(bobSession.crypto?.cryptoStore?.deviceId, bobSession2.crypto?.cryptoStore?.deviceId)
bobSession.clear(context)
bobSession2.clear(context)
}
@Test
fun test_integration_migrationInboundGroupSession() {
Log.e(LOG_TAG, "test_integration_migrationInboundGroupSession")
val context = InstrumentationRegistry.getContext()
val results = java.util.HashMap<String, Any>()
val pair = doE2ETestWithAliceAndBobInARoom(true)
val aliceSession = pair.first.first
val aliceRoomId = pair.first.second
val bobSession = pair.second
val messageFromAlice = "Hello I'm Alice!"
val roomFromBobPOV = bobSession.dataHandler.getRoom(aliceRoomId)
val roomFromAlicePOV = aliceSession.dataHandler.getRoom(aliceRoomId)
Assert.assertTrue(roomFromBobPOV.isEncrypted)
Assert.assertTrue(roomFromAlicePOV.isEncrypted)
aliceSession.crypto!!.setWarnOnUnknownDevices(false)
val lock = CountDownLatch(2)
val eventListener = object : MXEventListener() {
override fun onLiveEvent(event: Event, roomState: RoomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession)
results["onLiveEvent"] = "onLiveEvent"
lock.countDown()
}
}
}
roomFromBobPOV.addEventListener(eventListener)
roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), TestApiCallback<Void>(lock))
mTestHelper.await(lock)
Assert.assertTrue(results.containsKey("onLiveEvent"))
// Close alice and bob session
aliceSession.crypto!!.close()
bobSession.crypto!!.close()
// Do not login, but instead create a new session
val aliceSession2 = mTestHelper.createNewSession(aliceSession, sessionTestParamRealm)
// Check that the store contains the inboundGroupSession
assertTrue(aliceSession2.crypto?.cryptoStore is RealmCryptoStore)
// Not empty list
assertTrue(aliceSession2.crypto!!.cryptoStore!!.inboundGroupSessions!!.isNotEmpty())
// Bob should still be able to decrypt message from Alice
// Do not login, but instead create a new session
val bobSession2 = mTestHelper.createNewSession(bobSession, sessionTestParamRealm)
// Check that the store contains the inboundGroupSession
assertTrue(bobSession2.crypto!!.cryptoStore is RealmCryptoStore)
// Not empty list
assertFalse(bobSession2.crypto!!.cryptoStore!!.inboundGroupSessions!!.isEmpty())
val roomFromBobPOV2 = bobSession2.dataHandler.getRoom(aliceRoomId)
Assert.assertTrue(roomFromBobPOV2.isEncrypted)
val lock2 = CountDownLatch(1)
val eventListener2 = object : EventTimeline.Listener {
override fun onEvent(event: Event, direction: EventTimeline.Direction, roomState: RoomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession)
results["onLiveEvent2"] = "onLiveEvent2"
lock2.countDown()
}
}
}
roomFromBobPOV2.timeline.addEventTimelineListener(eventListener2)
roomFromBobPOV2.timeline.backPaginate(1, null)
mTestHelper.await(lock2)
Assert.assertTrue(results.containsKey("onLiveEvent2"))
aliceSession.clear(context)
bobSession.clear(context)
aliceSession2.clear(context)
bobSession2.clear(context)
}
/* ==========================================================================================
* Private
* ========================================================================================== */
private fun testMigration(doOnFileStore: (IMXCryptoStore) -> Unit,
checkOnRealmStore: (IMXCryptoStore) -> Unit) {
val context = InstrumentationRegistry.getContext()
val credentials = cryptoStoreHelper.createCredential()
val fileCryptoStore = MXFileCryptoStore(false)
fileCryptoStore.initWithCredentials(context, credentials)
fileCryptoStore.open()
// Let each test do what they want to configure the file store
doOnFileStore.invoke(fileCryptoStore)
// It will trigger the migration
val realmCryptoStore = RealmCryptoStore()
realmCryptoStore.initWithCredentials(context, credentials)
// Check the realm store content
checkOnRealmStore.invoke(realmCryptoStore)
// Check that file store has been deleted
assertFalse(fileCryptoStore.hasData())
fileCryptoStore.close()
realmCryptoStore.close()
}
companion object {
private const val LOG_TAG = "CryptoStoreMigrationTest"
}
/* ==========================================================================================
* TODO REMOVE and replace by call form mCryptoTestHelper (from the branch keys backup)
* ========================================================================================== */
/**
* @param cryptedBob
* @return alice and bob sessions
* @throws Exception
*/
@Throws(Exception::class)
private fun doE2ETestWithAliceAndBobInARoom(cryptedBob: Boolean): Pair<SessionAndRoomId, MXSession> {
val statuses = java.util.HashMap<String, String>()
val sessionAndRoomId = doE2ETestWithAliceInARoom()
val aliceSession = sessionAndRoomId.first
val aliceRoomId = sessionAndRoomId.second
val room = aliceSession.dataHandler.getRoom(aliceRoomId)
val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, sessionTestParamLegacy)
val lock0 = CountDownLatch(1)
bobSession.enableCrypto(cryptedBob, object : TestApiCallback<Void>(lock0) {
override fun onSuccess(info: Void?) {
statuses["enableCrypto"] = "enableCrypto"
super.onSuccess(info)
}
})
mTestHelper.await(lock0)
val lock1 = CountDownLatch(2)
val bobEventListener = object : MXEventListener() {
override fun onNewRoom(roomId: String) {
if (TextUtils.equals(roomId, aliceRoomId)) {
if (!statuses.containsKey("onNewRoom")) {
statuses["onNewRoom"] = "onNewRoom"
lock1.countDown()
}
}
}
}
bobSession.dataHandler.addListener(bobEventListener)
room.invite(bobSession.myUserId, object : TestApiCallback<Void>(lock1) {
override fun onSuccess(info: Void?) {
statuses["invite"] = "invite"
super.onSuccess(info)
}
})
mTestHelper.await(lock1)
Assert.assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom"))
bobSession.dataHandler.removeListener(bobEventListener)
val lock2 = CountDownLatch(2)
bobSession.joinRoom(aliceRoomId, object : TestApiCallback<String>(lock2) {
override fun onSuccess(info: String) {
statuses["joinRoom"] = "joinRoom"
super.onSuccess(info)
}
override fun onNetworkError(e: Exception) {
statuses["onNetworkError"] = e.message!!
super.onNetworkError(e)
}
override fun onMatrixError(e: MatrixError) {
statuses["onMatrixError"] = e.message
super.onMatrixError(e)
}
override fun onUnexpectedError(e: Exception) {
statuses["onUnexpectedError"] = e.message!!
super.onUnexpectedError(e)
}
})
room.addEventListener(object : MXEventListener() {
override fun onLiveEvent(event: Event, roomState: RoomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_STATE_ROOM_MEMBER)) {
val contentToConsider = event.contentAsJsonObject
val member = JsonUtils.toRoomMember(contentToConsider)
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN)) {
statuses["AliceJoin"] = "AliceJoin"
lock2.countDown()
}
}
}
})
mTestHelper.await(lock2)
Assert.assertTrue(statuses.toString() + "", statuses.containsKey("joinRoom"))
Assert.assertTrue(statuses.toString() + "", statuses.containsKey("AliceJoin"))
bobSession.dataHandler.removeListener(bobEventListener)
return Pair(sessionAndRoomId, bobSession)
}
/**
* @return alice session
* @throws Exception
*/
@Throws(Exception::class)
private fun doE2ETestWithAliceInARoom(): SessionAndRoomId {
val results = java.util.HashMap<String, Any>()
val aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, sessionTestParamLegacy)
val lock0 = CountDownLatch(1)
aliceSession.enableCrypto(true, object : TestApiCallback<Void>(lock0) {
override fun onSuccess(info: Void?) {
results["enableCrypto"] = "enableCrypto"
super.onSuccess(info)
}
})
mTestHelper.await(lock0)
Assert.assertTrue(results.containsKey("enableCrypto"))
var roomId: String? = null
val lock1 = CountDownLatch(1)
aliceSession.createRoom(object : TestApiCallback<String>(lock1) {
override fun onSuccess(createdRoomId: String) {
roomId = createdRoomId
super.onSuccess(createdRoomId)
}
})
mTestHelper.await(lock1)
Assert.assertNotNull(roomId)
val room = aliceSession.dataHandler.getRoom(roomId)
val lock2 = CountDownLatch(1)
room.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, object : TestApiCallback<Void>(lock2) {
override fun onSuccess(info: Void?) {
results["enableEncryptionWithAlgorithm"] = "enableEncryptionWithAlgorithm"
super.onSuccess(info)
}
})
mTestHelper.await(lock2)
Assert.assertTrue(results.containsKey("enableEncryptionWithAlgorithm"))
return SessionAndRoomId(aliceSession, roomId)
}
private fun buildTextEvent(text: String, session: MXSession, roomId: String): Event {
val message = Message()
message.msgtype = Message.MSGTYPE_TEXT
message.body = text
return Event(message, session.credentials.userId, roomId)
}
private fun checkEncryptedEvent(event: Event, roomId: String, clearMessage: String, senderSession: MXSession) {
Assert.assertEquals(Event.EVENT_TYPE_MESSAGE_ENCRYPTED, event.wireType)
Assert.assertNotNull(event.wireContent)
val eventWireContent = event.wireContent.asJsonObject
Assert.assertNotNull(eventWireContent)
Assert.assertNull(eventWireContent.get("body"))
Assert.assertEquals(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, eventWireContent.get("algorithm").asString)
Assert.assertNotNull(eventWireContent.get("ciphertext"))
Assert.assertNotNull(eventWireContent.get("session_id"))
Assert.assertNotNull(eventWireContent.get("sender_key"))
Assert.assertEquals(senderSession.credentials.deviceId, eventWireContent.get("device_id").asString)
Assert.assertNotNull(event.eventId)
Assert.assertEquals(roomId, event.roomId)
Assert.assertEquals(Event.EVENT_TYPE_MESSAGE, event.getType())
Assert.assertTrue(event.getAge() < 10000)
val eventContent = event.contentAsJsonObject
Assert.assertNotNull(eventContent)
Assert.assertEquals(clearMessage, eventContent!!.get("body").asString)
Assert.assertEquals(senderSession.myUserId, event.sender)
}
} | 1 | null | 1 | 1 | 497c7fa4a17df57dfe6e57e58b48dd174b395d01 | 22,092 | matrix-android-sdk | Apache License 2.0 |
Backend/Spring/start-code-executions/src/test/kotlin/org/example/startcodeexecutions/StartCodeExecutionsApplicationTests.kt | Luxusio | 360,716,262 | false | {"Text": 4, "Git Attributes": 1, "Markdown": 3, "Gradle": 32, "Shell": 23, "Ignore List": 28, "Batchfile": 23, "INI": 44, "Java": 473, "JSON": 4, "HTML": 138, "JavaScript": 40, "CSS": 14, "Gradle Kotlin DSL": 15, "Kotlin": 23, "XML": 36, "Python": 7, "Maven POM": 2, "YAML": 5, "Java Properties": 5, "SQL": 1, "Java Server Pages": 6, "AsciiDoc": 1} | package org.example.startcodeexecutions
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class StartCodeExecutionsApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Java | 0 | 0 | 368b567e0e2392240749d274cbd4d28fbec4e8e7 | 244 | Programming-Study | MIT License |
dsl/camel-kotlin-api/src/generated/kotlin/org/apache/camel/kotlin/components/HwcloudIamUriDsl.kt | dhis2 | 598,577,710 | true | {"Groovy": 164, "Text": 249, "Shell": 20, "Maven POM": 587, "Batchfile": 4, "YAML": 74, "Markdown": 26, "Git Attributes": 1, "XML": 1786, "Ignore List": 19, "JSON": 2558, "Git Config": 1, "Java": 21541, "Java Properties": 1060, "AsciiDoc": 1303, "Kotlin": 495, "JavaScript": 32, "OASv3-json": 19, "Dockerfile": 4, "JAR Manifest": 47, "CSS": 2, "XSLT": 61, "SVG": 2, "HTML": 150, "INI": 22, "OASv2-json": 6, "OASv3-yaml": 8, "Thrift": 2, "Public Key": 16, "Protocol Buffer": 5, "Ruby": 1, "GraphQL": 4, "SQL": 37, "Fluent": 9, "XQuery": 5, "TOML": 2, "Rust": 1, "Tcl": 5, "Jsonnet": 2, "Mustache": 7, "RobotFramework": 7, "ASN.1": 1, "Apex": 3, "Erlang": 1, "OASv2-yaml": 1} | /*
* 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 org.apache.camel.kotlin.components
import kotlin.Boolean
import kotlin.Int
import kotlin.String
import kotlin.Unit
import org.apache.camel.kotlin.CamelDslMarker
import org.apache.camel.kotlin.UriDsl
/**
* To securely manage users on Huawei Cloud
*/
public fun UriDsl.`hwcloud-iam`(i: HwcloudIamUriDsl.() -> Unit) {
HwcloudIamUriDsl(this).apply(i)
}
@CamelDslMarker
public class HwcloudIamUriDsl(
it: UriDsl,
) {
private val it: UriDsl
init {
this.it = it
this.it.component("hwcloud-iam")
}
private var operation: String = ""
/**
* Operation to be performed
*/
public fun operation(operation: String) {
this.operation = operation
it.url("$operation")
}
/**
* Access key for the cloud user
*/
public fun accessKey(accessKey: String) {
it.property("accessKey", accessKey)
}
/**
* Group ID to perform operation with
*/
public fun groupId(groupId: String) {
it.property("groupId", groupId)
}
/**
* Ignore SSL verification
*/
public fun ignoreSslVerification(ignoreSslVerification: String) {
it.property("ignoreSslVerification", ignoreSslVerification)
}
/**
* Ignore SSL verification
*/
public fun ignoreSslVerification(ignoreSslVerification: Boolean) {
it.property("ignoreSslVerification", ignoreSslVerification.toString())
}
/**
* Proxy server ip/hostname
*/
public fun proxyHost(proxyHost: String) {
it.property("proxyHost", proxyHost)
}
/**
* Proxy authentication password
*/
public fun proxyPassword(proxyPassword: String) {
it.property("proxyPassword", proxyPassword)
}
/**
* Proxy server port
*/
public fun proxyPort(proxyPort: String) {
it.property("proxyPort", proxyPort)
}
/**
* Proxy server port
*/
public fun proxyPort(proxyPort: Int) {
it.property("proxyPort", proxyPort.toString())
}
/**
* Proxy authentication user
*/
public fun proxyUser(proxyUser: String) {
it.property("proxyUser", proxyUser)
}
/**
* IAM service region
*/
public fun region(region: String) {
it.property("region", region)
}
/**
* Secret key for the cloud user
*/
public fun secretKey(secretKey: String) {
it.property("secretKey", secretKey)
}
/**
* Configuration object for cloud service authentication
*/
public fun serviceKeys(serviceKeys: String) {
it.property("serviceKeys", serviceKeys)
}
/**
* User ID to perform operation with
*/
public fun userId(userId: String) {
it.property("userId", userId)
}
/**
* Whether the producer should be started lazy (on the first message). By starting lazy you can
* use this to allow CamelContext and routes to startup in situations where a producer may otherwise
* fail during starting and cause the route to fail being started. By deferring this startup to be
* lazy then the startup failure can be handled during routing messages via Camel's routing error
* handlers. Beware that when the first message is processed then creating and starting the producer
* may take a little time and prolong the total processing time of the processing.
*/
public fun lazyStartProducer(lazyStartProducer: String) {
it.property("lazyStartProducer", lazyStartProducer)
}
/**
* Whether the producer should be started lazy (on the first message). By starting lazy you can
* use this to allow CamelContext and routes to startup in situations where a producer may otherwise
* fail during starting and cause the route to fail being started. By deferring this startup to be
* lazy then the startup failure can be handled during routing messages via Camel's routing error
* handlers. Beware that when the first message is processed then creating and starting the producer
* may take a little time and prolong the total processing time of the processing.
*/
public fun lazyStartProducer(lazyStartProducer: Boolean) {
it.property("lazyStartProducer", lazyStartProducer.toString())
}
}
| 0 | Java | 0 | 1 | 65511a265752d23f5bbf4bb32cb3438c1d535f98 | 4,824 | camel | Apache License 2.0 |
app-inspection/inspectors/network/ide/src/com/android/tools/idea/appinspection/inspectors/network/ide/analytics/IdeNetworkInspectorTracker.kt | Hzy-Joel | 570,420,990 | true | {"Text": 355, "EditorConfig": 2, "Markdown": 64, "Shell": 32, "Ignore List": 193, "XML": 13507, "Starlark": 142, "Kotlin": 6746, "Java": 8085, "Gradle": 2753, "Proguard": 169, "INI": 72, "JSON": 80, "Graphviz (DOT)": 1, "Ant Build System": 2, "Protocol Buffer": 8, "Java Properties": 166, "HTML": 67, "Batchfile": 20, "Gradle Kotlin DSL": 1655, "CMake": 19, "C": 29, "Checksums": 339, "C++": 14, "TOML": 2, "Smali": 5, "SVG": 1329, "AIDL": 9, "JFlex": 8, "Prolog": 6, "QMake": 2, "RenderScript": 1, "NSIS": 4, "GraphQL": 5, "Python": 10, "Makefile": 8, "YAML": 1, "HAProxy": 1, "Org": 2, "JavaScript": 3} | /*
* Copyright (C) 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 com.android.tools.idea.appinspection.inspectors.network.ide.analytics
import com.android.tools.analytics.UsageTracker
import com.android.tools.idea.appinspection.inspectors.network.model.analytics.NetworkInspectorTracker
import com.android.tools.idea.stats.AnonymizerUtil
import com.google.wireless.android.sdk.stats.AndroidStudioEvent
import com.google.wireless.android.sdk.stats.AppInspectionEvent
import com.google.wireless.android.sdk.stats.AppInspectionEvent.NetworkInspectorEvent
import com.intellij.openapi.project.Project
class IdeNetworkInspectorTracker(private val project: Project) : NetworkInspectorTracker {
override fun trackMigrationDialogSelected() {
track(
NetworkInspectorEvent.newBuilder().apply {
type = NetworkInspectorEvent.Type.MIGRATION_LINK_SELECTED
}
)
}
override fun trackConnectionDetailsSelected() {
track(
NetworkInspectorEvent.newBuilder().apply {
type = NetworkInspectorEvent.Type.CONNECTION_DETAIL_SELECTED
}
)
}
override fun trackRequestTabSelected() {
track(
NetworkInspectorEvent.newBuilder().apply {
type = NetworkInspectorEvent.Type.REQUEST_TAB_SELECTED
}
)
}
override fun trackResponseTabSelected() {
track(
NetworkInspectorEvent.newBuilder().apply {
type = NetworkInspectorEvent.Type.RESPONSE_TAB_SELECTED
}
)
}
override fun trackCallstackTabSelected() {
track(
NetworkInspectorEvent.newBuilder().apply {
type = NetworkInspectorEvent.Type.CALLSTACK_TAB_SELECTED
}
)
}
private fun track(networkEvent: NetworkInspectorEvent.Builder) {
val inspectionEvent = AppInspectionEvent.newBuilder()
.setType(AppInspectionEvent.Type.INSPECTOR_EVENT)
.setNetworkInspectorEvent(networkEvent)
val studioEvent = AndroidStudioEvent.newBuilder()
.setKind(AndroidStudioEvent.EventKind.APP_INSPECTION)
.setAppInspectionEvent(inspectionEvent)
// TODO(b/153270761): Use studioEvent.withProjectId instead, after code is moved out of
// monolithic core module
studioEvent.projectId = AnonymizerUtil.anonymizeUtf8(project.basePath!!)
UsageTracker.log(studioEvent)
}
} | 0 | null | 0 | 0 | b373163869f676145341d60985cdbdaca3565c0b | 2,831 | android | Apache License 2.0 |
libraries/testlib/test/template/experiment1/I18nTemplateTest.kt | stepancheg | 3,653,064 | true | {"Markdown": 7, "XML": 325, "Ant Build System": 8, "Ignore List": 3, "Python": 1, "Shell": 3, "Makefile": 1, "JAR Manifest": 2, "Java": 1653, "Kotlin": 1384, "Text": 271, "Java Properties": 1, "INI": 1, "HTML": 9, "JavaScript": 28, "JFlex": 2, "Batchfile": 1, "Maven POM": 8, "CSS": 6} | package template.experiment1
import kotlin.template.experiment1.*
import kotlin.test.assertEquals
import junit.framework.TestCase
import java.util.Date
import java.util.Locale
class I18nTemplateTest : TestCase() {
fun testDefaultLocale() : Unit {
format(I18nFormatter())
}
fun testFrance() : Unit {
format(I18nFormatter(Locale.FRANCE.sure()))
}
fun testGermany() : Unit {
format(I18nFormatter(Locale.GERMANY.sure()))
}
fun format(format: I18nFormatter): Unit {
val name = "James"
// TODO currently numbers cause: java.lang.ClassNotFoundException: jet.Number
//val price: Double = 1.99
val now = Date()
// Code generated by the following template expression:
//
// val actual = format.toI18n("hello $name!")
val actual = format.toString{
it.text("hello ")
it.expression(name)
/*
it.text(" price ")
it.expression(price)
*/
it.text(" date ")
it.expression(now)
}
println("Got text: $actual")
}
}
| 0 | Java | 0 | 1 | 70216bff120bfdbca10fdfa5eb1e3fec283d1b1d | 1,110 | kotlin | Apache License 2.0 |
app/src/main/java/com/pedro/sample/Camera2DemoActivity.kt | jin-vita | 655,484,840 | false | {"Java": 833804, "Kotlin": 414537, "GLSL": 40954} | package com.pedro.sample
import android.Manifest
import android.app.AlertDialog
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.util.Size
import android.view.SurfaceHolder
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.pedro.encoder.input.video.CameraHelper
import com.pedro.encoder.input.video.CameraOpenException
import com.pedro.rtsp.utils.ConnectCheckerRtsp
import com.pedro.rtspserver.RtspServerCamera2
import kotlinx.android.synthetic.main.activity_camera2_demo.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.IOException
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException
import java.text.SimpleDateFormat
import java.util.*
class Camera2DemoActivity : AppCompatActivity(), ConnectCheckerRtsp, View.OnClickListener,
SurfaceHolder.Callback {
private val PERMISSIONS = arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
private lateinit var rtspServerCamera2: RtspServerCamera2
private lateinit var button: Button
private lateinit var bRecord: Button
private lateinit var output1: TextView
private var currentDateAndTime = ""
private lateinit var folder: File
val handler = Handler(Looper.getMainLooper())
var cameraIds = arrayOfNulls<String>(0)
// 화면잠금
var deviceManger: DevicePolicyManager? = null
var compName: ComponentName? = null
var active = false
var systemAlertDialogShown = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContentView(R.layout.activity_camera2_demo)
folder = File(getExternalFilesDir(null)!!.absolutePath + "/rtmp-rtsp-stream-client-java")
button = findViewById(R.id.b_start_stop)
button.setOnClickListener(this)
bRecord = findViewById(R.id.b_record)
bRecord.setOnClickListener(this)
switch_camera.setOnClickListener(this)
output1 = findViewById(R.id.output1)
// 프리뷰 화면을 보고싶다면...
//rtspServerCamera2 = RtspServerCamera2(surfaceView, this, 1935)
//surfaceView.holder.addCallback(this)
val exposureButton = findViewById<Button>(R.id.exposureButton)
exposureButton.setOnClickListener {
rtspServerCamera2.exposure = rtspServerCamera2.maxExposure
Toast.makeText(this, "max exposure : ${rtspServerCamera2.maxExposure}", Toast.LENGTH_SHORT).show()
}
if (!hasPermissions(this, *PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1)
} else {
// 인텐트 처리
intent?.apply {
handleIntent(this)
}
}
save()
}
private fun save() {
RobotClient.api.postDeviceSave(
requestCode = 7777777,
id = "LTR-SMC-001-F",
name = "<NAME>",
dept = "서울삼성병원",
type = "LTR",
group_id = "LTR-SMC",
regid = "",
ip = getIP(),
mac = "",
mobile = "",
ostype = "",
osversion = "",
manufacturer = "",
model = "",
display = "",
extra1 = "",
extra2 = "",
extra3 = "",
access = "",
permission = ""
).enqueue(object : Callback<DeviceSaveResponse> {
override fun onResponse(call: Call<DeviceSaveResponse>, response: Response<DeviceSaveResponse>) {}
override fun onFailure(call: Call<DeviceSaveResponse>, t: Throwable) { handler.postDelayed(::save, 10000) }
})
}
private fun getIP(): String {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val it = en.nextElement()
val enumIpAddress = it.inetAddresses
while (enumIpAddress.hasMoreElements()) {
val inetAddress = enumIpAddress.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address)
return inetAddress.getHostAddress() ?: "unknown IP"
}
}
} catch (_: SocketException) {
}
return "unknown IP"
}
private fun hasPermissions(context: Context?, vararg permissions: String): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null) {
for (permission in permissions) {
if (ActivityCompat.checkSelfPermission(context,
permission) != PackageManager.PERMISSION_GRANTED) {
return false
}
}
}
return true
}
override fun onNewIntent(intent: Intent?) {
intent?.apply {
handleIntent(this)
}
super.onNewIntent(intent)
}
fun handleIntent(intent: Intent?) {
if (intent != null) {
// 서버 시작
startServer()
// 5초 후에 화면 종료
handler.postDelayed(
{ moveTaskToBack(true) },
5000)
}
}
override fun onResume() {
super.onResume()
// 위험권한 부여 요청
requestPermission()
}
fun requestPermission() {
// 단말 관리자 앱으로 설정 요청
deviceManger = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
compName = ComponentName(this, DeviceAdmin::class.java)
active = deviceManger!!.isAdminActive(compName!!)
Log.d("Camera", "deviceAdmin is active : ${active}")
if (!active) {
val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).apply {
putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName)
putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "기기 관리자 앱으로 권한을 부여합니다")
}
startActivityForResult(intent, 1001)
} else {
showSystemAlertWindowPermission()
}
}
/**
* 다른 앱 위에 그리기 권한 허용 여부 확인
*/
fun showSystemAlertWindowPermission(): Boolean {
Log.d("Camera", "showSystemAlertWindowPermission() called.")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
val dialog = AlertDialog.Builder(this)
dialog.setCancelable(false)
dialog.setTitle("다른 앱 위에 그리기 권한을 부여하셔야 사용하실 수 있습니다.")
dialog.setPositiveButton("확인") { dialog, which ->
dialog.dismiss()
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse(
"package:$packageName"
)
)
startActivity(intent)
}
dialog.setNegativeButton("무시") { dialog, which ->
dialog.dismiss()
}
dialog.show()
systemAlertDialogShown = true
} else {
// TODO : 셋톱박스 제외해야 함
//checkLocation()
}
}
return true
}
fun startServer() {
// 카메라 id 확인
val cameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
cameraIds = cameraManager.cameraIdList
output1.append("카메라 갯수 : ${cameraIds.size} ")
cameraIds.forEachIndexed { index, cameraId ->
cameraId?.apply {
output1.append("카메라 ${index} : ${this} ")
val resolution = getResolution(cameraManager, this)
output1.append("(${resolution.width}, ${resolution.height})")
}
}
if (cameraIds.isNotEmpty()) {
// 첫번째 서비스 실행
val serviceIntent = Intent(applicationContext, CameraRtspService::class.java)
serviceIntent.putExtra("command", "start")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent)
} else {
startService(serviceIntent)
}
// 두번째 서비스 실행
if (cameraIds.size > 1) {
val serviceIntent2 = Intent(applicationContext, CameraRtspService2::class.java)
serviceIntent2.putExtra("command", "start")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent2)
} else {
startService(serviceIntent2)
}
}
}
}
@Throws(CameraAccessException::class)
fun getResolution(cameraManager: CameraManager, cameraId: String): Size {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
?: throw IllegalStateException("Failed to get configuration map.")
val choices: Array<Size> = map.getOutputSizes(ImageFormat.JPEG)
Arrays.sort(
choices,
Collections.reverseOrder { lhs, rhs -> // Cast to ensure the multiplications won't overflow
java.lang.Long.signum((lhs.width * lhs.height).toLong() - (rhs.width * rhs.height).toLong())
})
return choices[0]
}
fun stopServer() {
// 서비스 실행
val serviceIntent = Intent(applicationContext, CameraRtspService::class.java)
serviceIntent.putExtra("command", "start")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent)
} else {
startService(serviceIntent)
}
}
/**
* 시작하거나 중지하기
*/
private fun startStopServer() {
if (!rtspServerCamera2.isStreaming) {
val videoWidth = 1920
val videoHeight = 1080
val fps = 30
val bitrate = 1200 * 1024
val rotation = CameraHelper.getCameraOrientation(this)
if (rtspServerCamera2.isRecording || rtspServerCamera2.prepareAudio() &&
//rtspServerCamera2.prepareVideo(videoWidth, videoHeight, fps, bitrate, rotation)) {
rtspServerCamera2.prepareVideo()) {
button.setText(R.string.stop_button)
rtspServerCamera2.startStream()
tv_url.text = rtspServerCamera2.getEndPointConnection()
} else {
Toast.makeText(this, "Error preparing stream, This device cant do it", Toast.LENGTH_SHORT).show()
}
} else {
button.setText(R.string.start_button)
rtspServerCamera2.stopStream()
tv_url.text = ""
}
}
override fun onNewBitrateRtsp(bitrate: Long) {
}
override fun onConnectionSuccessRtsp() {
runOnUiThread {
Toast.makeText(this@Camera2DemoActivity, "Connection success", Toast.LENGTH_SHORT).show()
}
}
override fun onConnectionFailedRtsp(reason: String) {
runOnUiThread {
Toast.makeText(this@Camera2DemoActivity, "Connection failed. $reason", Toast.LENGTH_SHORT)
.show()
rtspServerCamera2.stopStream()
button.setText(R.string.start_button)
}
}
override fun onConnectionStartedRtsp(rtspUrl: String) {
}
override fun onDisconnectRtsp() {
runOnUiThread {
Toast.makeText(this@Camera2DemoActivity, "Disconnected", Toast.LENGTH_SHORT).show()
}
}
override fun onAuthErrorRtsp() {
runOnUiThread {
Toast.makeText(this@Camera2DemoActivity, "Auth error", Toast.LENGTH_SHORT).show()
rtspServerCamera2.stopStream()
button.setText(R.string.start_button)
tv_url.text = ""
}
}
override fun onAuthSuccessRtsp() {
runOnUiThread {
Toast.makeText(this@Camera2DemoActivity, "Auth success", Toast.LENGTH_SHORT).show()
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.b_start_stop -> startStopServer()
R.id.switch_camera -> try {
rtspServerCamera2.switchCamera()
} catch (e: CameraOpenException) {
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
R.id.b_record -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (!rtspServerCamera2.isRecording) {
try {
if (!folder.exists()) {
folder.mkdir()
}
val sdf = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
currentDateAndTime = sdf.format(Date())
if (!rtspServerCamera2.isStreaming) {
if (rtspServerCamera2.prepareAudio() && rtspServerCamera2.prepareVideo()) {
rtspServerCamera2.startRecord(folder.absolutePath + "/" + currentDateAndTime + ".mp4")
bRecord.setText(R.string.stop_record)
Toast.makeText(this, "Recording... ", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(
this, "Error preparing stream, This device cant do it",
Toast.LENGTH_SHORT
).show()
}
} else {
rtspServerCamera2.startRecord(folder.absolutePath + "/" + currentDateAndTime + ".mp4")
bRecord.setText(R.string.stop_record)
Toast.makeText(this, "Recording... ", Toast.LENGTH_SHORT).show()
}
} catch (e: IOException) {
rtspServerCamera2.stopRecord()
bRecord.setText(R.string.start_record)
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
} else {
rtspServerCamera2.stopRecord()
bRecord.setText(R.string.start_record)
Toast.makeText(
this, "file " + currentDateAndTime + ".mp4 saved in " + folder.absolutePath,
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(this, "You need min JELLY_BEAN_MR2(API 18) for do it...", Toast.LENGTH_SHORT).show()
}
}
else -> {
}
}
}
override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
}
override fun surfaceChanged(surfaceHolder: SurfaceHolder, i: Int, i1: Int, i2: Int) {
//rtspServerCamera2.startPreview()
val cameraId = rtspServerCamera2.camerasAvailable[0]
rtspServerCamera2.startPreview(cameraId)
}
override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (rtspServerCamera2.isRecording) {
rtspServerCamera2.stopRecord()
bRecord.setText(R.string.start_record)
Toast.makeText(this, "file " + currentDateAndTime + ".mp4 saved in " + folder.absolutePath, Toast.LENGTH_SHORT).show()
currentDateAndTime = ""
}
}
if (rtspServerCamera2.isStreaming) {
rtspServerCamera2.stopStream()
button.text = resources.getString(R.string.start_button)
tv_url.text = ""
}
rtspServerCamera2.stopPreview()
}
}
| 1 | null | 1 | 1 | 0547c2e04c60d29bf203406b289e2e6d1c6858dd | 14,727 | my-rtsp-server | Apache License 2.0 |
generators/opengl/src/main/kotlin/overrungl/opengl/GLARB.kt | Over-Run | 524,365,086 | false | {"Gradle Kotlin DSL": 9, "CODEOWNERS": 1, "Java Properties": 1, "Markdown": 11, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "INI": 1, "YAML": 4, "Kotlin": 8, "Java": 713, "XML": 1} | /*
* MIT License
*
* Copyright (c) 2023-2024 Overrun Organization
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package overrungl.opengl
import overrungl.opengl.OpenGLExt.ARB
/**
* @author squid233
* @since 0.1.0
*/
fun arb() {
file("ES32Compatibility", ARB, "GL_ARB_ES3_2_compatibility") {
"GL_PRIMITIVE_BOUNDING_BOX_ARB"("0x92BE")
"GL_MULTISAMPLE_LINE_WIDTH_RANGE_ARB"("0x9381")
"GL_MULTISAMPLE_LINE_WIDTH_GRANULARITY_ARB"("0x9382")
"glPrimitiveBoundingBoxARB"(
void,
GLfloat("minX"),
GLfloat("minY"),
GLfloat("minZ"),
GLfloat("minW"),
GLfloat("maxX"),
GLfloat("maxY"),
GLfloat("maxZ"),
GLfloat("maxW")
)
}
file("BindlessTexture", ARB, "GL_ARB_bindless_texture") {
"GL_UNSIGNED_INT64_ARB"("0x140F")
"glGetTextureHandleARB"(GLuint64, GLuint("texture"))
"glGetTextureSamplerHandleARB"(GLuint64, GLuint("texture"), GLuint("sampler"))
"glMakeTextureHandleResidentARB"(void, GLuint64("handle"))
"glMakeTextureHandleNonResidentARB"(void, GLuint64("handle"))
"glGetImageHandleARB"(
GLuint64,
GLuint("texture"),
GLint("level"),
GLboolean("layered"),
GLint("layer"),
GLenum("format")
)
"glMakeImageHandleResidentARB"(void, GLuint64("handle"), GLenum("access"))
"glMakeImageHandleNonResidentARB"(void, GLuint64("handle"))
"glUniformHandleui64ARB"(void, GLint("location"), GLuint64("value"))
"glUniformHandleui64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLuint64 *"))
"glProgramUniformHandleui64ARB"(void, GLuint("program"), GLint("location"), GLuint64("value"))
"glProgramUniformHandleui64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("values", "const GLuint64 *")
)
"glIsTextureHandleResidentARB"(GLboolean, GLuint64("handle"))
"glIsImageHandleResidentARB"(GLboolean, GLuint64("handle"))
"glVertexAttribL1ui64ARB"(void, GLuint("index"), GLuint64EXT("x"))
"glVertexAttribL1ui64vARB"(void, GLuint("index"), address("v", "const GLuint64EXT *"))
"glGetVertexAttribLui64vARB"(void, GLuint("index"), GLenum("pname"), address("params", "GLuint64EXT *"))
}
file("CLEvent", ARB, "GL_ARB_cl_event") {
"GL_SYNC_CL_EVENT_ARB"("0x8240")
"GL_SYNC_CL_EVENT_COMPLETE_ARB"("0x8241")
"glCreateSyncFromCLeventARB"(
address,
address("context", "struct _cl_context *"),
address("event", "struct _cl_event *"),
GLbitfield("flags"),
nativeType = "GLsync"
)
}
file("ColorBufferFloat", ARB, "GL_ARB_color_buffer_float") {
"GL_RGBA_FLOAT_MODE_ARB"("0x8820")
"GL_CLAMP_VERTEX_COLOR_ARB"("0x891A")
"GL_CLAMP_FRAGMENT_COLOR_ARB"("0x891B")
"GL_CLAMP_READ_COLOR_ARB"("0x891C")
"GL_FIXED_ONLY_ARB"("0x891D")
"glClampColorARB"(void, GLenum("target"), GLenum("clamp"))
}
file("ComputeVariableGroupSize", ARB, "GL_ARB_compute_variable_group_size") {
"GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB"("0x9344")
"GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB"("0x90EB")
"GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB"("0x9345")
"GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB"("0x91BF")
"glDispatchComputeGroupSizeARB"(
void,
GLuint("num_groups_x"),
GLuint("num_groups_y"),
GLuint("num_groups_z"),
GLuint("group_size_x"),
GLuint("group_size_y"),
GLuint("group_size_z")
)
}
file("DebugOutput", ARB, "GL_ARB_debug_output") {
"GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB"("0x8242")
"GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB"("0x8243")
"GL_DEBUG_CALLBACK_FUNCTION_ARB"("0x8244")
"GL_DEBUG_CALLBACK_USER_PARAM_ARB"("0x8245")
"GL_DEBUG_SOURCE_API_ARB"("0x8246")
"GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB"("0x8247")
"GL_DEBUG_SOURCE_SHADER_COMPILER_ARB"("0x8248")
"GL_DEBUG_SOURCE_THIRD_PARTY_ARB"("0x8249")
"GL_DEBUG_SOURCE_APPLICATION_ARB"("0x824A")
"GL_DEBUG_SOURCE_OTHER_ARB"("0x824B")
"GL_DEBUG_TYPE_ERROR_ARB"("0x824C")
"GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB"("0x824D")
"GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB"("0x824E")
"GL_DEBUG_TYPE_PORTABILITY_ARB"("0x824F")
"GL_DEBUG_TYPE_PERFORMANCE_ARB"("0x8250")
"GL_DEBUG_TYPE_OTHER_ARB"("0x8251")
"GL_MAX_DEBUG_MESSAGE_LENGTH_ARB"("0x9143")
"GL_MAX_DEBUG_LOGGED_MESSAGES_ARB"("0x9144")
"GL_DEBUG_LOGGED_MESSAGES_ARB"("0x9145")
"GL_DEBUG_SEVERITY_HIGH_ARB"("0x9146")
"GL_DEBUG_SEVERITY_MEDIUM_ARB"("0x9147")
"GL_DEBUG_SEVERITY_LOW_ARB"("0x9148")
"glDebugMessageControlARB"(
void,
GLenum("source"),
GLenum("type"),
GLenum("severity"),
GLsizei("count"),
address("ids", "const GLuint *"),
GLboolean("enabled")
)
"glDebugMessageInsertARB"(
void,
GLenum("source"),
GLenum("type"),
GLuint("id"),
GLenum("severity"),
GLsizei("length"),
address("buf", "const GLchar *")
)
("glDebugMessageCallbackARB"(
void,
address("callback", "GLDEBUGPROCARB"),
address("userParam", "const void *")
)) {
"glDebugMessageCallbackARB"(
void,
"glDebugMessageCallbackARB(callback.stub(arena), userParam);",
arena("arena"),
Type("overrungl.opengl.GLDebugProc", null)("callback"),
address("userParam", "const void *")
)
}
"glGetDebugMessageLogARB"(
GLuint,
GLuint("count"),
GLsizei("bufSize"),
address("sources", "GLenum *"),
address("types", "GLenum *"),
address("ids", "GLuint *"),
address("severities", "GLenum *"),
address("lengths", "GLsizei *"),
address("messageLog", "GLchar *")
)
}
file(
"DepthTexture", ARB, "GL_ARB_depth_texture",
"GL_DEPTH_COMPONENT16_ARB" to "0x81A5",
"GL_DEPTH_COMPONENT24_ARB" to "0x81A6",
"GL_DEPTH_COMPONENT32_ARB" to "0x81A7",
"GL_TEXTURE_DEPTH_SIZE_ARB" to "0x884A",
"GL_DEPTH_TEXTURE_MODE_ARB" to "0x884B"
)
file("DrawBuffers", ARB, "GL_ARB_draw_buffers") {
"GL_MAX_DRAW_BUFFERS_ARB"("0x8824")
"GL_DRAW_BUFFER0_ARB"("0x8825")
"GL_DRAW_BUFFER1_ARB"("0x8826")
"GL_DRAW_BUFFER2_ARB"("0x8827")
"GL_DRAW_BUFFER3_ARB"("0x8828")
"GL_DRAW_BUFFER4_ARB"("0x8829")
"GL_DRAW_BUFFER5_ARB"("0x882A")
"GL_DRAW_BUFFER6_ARB"("0x882B")
"GL_DRAW_BUFFER7_ARB"("0x882C")
"GL_DRAW_BUFFER8_ARB"("0x882D")
"GL_DRAW_BUFFER9_ARB"("0x882E")
"GL_DRAW_BUFFER10_ARB"("0x882F")
"GL_DRAW_BUFFER11_ARB"("0x8830")
"GL_DRAW_BUFFER12_ARB"("0x8831")
"GL_DRAW_BUFFER13_ARB"("0x8832")
"GL_DRAW_BUFFER14_ARB"("0x8833")
"GL_DRAW_BUFFER15_ARB"("0x8834")
"glDrawBuffersARB"(void, GLsizei("n"), address("bufs", "const GLenum *"))
}
file("DrawBuffersBlend", ARB, "GL_ARB_draw_buffers_blend") {
"glBlendEquationiARB"(void, GLuint("buf"), GLenum("mode"))
"glBlendEquationSeparateiARB"(void, GLuint("buf"), GLenum("modeRGB"), GLenum("modeAlpha"))
"glBlendFunciARB"(void, GLuint("buf"), GLenum("src"), GLenum("dst"))
"glBlendFuncSeparateiARB"(
void,
GLuint("buf"),
GLenum("srcRGB"),
GLenum("dstRGB"),
GLenum("srcAlpha"),
GLenum("dstAlpha")
)
}
file("DrawInstanced", ARB, "GL_ARB_draw_instanced") {
"glDrawArraysInstancedARB"(void, GLenum("mode"), GLint("first"), GLsizei("count"), GLsizei("primcount"))
"glDrawElementsInstancedARB"(
void,
GLenum("mode"),
GLsizei("count"),
GLenum("type"),
address("indices", "const void *"),
GLsizei("primcount")
)
}
file("FragmentProgram", ARB, "GL_ARB_fragment_program") {
"GL_FRAGMENT_PROGRAM_ARB"("0x8804")
"GL_PROGRAM_FORMAT_ASCII_ARB"("0x8875")
"GL_PROGRAM_LENGTH_ARB"("0x8627")
"GL_PROGRAM_FORMAT_ARB"("0x8876")
"GL_PROGRAM_BINDING_ARB"("0x8677")
"GL_PROGRAM_INSTRUCTIONS_ARB"("0x88A0")
"GL_MAX_PROGRAM_INSTRUCTIONS_ARB"("0x88A1")
"GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB"("0x88A2")
"GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB"("0x88A3")
"GL_PROGRAM_TEMPORARIES_ARB"("0x88A4")
"GL_MAX_PROGRAM_TEMPORARIES_ARB"("0x88A5")
"GL_PROGRAM_NATIVE_TEMPORARIES_ARB"("0x88A6")
"GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB"("0x88A7")
"GL_PROGRAM_PARAMETERS_ARB"("0x88A8")
"GL_MAX_PROGRAM_PARAMETERS_ARB"("0x88A9")
"GL_PROGRAM_NATIVE_PARAMETERS_ARB"("0x88AA")
"GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB"("0x88AB")
"GL_PROGRAM_ATTRIBS_ARB"("0x88AC")
"GL_MAX_PROGRAM_ATTRIBS_ARB"("0x88AD")
"GL_PROGRAM_NATIVE_ATTRIBS_ARB"("0x88AE")
"GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB"("0x88AF")
"GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB"("0x88B4")
"GL_MAX_PROGRAM_ENV_PARAMETERS_ARB"("0x88B5")
"GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB"("0x88B6")
"GL_PROGRAM_ALU_INSTRUCTIONS_ARB"("0x8805")
"GL_PROGRAM_TEX_INSTRUCTIONS_ARB"("0x8806")
"GL_PROGRAM_TEX_INDIRECTIONS_ARB"("0x8807")
"GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB"("0x8808")
"GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB"("0x8809")
"GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB"("0x880A")
"GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB"("0x880B")
"GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB"("0x880C")
"GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB"("0x880D")
"GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB"("0x880E")
"GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB"("0x880F")
"GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB"("0x8810")
"GL_PROGRAM_STRING_ARB"("0x8628")
"GL_PROGRAM_ERROR_POSITION_ARB"("0x864B")
"GL_CURRENT_MATRIX_ARB"("0x8641")
"GL_TRANSPOSE_CURRENT_MATRIX_ARB"("0x88B7")
"GL_CURRENT_MATRIX_STACK_DEPTH_ARB"("0x8640")
"GL_MAX_PROGRAM_MATRICES_ARB"("0x862F")
"GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB"("0x862E")
"GL_MAX_TEXTURE_COORDS_ARB"("0x8871")
"GL_MAX_TEXTURE_IMAGE_UNITS_ARB"("0x8872")
"GL_PROGRAM_ERROR_STRING_ARB"("0x8874")
"GL_MATRIX0_ARB"("0x88C0")
"GL_MATRIX1_ARB"("0x88C1")
"GL_MATRIX2_ARB"("0x88C2")
"GL_MATRIX3_ARB"("0x88C3")
"GL_MATRIX4_ARB"("0x88C4")
"GL_MATRIX5_ARB"("0x88C5")
"GL_MATRIX6_ARB"("0x88C6")
"GL_MATRIX7_ARB"("0x88C7")
"GL_MATRIX8_ARB"("0x88C8")
"GL_MATRIX9_ARB"("0x88C9")
"GL_MATRIX10_ARB"("0x88CA")
"GL_MATRIX11_ARB"("0x88CB")
"GL_MATRIX12_ARB"("0x88CC")
"GL_MATRIX13_ARB"("0x88CD")
"GL_MATRIX14_ARB"("0x88CE")
"GL_MATRIX15_ARB"("0x88CF")
"GL_MATRIX16_ARB"("0x88D0")
"GL_MATRIX17_ARB"("0x88D1")
"GL_MATRIX18_ARB"("0x88D2")
"GL_MATRIX19_ARB"("0x88D3")
"GL_MATRIX20_ARB"("0x88D4")
"GL_MATRIX21_ARB"("0x88D5")
"GL_MATRIX22_ARB"("0x88D6")
"GL_MATRIX23_ARB"("0x88D7")
"GL_MATRIX24_ARB"("0x88D8")
"GL_MATRIX25_ARB"("0x88D9")
"GL_MATRIX26_ARB"("0x88DA")
"GL_MATRIX27_ARB"("0x88DB")
"GL_MATRIX28_ARB"("0x88DC")
"GL_MATRIX29_ARB"("0x88DD")
"GL_MATRIX30_ARB"("0x88DE")
"GL_MATRIX31_ARB"("0x88DF")
"glProgramStringARB"(
void,
GLenum("target"),
GLenum("format"),
GLsizei("len"),
address("string", "const void *")
)
"glBindProgramARB"(void, GLenum("target"), GLuint("program"))
"glDeleteProgramsARB"(void, GLsizei("n"), address("programs", "const GLuint *"))
"glGenProgramsARB"(void, GLsizei("n"), address("programs", "GLuint *"))
"glProgramEnvParameter4dARB"(
void,
GLenum("target"),
GLuint("index"),
GLdouble("x"),
GLdouble("y"),
GLdouble("z"),
GLdouble("w")
)
"glProgramEnvParameter4dvARB"(void, GLenum("target"), GLuint("index"), address("params", "const GLdouble *"))
"glProgramEnvParameter4fARB"(
void,
GLenum("target"),
GLuint("index"),
GLfloat("x"),
GLfloat("y"),
GLfloat("z"),
GLfloat("w")
)
"glProgramEnvParameter4fvARB"(void, GLenum("target"), GLuint("index"), address("params", "const GLfloat *"))
"glProgramLocalParameter4dARB"(
void,
GLenum("target"),
GLuint("index"),
GLdouble("x"),
GLdouble("y"),
GLdouble("z"),
GLdouble("w")
)
"glProgramLocalParameter4dvARB"(void, GLenum("target"), GLuint("index"), address("params", "const GLdouble *"))
"glProgramLocalParameter4fARB"(
void,
GLenum("target"),
GLuint("index"),
GLfloat("x"),
GLfloat("y"),
GLfloat("z"),
GLfloat("w")
)
"glProgramLocalParameter4fvARB"(void, GLenum("target"), GLuint("index"), address("params", "const GLfloat *"))
"glGetProgramEnvParameterdvARB"(void, GLenum("target"), GLuint("index"), address("params", "GLdouble *"))
"glGetProgramEnvParameterfvARB"(void, GLenum("target"), GLuint("index"), address("params", "GLfloat *"))
"glGetProgramLocalParameterdvARB"(void, GLenum("target"), GLuint("index"), address("params", "GLdouble *"))
"glGetProgramLocalParameterfvARB"(void, GLenum("target"), GLuint("index"), address("params", "GLfloat *"))
"glGetProgramivARB"(void, GLenum("target"), GLenum("pname"), address("params", "GLint *"))
"glGetProgramStringARB"(void, GLenum("target"), GLenum("pname"), address("string", "void *"))
"glIsProgramARB"(GLboolean, GLuint("program"))
}
file(
"FragmentShader", ARB, "GL_ARB_fragment_shader",
"GL_FRAGMENT_SHADER_ARB" to "0x8B30",
"GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB" to "0x8B49",
"GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB" to "0x8B8B"
)
file("GeometryShader4", ARB, "GL_ARB_geometry_shader4") {
"GL_LINES_ADJACENCY_ARB"("0x000A")
"GL_LINE_STRIP_ADJACENCY_ARB"("0x000B")
"GL_TRIANGLES_ADJACENCY_ARB"("0x000C")
"GL_TRIANGLE_STRIP_ADJACENCY_ARB"("0x000D")
"GL_PROGRAM_POINT_SIZE_ARB"("0x8642")
"GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB"("0x8C29")
"GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB"("0x8DA7")
"GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB"("0x8DA8")
"GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB"("0x8DA9")
"GL_GEOMETRY_SHADER_ARB"("0x8DD9")
"GL_GEOMETRY_VERTICES_OUT_ARB"("0x8DDA")
"GL_GEOMETRY_INPUT_TYPE_ARB"("0x8DDB")
"GL_GEOMETRY_OUTPUT_TYPE_ARB"("0x8DDC")
"GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB"("0x8DDD")
"GL_MAX_VERTEX_VARYING_COMPONENTS_ARB"("0x8DDE")
"GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB"("0x8DDF")
"GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB"("0x8DE0")
"GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB"("0x8DE1")
"glProgramParameteriARB"(void, GLuint("program"), GLenum("pname"), GLint("value"))
"glFramebufferTextureARB"(void, GLenum("target"), GLenum("attachment"), GLuint("texture"), GLint("level"))
"glFramebufferTextureLayerARB"(
void,
GLenum("target"),
GLenum("attachment"),
GLuint("texture"),
GLint("level"),
GLint("layer")
)
"glFramebufferTextureFaceARB"(
void,
GLenum("target"),
GLenum("attachment"),
GLuint("texture"),
GLint("level"),
GLenum("face")
)
}
file("GLSpirv", ARB, "GL_ARB_gl_spirv") {
"GL_SHADER_BINARY_FORMAT_SPIR_V_ARB"("0x9551")
"GL_SPIR_V_BINARY_ARB"("0x9552")
"glSpecializeShaderARB"(
void,
GLuint("shader"),
address("pEntryPoint", "const GLchar *"),
GLuint("numSpecializationConstants"),
address("pConstantIndex", "const GLuint *"),
address("pConstantValue", "const GLuint *")
)
}
file("GpuShaderInt64", ARB, "GL_ARB_gpu_shader_int64") {
"GL_INT64_ARB"("0x140E")
"GL_INT64_VEC2_ARB"("0x8FE9")
"GL_INT64_VEC3_ARB"("0x8FEA")
"GL_INT64_VEC4_ARB"("0x8FEB")
"GL_UNSIGNED_INT64_VEC2_ARB"("0x8FF5")
"GL_UNSIGNED_INT64_VEC3_ARB"("0x8FF6")
"GL_UNSIGNED_INT64_VEC4_ARB"("0x8FF7")
"glUniform1i64ARB"(void, GLint("location"), GLint64("x"))
"glUniform2i64ARB"(void, GLint("location"), GLint64("x"), GLint64("y"))
"glUniform3i64ARB"(void, GLint("location"), GLint64("x"), GLint64("y"), GLint64("z"))
"glUniform4i64ARB"(void, GLint("location"), GLint64("x"), GLint64("y"), GLint64("z"), GLint64("w"))
"glUniform1i64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLint64 *"))
"glUniform2i64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLint64 *"))
"glUniform3i64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLint64 *"))
"glUniform4i64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLint64 *"))
"glUniform1ui64ARB"(void, GLint("location"), GLuint64("x"))
"glUniform2ui64ARB"(void, GLint("location"), GLuint64("x"), GLuint64("y"))
"glUniform3ui64ARB"(void, GLint("location"), GLuint64("x"), GLuint64("y"), GLuint64("z"))
"glUniform4ui64ARB"(void, GLint("location"), GLuint64("x"), GLuint64("y"), GLuint64("z"), GLuint64("w"))
"glUniform1ui64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLuint64 *"))
"glUniform2ui64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLuint64 *"))
"glUniform3ui64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLuint64 *"))
"glUniform4ui64vARB"(void, GLint("location"), GLsizei("count"), address("value", "const GLuint64 *"))
"glGetUniformi64vARB"(void, GLuint("program"), GLint("location"), address("params", "GLint64 *"))
"glGetUniformui64vARB"(void, GLuint("program"), GLint("location"), address("params", "GLuint64 *"))
"glGetnUniformi64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("bufSize"),
address("params", "GLint64 *")
)
"glGetnUniformui64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("bufSize"),
address("params", "GLuint64 *")
)
"glProgramUniform1i64ARB"(void, GLuint("program"), GLint("location"), GLint64("x"))
"glProgramUniform2i64ARB"(void, GLuint("program"), GLint("location"), GLint64("x"), GLint64("y"))
"glProgramUniform3i64ARB"(void, GLuint("program"), GLint("location"), GLint64("x"), GLint64("y"), GLint64("z"))
"glProgramUniform4i64ARB"(
void,
GLuint("program"),
GLint("location"),
GLint64("x"),
GLint64("y"),
GLint64("z"),
GLint64("w")
)
"glProgramUniform1i64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLint64 *")
)
"glProgramUniform2i64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLint64 *")
)
"glProgramUniform3i64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLint64 *")
)
"glProgramUniform4i64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLint64 *")
)
"glProgramUniform1ui64ARB"(void, GLuint("program"), GLint("location"), GLuint64("x"))
"glProgramUniform2ui64ARB"(void, GLuint("program"), GLint("location"), GLuint64("x"), GLuint64("y"))
"glProgramUniform3ui64ARB"(
void,
GLuint("program"),
GLint("location"),
GLuint64("x"),
GLuint64("y"),
GLuint64("z")
)
"glProgramUniform4ui64ARB"(
void,
GLuint("program"),
GLint("location"),
GLuint64("x"),
GLuint64("y"),
GLuint64("z"),
GLuint64("w")
)
"glProgramUniform1ui64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLuint64 *")
)
"glProgramUniform2ui64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLuint64 *")
)
"glProgramUniform3ui64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLuint64 *")
)
"glProgramUniform4ui64vARB"(
void,
GLuint("program"),
GLint("location"),
GLsizei("count"),
address("value", "const GLuint64 *")
)
}
file("HalfFloatPixel", ARB, "GL_ARB_half_float_pixel", "GL_HALF_FLOAT_ARB" to "0x140B")
file("Imaging", ARB, "GL_ARB_imaging") {
"GL_CONVOLUTION_BORDER_MODE"("0x8013")
"GL_CONVOLUTION_FILTER_SCALE"("0x8014")
"GL_CONVOLUTION_FILTER_BIAS"("0x8015")
"GL_REDUCE"("0x8016")
"GL_CONVOLUTION_FORMAT"("0x8017")
"GL_CONVOLUTION_WIDTH"("0x8018")
"GL_CONVOLUTION_HEIGHT"("0x8019")
"GL_MAX_CONVOLUTION_WIDTH"("0x801A")
"GL_MAX_CONVOLUTION_HEIGHT"("0x801B")
"GL_POST_CONVOLUTION_RED_SCALE"("0x801C")
"GL_POST_CONVOLUTION_GREEN_SCALE"("0x801D")
"GL_POST_CONVOLUTION_BLUE_SCALE"("0x801E")
"GL_POST_CONVOLUTION_ALPHA_SCALE"("0x801F")
"GL_POST_CONVOLUTION_RED_BIAS"("0x8020")
"GL_POST_CONVOLUTION_GREEN_BIAS"("0x8021")
"GL_POST_CONVOLUTION_BLUE_BIAS"("0x8022")
"GL_POST_CONVOLUTION_ALPHA_BIAS"("0x8023")
"GL_HISTOGRAM_WIDTH"("0x8026")
"GL_HISTOGRAM_FORMAT"("0x8027")
"GL_HISTOGRAM_RED_SIZE"("0x8028")
"GL_HISTOGRAM_GREEN_SIZE"("0x8029")
"GL_HISTOGRAM_BLUE_SIZE"("0x802A")
"GL_HISTOGRAM_ALPHA_SIZE"("0x802B")
"GL_HISTOGRAM_LUMINANCE_SIZE"("0x802C")
"GL_HISTOGRAM_SINK"("0x802D")
"GL_MINMAX_FORMAT"("0x802F")
"GL_MINMAX_SINK"("0x8030")
"GL_TABLE_TOO_LARGE"("0x8031")
"GL_COLOR_MATRIX"("0x80B1")
"GL_COLOR_MATRIX_STACK_DEPTH"("0x80B2")
"GL_MAX_COLOR_MATRIX_STACK_DEPTH"("0x80B3")
"GL_POST_COLOR_MATRIX_RED_SCALE"("0x80B4")
"GL_POST_COLOR_MATRIX_GREEN_SCALE"("0x80B5")
"GL_POST_COLOR_MATRIX_BLUE_SCALE"("0x80B6")
"GL_POST_COLOR_MATRIX_ALPHA_SCALE"("0x80B7")
"GL_POST_COLOR_MATRIX_RED_BIAS"("0x80B8")
"GL_POST_COLOR_MATRIX_GREEN_BIAS"("0x80B9")
"GL_POST_COLOR_MATRIX_BLUE_BIAS"("0x80BA")
"GL_POST_COLOR_MATRIX_ALPHA_BIAS"("0x80BB")
"GL_COLOR_TABLE_SCALE"("0x80D6")
"GL_COLOR_TABLE_BIAS"("0x80D7")
"GL_COLOR_TABLE_FORMAT"("0x80D8")
"GL_COLOR_TABLE_WIDTH"("0x80D9")
"GL_COLOR_TABLE_RED_SIZE"("0x80DA")
"GL_COLOR_TABLE_GREEN_SIZE"("0x80DB")
"GL_COLOR_TABLE_BLUE_SIZE"("0x80DC")
"GL_COLOR_TABLE_ALPHA_SIZE"("0x80DD")
"GL_COLOR_TABLE_LUMINANCE_SIZE"("0x80DE")
"GL_COLOR_TABLE_INTENSITY_SIZE"("0x80DF")
"GL_CONSTANT_BORDER"("0x8151")
"GL_REPLICATE_BORDER"("0x8153")
"GL_CONVOLUTION_BORDER_COLOR"("0x8154")
"glColorTable"(
void,
GLenum("target"),
GLenum("internalformat"),
GLsizei("width"),
GLenum("format"),
GLenum("type"),
address("table", "const void *")
)
"glColorTableParameterfv"(void, GLenum("target"), GLenum("pname"), address("params", "const GLfloat *"))
"glColorTableParameteriv"(void, GLenum("target"), GLenum("pname"), address("params", "const GLint *"))
"glCopyColorTable"(void, GLenum("target"), GLenum("internalformat"), GLint("x"), GLint("y"), GLsizei("width"))
"glGetColorTable"(void, GLenum("target"), GLenum("format"), GLenum("type"), address("table", "void *"))
"glGetColorTableParameterfv"(void, GLenum("target"), GLenum("pname"), address("params", "GLfloat *"))
"glGetColorTableParameteriv"(void, GLenum("target"), GLenum("pname"), address("params", "GLint *"))
"glColorSubTable"(
void,
GLenum("target"),
GLsizei("start"),
GLsizei("count"),
GLenum("format"),
GLenum("type"),
address("data", "const void *")
)
"glCopyColorSubTable"(void, GLenum("target"), GLsizei("start"), GLint("x"), GLint("y"), GLsizei("width"))
"glConvolutionFilter1D"(
void,
GLenum("target"),
GLenum("internalformat"),
GLsizei("width"),
GLenum("format"),
GLenum("type"),
address("image", "const void *")
)
"glConvolutionFilter2D"(
void,
GLenum("target"),
GLenum("internalformat"),
GLsizei("width"),
GLsizei("height"),
GLenum("format"),
GLenum("type"),
address("image", "const void *")
)
"glConvolutionParameterf"(void, GLenum("target"), GLenum("pname"), GLfloat("params"))
"glConvolutionParameterfv"(void, GLenum("target"), GLenum("pname"), address("params", "const GLfloat *"))
"glConvolutionParameteri"(void, GLenum("target"), GLenum("pname"), GLint("params"))
"glConvolutionParameteriv"(void, GLenum("target"), GLenum("pname"), address("params", "const GLint *"))
"glCopyConvolutionFilter1D"(
void,
GLenum("target"),
GLenum("internalformat"),
GLint("x"),
GLint("y"),
GLsizei("width")
)
"glCopyConvolutionFilter2D"(
void,
GLenum("target"),
GLenum("internalformat"),
GLint("x"),
GLint("y"),
GLsizei("width"),
GLsizei("height")
)
"glGetConvolutionFilter"(void, GLenum("target"), GLenum("format"), GLenum("type"), address("image", "void *"))
"glGetConvolutionParameterfv"(void, GLenum("target"), GLenum("pname"), address("params", "GLfloat *"))
"glGetConvolutionParameteriv"(void, GLenum("target"), GLenum("pname"), address("params", "GLint *"))
"glGetSeparableFilter"(
void,
GLenum("target"),
GLenum("format"),
GLenum("type"),
address("row", "void *"),
address("column", "void *"),
address("span", "void *")
)
"glSeparableFilter2D"(
void,
GLenum("target"),
GLenum("internalformat"),
GLsizei("width"),
GLsizei("height"),
GLenum("format"),
GLenum("type"),
address("row", "const void *"),
address("column", "const void *")
)
"glGetHistogram"(
void,
GLenum("target"),
GLboolean("reset"),
GLenum("format"),
GLenum("type"),
address("values", "void *")
)
"glGetHistogramParameterfv"(void, GLenum("target"), GLenum("pname"), address("params", "GLfloat *"))
"glGetHistogramParameteriv"(void, GLenum("target"), GLenum("pname"), address("params", "GLint *"))
"glGetMinmax"(
void,
GLenum("target"),
GLboolean("reset"),
GLenum("format"),
GLenum("type"),
address("values", "void *")
)
"glGetMinmaxParameterfv"(void, GLenum("target"), GLenum("pname"), address("params", "GLfloat *"))
"glGetMinmaxParameteriv"(void, GLenum("target"), GLenum("pname"), address("params", "GLint *"))
"glHistogram"(void, GLenum("target"), GLsizei("width"), GLenum("internalformat"), GLboolean("sink"))
"glMinmax"(void, GLenum("target"), GLenum("internalformat"), GLboolean("sink"))
"glResetHistogram"(void, GLenum("target"))
"glResetMinmax"(void, GLenum("target"))
}
file("IndirectParameters", ARB, "GL_ARB_indirect_parameters") {
"GL_PARAMETER_BUFFER_ARB"("0x80EE")
"GL_PARAMETER_BUFFER_BINDING_ARB"("0x80EF")
"glMultiDrawArraysIndirectCountARB"(
void,
GLenum("mode"),
address("indirect", "const void *"),
GLintptr("drawcount"),
GLsizei("maxdrawcount"),
GLsizei("stride")
)
"glMultiDrawElementsIndirectCountARB"(
void,
GLenum("mode"),
GLenum("type"),
address("indirect", "const void *"),
GLintptr("drawcount"),
GLsizei("maxdrawcount"),
GLsizei("stride")
)
}
file("InstancedArrays", ARB, "GL_ARB_instanced_arrays") {
"GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB"("0x88FE")
"glVertexAttribDivisorARB"(void, GLuint("index"), GLuint("divisor"))
}
file(
"InternalformatQuery2", ARB, "GL_ARB_internalformat_query2",
"GL_SRGB_DECODE_ARB" to "0x8299",
"GL_VIEW_CLASS_EAC_R11" to "0x9383",
"GL_VIEW_CLASS_EAC_RG11" to "0x9384",
"GL_VIEW_CLASS_ETC2_RGB" to "0x9385",
"GL_VIEW_CLASS_ETC2_RGBA" to "0x9386",
"GL_VIEW_CLASS_ETC2_EAC_RGBA" to "0x9387",
"GL_VIEW_CLASS_ASTC_4x4_RGBA" to "0x9388",
"GL_VIEW_CLASS_ASTC_5x4_RGBA" to "0x9389",
"GL_VIEW_CLASS_ASTC_5x5_RGBA" to "0x938A",
"GL_VIEW_CLASS_ASTC_6x5_RGBA" to "0x938B",
"GL_VIEW_CLASS_ASTC_6x6_RGBA" to "0x938C",
"GL_VIEW_CLASS_ASTC_8x5_RGBA" to "0x938D",
"GL_VIEW_CLASS_ASTC_8x6_RGBA" to "0x938E",
"GL_VIEW_CLASS_ASTC_8x8_RGBA" to "0x938F",
"GL_VIEW_CLASS_ASTC_10x5_RGBA" to "0x9390",
"GL_VIEW_CLASS_ASTC_10x6_RGBA" to "0x9391",
"GL_VIEW_CLASS_ASTC_10x8_RGBA" to "0x9392",
"GL_VIEW_CLASS_ASTC_10x10_RGBA" to "0x9393",
"GL_VIEW_CLASS_ASTC_12x10_RGBA" to "0x9394",
"GL_VIEW_CLASS_ASTC_12x12_RGBA" to "0x9395"
)
file("MatrixPalette", ARB, "GL_ARB_matrix_palette") {
"GL_MATRIX_PALETTE_ARB"("0x8840")
"GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB"("0x8841")
"GL_MAX_PALETTE_MATRICES_ARB"("0x8842")
"GL_CURRENT_PALETTE_MATRIX_ARB"("0x8843")
"GL_MATRIX_INDEX_ARRAY_ARB"("0x8844")
"GL_CURRENT_MATRIX_INDEX_ARB"("0x8845")
"GL_MATRIX_INDEX_ARRAY_SIZE_ARB"("0x8846")
"GL_MATRIX_INDEX_ARRAY_TYPE_ARB"("0x8847")
"GL_MATRIX_INDEX_ARRAY_STRIDE_ARB"("0x8848")
"GL_MATRIX_INDEX_ARRAY_POINTER_ARB"("0x8849")
"glCurrentPaletteMatrixARB"(void, GLint("index"))
"glMatrixIndexubvARB"(void, GLint("size"), address("indices", "const GLubyte *"))
"glMatrixIndexusvARB"(void, GLint("size"), address("indices", "const GLushort *"))
"glMatrixIndexuivARB"(void, GLint("size"), address("indices", "const GLuint *"))
"glMatrixIndexPointerARB"(
void,
GLint("size"),
GLenum("type"),
GLsizei("stride"),
address("pointer", "const void *")
)
}
file("Multisample", ARB, "GL_ARB_multisample") {
"GL_MULTISAMPLE_ARB"("0x809D")
"GL_SAMPLE_ALPHA_TO_COVERAGE_ARB"("0x809E")
"GL_SAMPLE_ALPHA_TO_ONE_ARB"("0x809F")
"GL_SAMPLE_COVERAGE_ARB"("0x80A0")
"GL_SAMPLE_BUFFERS_ARB"("0x80A8")
"GL_SAMPLES_ARB"("0x80A9")
"GL_SAMPLE_COVERAGE_VALUE_ARB"("0x80AA")
"GL_SAMPLE_COVERAGE_INVERT_ARB"("0x80AB")
"GL_MULTISAMPLE_BIT_ARB"("0x20000000")
"glSampleCoverageARB"(void, GLfloat("value"), GLboolean("invert"))
}
file("Multitexture", ARB, "GL_ARB_multitexture") {
"GL_TEXTURE0_ARB"("0x84C0")
"GL_TEXTURE1_ARB"("0x84C1")
"GL_TEXTURE2_ARB"("0x84C2")
"GL_TEXTURE3_ARB"("0x84C3")
"GL_TEXTURE4_ARB"("0x84C4")
"GL_TEXTURE5_ARB"("0x84C5")
"GL_TEXTURE6_ARB"("0x84C6")
"GL_TEXTURE7_ARB"("0x84C7")
"GL_TEXTURE8_ARB"("0x84C8")
"GL_TEXTURE9_ARB"("0x84C9")
"GL_TEXTURE10_ARB"("0x84CA")
"GL_TEXTURE11_ARB"("0x84CB")
"GL_TEXTURE12_ARB"("0x84CC")
"GL_TEXTURE13_ARB"("0x84CD")
"GL_TEXTURE14_ARB"("0x84CE")
"GL_TEXTURE15_ARB"("0x84CF")
"GL_TEXTURE16_ARB"("0x84D0")
"GL_TEXTURE17_ARB"("0x84D1")
"GL_TEXTURE18_ARB"("0x84D2")
"GL_TEXTURE19_ARB"("0x84D3")
"GL_TEXTURE20_ARB"("0x84D4")
"GL_TEXTURE21_ARB"("0x84D5")
"GL_TEXTURE22_ARB"("0x84D6")
"GL_TEXTURE23_ARB"("0x84D7")
"GL_TEXTURE24_ARB"("0x84D8")
"GL_TEXTURE25_ARB"("0x84D9")
"GL_TEXTURE26_ARB"("0x84DA")
"GL_TEXTURE27_ARB"("0x84DB")
"GL_TEXTURE28_ARB"("0x84DC")
"GL_TEXTURE29_ARB"("0x84DD")
"GL_TEXTURE30_ARB"("0x84DE")
"GL_TEXTURE31_ARB"("0x84DF")
"GL_ACTIVE_TEXTURE_ARB"("0x84E0")
"GL_CLIENT_ACTIVE_TEXTURE_ARB"("0x84E1")
"GL_MAX_TEXTURE_UNITS_ARB"("0x84E2")
"glActiveTextureARB"(void, GLenum("texture"))
"glClientActiveTextureARB"(void, GLenum("texture"))
"glMultiTexCoord1dARB"(void, GLenum("target"), GLdouble("s"))
"glMultiTexCoord1dvARB"(void, GLenum("target"), address("v", "const GLdouble *"))
"glMultiTexCoord1fARB"(void, GLenum("target"), GLfloat("s"))
"glMultiTexCoord1fvARB"(void, GLenum("target"), address("v", "const GLfloat *"))
"glMultiTexCoord1iARB"(void, GLenum("target"), GLint("s"))
"glMultiTexCoord1ivARB"(void, GLenum("target"), address("v", "const GLint *"))
"glMultiTexCoord1sARB"(void, GLenum("target"), GLshort("s"))
"glMultiTexCoord1svARB"(void, GLenum("target"), address("v", "const GLshort *"))
"glMultiTexCoord2dARB"(void, GLenum("target"), GLdouble("s"), GLdouble("t"))
"glMultiTexCoord2dvARB"(void, GLenum("target"), address("v", "const GLdouble *"))
"glMultiTexCoord2fARB"(void, GLenum("target"), GLfloat("s"), GLfloat("t"))
"glMultiTexCoord2fvARB"(void, GLenum("target"), address("v", "const GLfloat *"))
"glMultiTexCoord2iARB"(void, GLenum("target"), GLint("s"), GLint("t"))
"glMultiTexCoord2ivARB"(void, GLenum("target"), address("v", "const GLint *"))
"glMultiTexCoord2sARB"(void, GLenum("target"), GLshort("s"), GLshort("t"))
"glMultiTexCoord2svARB"(void, GLenum("target"), address("v", "const GLshort *"))
"glMultiTexCoord3dARB"(void, GLenum("target"), GLdouble("s"), GLdouble("t"), GLdouble("r"))
"glMultiTexCoord3dvARB"(void, GLenum("target"), address("v", "const GLdouble *"))
"glMultiTexCoord3fARB"(void, GLenum("target"), GLfloat("s"), GLfloat("t"), GLfloat("r"))
"glMultiTexCoord3fvARB"(void, GLenum("target"), address("v", "const GLfloat *"))
"glMultiTexCoord3iARB"(void, GLenum("target"), GLint("s"), GLint("t"), GLint("r"))
"glMultiTexCoord3ivARB"(void, GLenum("target"), address("v", "const GLint *"))
"glMultiTexCoord3sARB"(void, GLenum("target"), GLshort("s"), GLshort("t"), GLshort("r"))
"glMultiTexCoord3svARB"(void, GLenum("target"), address("v", "const GLshort *"))
"glMultiTexCoord4dARB"(void, GLenum("target"), GLdouble("s"), GLdouble("t"), GLdouble("r"), GLdouble("q"))
"glMultiTexCoord4dvARB"(void, GLenum("target"), address("v", "const GLdouble *"))
"glMultiTexCoord4fARB"(void, GLenum("target"), GLfloat("s"), GLfloat("t"), GLfloat("r"), GLfloat("q"))
"glMultiTexCoord4fvARB"(void, GLenum("target"), address("v", "const GLfloat *"))
"glMultiTexCoord4iARB"(void, GLenum("target"), GLint("s"), GLint("t"), GLint("r"), GLint("q"))
"glMultiTexCoord4ivARB"(void, GLenum("target"), address("v", "const GLint *"))
"glMultiTexCoord4sARB"(void, GLenum("target"), GLshort("s"), GLshort("t"), GLshort("r"), GLshort("q"))
"glMultiTexCoord4svARB"(void, GLenum("target"), address("v", "const GLshort *"))
}
file("OcclusionQuery", ARB, "GL_ARB_occlusion_query") {
"GL_QUERY_COUNTER_BITS_ARB"("0x8864")
"GL_CURRENT_QUERY_ARB"("0x8865")
"GL_QUERY_RESULT_ARB"("0x8866")
"GL_QUERY_RESULT_AVAILABLE_ARB"("0x8867")
"GL_SAMPLES_PASSED_ARB"("0x8914")
"glGenQueriesARB"(void, GLsizei("n"), address("ids", "GLuint *"))
"glDeleteQueriesARB"(void, GLsizei("n"), address("ids", "const GLuint *"))
"glIsQueryARB"(GLboolean, GLuint("id"))
"glBeginQueryARB"(void, GLenum("target"), GLuint("id"))
"glEndQueryARB"(void, GLenum("target"))
"glGetQueryivARB"(void, GLenum("target"), GLenum("pname"), address("params", "GLint *"))
"glGetQueryObjectivARB"(void, GLuint("id"), GLenum("pname"), address("params", "GLint *"))
"glGetQueryObjectuivARB"(void, GLuint("id"), GLenum("pname"), address("params", "GLuint *"))
}
file("ParallelShaderCompile", ARB, "GL_ARB_parallel_shader_compile") {
"GL_MAX_SHADER_COMPILER_THREADS_ARB"("0x91B0")
"GL_COMPLETION_STATUS_ARB"("0x91B1")
"glMaxShaderCompilerThreadsARB"(void, GLuint("count"))
}
file(
"PipelineStatisticsQuery", ARB, "GL_ARB_pipeline_statistics_query",
"GL_VERTICES_SUBMITTED_ARB" to "0x82EE",
"GL_PRIMITIVES_SUBMITTED_ARB" to "0x82EF",
"GL_VERTEX_SHADER_INVOCATIONS_ARB" to "0x82F0",
"GL_TESS_CONTROL_SHADER_PATCHES_ARB" to "0x82F1",
"GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB" to "0x82F2",
"GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB" to "0x82F3",
"GL_FRAGMENT_SHADER_INVOCATIONS_ARB" to "0x82F4",
"GL_COMPUTE_SHADER_INVOCATIONS_ARB" to "0x82F5",
"GL_CLIPPING_INPUT_PRIMITIVES_ARB" to "0x82F6",
"GL_CLIPPING_OUTPUT_PRIMITIVES_ARB" to "0x82F7"
)
file(
"PixelBufferObject", ARB, "GL_ARB_pixel_buffer_object",
"GL_PIXEL_PACK_BUFFER_ARB" to "0x88EB",
"GL_PIXEL_UNPACK_BUFFER_ARB" to "0x88EC",
"GL_PIXEL_PACK_BUFFER_BINDING_ARB" to "0x88ED",
"GL_PIXEL_UNPACK_BUFFER_BINDING_ARB" to "0x88EF"
)
file("PointParameters", ARB, "GL_ARB_point_parameters") {
"GL_POINT_SIZE_MIN_ARB"("0x8126")
"GL_POINT_SIZE_MAX_ARB"("0x8127")
"GL_POINT_FADE_THRESHOLD_SIZE_ARB"("0x8128")
"GL_POINT_DISTANCE_ATTENUATION_ARB"("0x8129")
"glPointParameterfARB"(void, GLenum("pname"), GLfloat("param"))
"glPointParameterfvARB"(void, GLenum("pname"), address("params", "const GLfloat *"))
}
file(
"PointSprite", ARB, "GL_ARB_point_sprite",
"GL_POINT_SPRITE_ARB" to "0x8861",
"GL_COORD_REPLACE_ARB" to "0x8862"
)
file("Robustness", ARB, "GL_ARB_robustness") {
"GL_NO_RESET_NOTIFICATION_ARB"("0x8261")
"GL_RESET_NOTIFICATION_STRATEGY_ARB"("0x8256")
"GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB"("0x00000004")
"GL_UNKNOWN_CONTEXT_RESET_ARB"("0x8255")
"GL_LOSE_CONTEXT_ON_RESET_ARB"("0x8252")
"GL_INNOCENT_CONTEXT_RESET_ARB"("0x8254")
"GL_GUILTY_CONTEXT_RESET_ARB"("0x8253")
"glGetGraphicsResetStatusARB"(int)
"glGetnCompressedTexImageARB"(void, int("target"), int("lod"), int("bufSize"), address("img", "void*"))
"glGetnTexImageARB"(
void,
int("target"),
int("level"),
int("format"),
int("type"),
int("bufSize"),
address("img", "void*")
)
"glGetnUniformdvARB"(void, int("program"), int("location"), int("bufSize"), address("params", "GLdouble*"))
"glGetnUniformfvARB"(void, int("program"), int("location"), int("bufSize"), address("params", "GLfloat*"))
"glGetnUniformivARB"(void, int("program"), int("location"), int("bufSize"), address("params", "GLint*"))
"glGetnUniformuivARB"(void, int("program"), int("location"), int("bufSize"), address("params", "GLuint*"))
"glReadnPixelsARB"(
void,
int("x"),
int("y"),
int("width"),
int("height"),
int("format"),
int("type"),
int("bufSize"),
address("data", "void*")
)
}
file("SampleLocations", ARB, "GL_ARB_sample_locations") {
"GL_SAMPLE_LOCATION_SUBPIXEL_BITS_ARB"("0x933D")
"GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_ARB"("0x933E")
"GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_ARB"("0x933F")
"GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_ARB"("0x9340")
"GL_SAMPLE_LOCATION_ARB"("0x8E50")
"GL_PROGRAMMABLE_SAMPLE_LOCATION_ARB"("0x9341")
"GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB"("0x9342")
"GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB"("0x9343")
"glEvaluateDepthValuesARB"(void)
"glFramebufferSampleLocationsfvARB"(
void,
int("target"),
int("start"),
int("count"),
address("v", "const GLfloat *v")
)
"glNamedFramebufferSampleLocationsfvARB"(
void,
int("framebuffer"),
int("start"),
int("count"),
address("v", "const GLfloat *v")
)
}
file("SampleShading", ARB, "GL_ARB_sample_shading") {
"GL_SAMPLE_SHADING_ARB"("0x8C36")
"GL_MIN_SAMPLE_SHADING_VALUE_ARB"("0x8C37")
"glMinSampleShadingARB"(void, float("value"))
}
file("ShaderObjects", ARB, "GL_ARB_shader_objects") {
"GL_PROGRAM_OBJECT_ARB"("0x8B40")
"GL_SHADER_OBJECT_ARB"("0x8B48")
"GL_OBJECT_TYPE_ARB"("0x8B4E")
"GL_OBJECT_SUBTYPE_ARB"("0x8B4F")
"GL_FLOAT_VEC2_ARB"("0x8B50")
"GL_FLOAT_VEC3_ARB"("0x8B51")
"GL_FLOAT_VEC4_ARB"("0x8B52")
"GL_INT_VEC2_ARB"("0x8B53")
"GL_INT_VEC3_ARB"("0x8B54")
"GL_INT_VEC4_ARB"("0x8B55")
"GL_BOOL_ARB"("0x8B56")
"GL_BOOL_VEC2_ARB"("0x8B57")
"GL_BOOL_VEC3_ARB"("0x8B58")
"GL_BOOL_VEC4_ARB"("0x8B59")
"GL_FLOAT_MAT2_ARB"("0x8B5A")
"GL_FLOAT_MAT3_ARB"("0x8B5B")
"GL_FLOAT_MAT4_ARB"("0x8B5C")
"GL_SAMPLER_1D_ARB"("0x8B5D")
"GL_SAMPLER_2D_ARB"("0x8B5E")
"GL_SAMPLER_3D_ARB"("0x8B5F")
"GL_SAMPLER_CUBE_ARB"("0x8B60")
"GL_SAMPLER_1D_SHADOW_ARB"("0x8B61")
"GL_SAMPLER_2D_SHADOW_ARB"("0x8B62")
"GL_SAMPLER_2D_RECT_ARB"("0x8B63")
"GL_SAMPLER_2D_RECT_SHADOW_ARB"("0x8B64")
"GL_OBJECT_DELETE_STATUS_ARB"("0x8B80")
"GL_OBJECT_COMPILE_STATUS_ARB"("0x8B81")
"GL_OBJECT_LINK_STATUS_ARB"("0x8B82")
"GL_OBJECT_VALIDATE_STATUS_ARB"("0x8B83")
"GL_OBJECT_INFO_LOG_LENGTH_ARB"("0x8B84")
"GL_OBJECT_ATTACHED_OBJECTS_ARB"("0x8B85")
"GL_OBJECT_ACTIVE_UNIFORMS_ARB"("0x8B86")
"GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB"("0x8B87")
"GL_OBJECT_SHADER_SOURCE_LENGTH_ARB"("0x8B88")
"glDeleteObjectARB"(void, int("obj"))
"glGetHandleARB"(int, int("pname"))
"glDetachObjectARB"(void, int("containerObj"), int("attachedObj"))
"glCreateShaderObjectARB"(int, int("shaderType"))
"glShaderSourceARB"(
void,
int("shaderObj"),
int("count"),
address("string", "const GLcharARB**"),
address("length", "const GLint*")
)
"glCompileShaderARB"(void, int("shaderObj"))
"glCreateProgramObjectARB"(int)
"glAttachObjectARB"(void, int("containerObj"), int("obj"))
"glLinkProgramARB"(void, int("programObj"))
"glUseProgramObjectARB"(void, int("programObj"))
"glValidateProgramARB"(void, int("programObj"))
"glUniform1fARB"(void, int("location"), float("v0"))
"glUniform2fARB"(void, int("location"), float("v0"), float("v1"))
"glUniform3fARB"(void, int("location"), float("v0"), float("v1"), float("v2"))
"glUniform4fARB"(void, int("location"), float("v0"), float("v1"), float("v2"), float("v3"))
"glUniform1iARB"(void, int("location"), int("v0"))
"glUniform2iARB"(void, int("location"), int("v0"), int("v1"))
"glUniform3iARB"(void, int("location"), int("v0"), int("v1"), int("v2"))
"glUniform4iARB"(void, int("location"), int("v0"), int("v1"), int("v2"), int("v3"))
"glUniform1fvARB"(void, int("location"), int("count"), address("value", "const GLfloat*"))
"glUniform2fvARB"(void, int("location"), int("count"), address("value", "const GLfloat*"))
"glUniform3fvARB"(void, int("location"), int("count"), address("value", "const GLfloat*"))
"glUniform4fvARB"(void, int("location"), int("count"), address("value", "const GLfloat*"))
"glUniform1ivARB"(void, int("location"), int("count"), address("value", "const GLint*"))
"glUniform2ivARB"(void, int("location"), int("count"), address("value", "const GLint*"))
"glUniform3ivARB"(void, int("location"), int("count"), address("value", "const GLint*"))
"glUniform4ivARB"(void, int("location"), int("count"), address("value", "const GLint*"))
"glUniformMatrix2fvARB"(
void,
int("location"),
int("count"),
boolean("transpose"),
address("value", "const GLfloat*")
)
"glUniformMatrix3fvARB"(
void,
int("location"),
int("count"),
boolean("transpose"),
address("value", "const GLfloat*")
)
"glUniformMatrix4fvARB"(
void,
int("location"),
int("count"),
boolean("transpose"),
address("value", "const GLfloat*")
)
"glGetObjectParameterfvARB"(void, int("obj"), int("pname"), address("params", "GLfloat*"))
"glGetObjectParameterivARB"(void, int("obj"), int("pname"), address("params", "GLint*"))
"glGetInfoLogARB"(
void,
int("obj"),
int("maxLength"),
address("length", "GLsizei*"),
address("infoLog", "GLcharARB*")
)
"glGetAttachedObjectsARB"(
void,
int("containerObj"),
int("maxCount"),
address("count", "GLsizei*"),
address("obj", "GLhandleARB*")
)
"glGetUniformLocationARB"(int, int("programObj"), address("name", "const GLcharARB*"))
"glGetActiveUniformARB"(
void,
int("programObj"),
int("index"),
int("maxLength"),
address("length", "GLsizei*"),
address("size", "GLint*"),
address("type", "GLenum*"),
address("name", "GLcharARB*")
)
"glGetUniformfvARB"(void, int("programObj"), int("location"), address("params", "GLfloat*"))
"glGetUniformivARB"(void, int("programObj"), int("location"), address("params", "GLint*"))
"glGetShaderSourceARB"(
void,
int("obj"),
int("maxLength"),
address("length", "GLsizei*"),
address("source", "GLcharARB*")
)
}
file("ShadingLanguageInclude", ARB, "GL_ARB_shading_language_include") {
"GL_SHADER_INCLUDE_ARB"("0x8DAE")
"GL_NAMED_STRING_LENGTH_ARB"("0x8DE9")
"GL_NAMED_STRING_TYPE_ARB"("0x8DEA")
"glNamedStringARB"(
void,
int("type"),
int("nameLen"),
address("name", "const GLchar*"),
int("stringLen"),
address("string", "const GLchar*")
)
"glDeleteNamedStringARB"(void, int("nameLen"), address("name", "const GLchar*"))
"glCompileShaderIncludeARB"(
void,
int("shader"),
int("count"),
address("path", "const GLchar *const*"),
address("length", "const GLint*")
)
"glIsNamedStringARB"(boolean, int("nameLen"), address("name", "const GLchar*"))
"glGetNamedStringARB"(
void,
int("nameLen"),
address("name", "const GLchar*"),
int("bufSize"),
address("stringLen", "GLint*"),
address("string", "GLchar*")
)
"glGetNamedStringivARB"(
void,
int("nameLen"),
address("name", "const GLchar*"),
int("pname"),
address("params", "GLint*")
)
}
file(
"Shadow", ARB, "GL_ARB_shadow",
"GL_TEXTURE_COMPARE_MODE_ARB" to "0x884C",
"GL_TEXTURE_COMPARE_FUNC_ARB" to "0x884D",
"GL_COMPARE_R_TO_TEXTURE_ARB" to "0x884E"
)
file(
"ShadowAmbient", ARB, "GL_ARB_shadow_ambient",
"GL_TEXTURE_COMPARE_FAIL_VALUE_ARB" to "0x80BF"
)
file("SparseBuffer", ARB, "GL_ARB_sparse_buffer") {
"GL_SPARSE_STORAGE_BIT_ARB"("0x0400")
"GL_SPARSE_BUFFER_PAGE_SIZE_ARB"("0x82F8")
"glBufferPageCommitmentARB"(void, int("target"), long("offset"), long("size"), boolean("commit"))
"glNamedBufferPageCommitmentEXT"(void, int("buffer"), long("offset"), long("size"), boolean("commit"))
"glNamedBufferPageCommitmentARB"(void, int("buffer"), long("offset"), long("size"), boolean("commit"))
}
file("SparseTexture", ARB, "GL_ARB_sparse_texture") {
"GL_TEXTURE_SPARSE_ARB"("0x91A6")
"GL_VIRTUAL_PAGE_SIZE_INDEX_ARB"("0x91A7")
"GL_NUM_SPARSE_LEVELS_ARB"("0x91AA")
"GL_NUM_VIRTUAL_PAGE_SIZES_ARB"("0x91A8")
"GL_VIRTUAL_PAGE_SIZE_X_ARB"("0x9195")
"GL_VIRTUAL_PAGE_SIZE_Y_ARB"("0x9196")
"GL_VIRTUAL_PAGE_SIZE_Z_ARB"("0x9197")
"GL_MAX_SPARSE_TEXTURE_SIZE_ARB"("0x9198")
"GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB"("0x9199")
"GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB"("0x919A")
"GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB"("0x91A9")
"glTexPageCommitmentARB"(
void,
int("target"),
int("level"),
int("xoffset"),
int("yoffset"),
int("zoffset"),
int("width"),
int("height"),
int("depth"),
boolean("commit")
)
}
file(
"TextureBorderClamp", ARB, "GL_ARB_texture_border_clamp",
"GL_CLAMP_TO_BORDER_ARB" to "0x812D"
)
file("TextureBufferObject", ARB, "GL_ARB_texture_buffer_object") {
"GL_TEXTURE_BUFFER_ARB"("0x8C2A")
"GL_MAX_TEXTURE_BUFFER_SIZE_ARB"("0x8C2B")
"GL_TEXTURE_BINDING_BUFFER_ARB"("0x8C2C")
"GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB"("0x8C2D")
"GL_TEXTURE_BUFFER_FORMAT_ARB"("0x8C2E")
"glTexBufferARB"(void, int("target"), int("internalFormat"), int("buffer"))
}
file("TextureCompression", ARB, "GL_ARB_texture_compression") {
"GL_COMPRESSED_ALPHA_ARB"("0x84E9")
"GL_COMPRESSED_LUMINANCE_ARB"("0x84EA")
"GL_COMPRESSED_LUMINANCE_ALPHA_ARB"("0x84EB")
"GL_COMPRESSED_INTENSITY_ARB"("0x84EC")
"GL_COMPRESSED_RGB_ARB"("0x84ED")
"GL_COMPRESSED_RGBA_ARB"("0x84EE")
"GL_TEXTURE_COMPRESSION_HINT_ARB"("0x84EF")
"GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB"("0x86A0")
"GL_TEXTURE_COMPRESSED_ARB"("0x86A1")
"GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB"("0x86A2")
"GL_COMPRESSED_TEXTURE_FORMATS_ARB"("0x86A3")
"glCompressedTexImage3DARB"(
void,
int("target"),
int("level"),
int("internalFormat"),
int("width"),
int("height"),
int("depth"),
int("border"),
int("imageSize"),
address("data", "const void*")
)
"glCompressedTexImage2DARB"(
void,
int("target"),
int("level"),
int("internalFormat"),
int("width"),
int("height"),
int("border"),
int("imageSize"),
address("data", "const void*")
)
"glCompressedTexImage1DARB"(
void,
int("target"),
int("level"),
int("internalFormat"),
int("width"),
int("border"),
int("imageSize"),
address("data", "const void*")
)
"glCompressedTexSubImage3DARB"(
void,
int("target"),
int("level"),
int("xoffset"),
int("yoffset"),
int("zoffset"),
int("width"),
int("height"),
int("depth"),
int("format"),
int("imageSize"),
address("data", "const void*")
)
"glCompressedTexSubImage2DARB"(
void,
int("target"),
int("level"),
int("xoffset"),
int("yoffset"),
int("width"),
int("height"),
int("format"),
int("imageSize"),
address("data", "const void*")
)
"glCompressedTexSubImage1DARB"(
void,
int("target"),
int("level"),
int("xoffset"),
int("width"),
int("format"),
int("imageSize"),
address("data", "const void*")
)
"glGetCompressedTexImageARB"(void, int("target"), int("level"), address("img", "void*"))
}
file(
"TextureCompressionBptc", ARB, "GL_ARB_texture_compression_bptc",
"GL_COMPRESSED_RGBA_BPTC_UNORM_ARB" to "0x8E8C",
"GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB" to "0x8E8D",
"GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB" to "0x8E8E",
"GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB" to "0x8E8F"
)
file(
"TextureCubeMap", ARB, "GL_ARB_texture_cube_map",
"GL_NORMAL_MAP_ARB" to "0x8511",
"GL_REFLECTION_MAP_ARB" to "0x8512",
"GL_TEXTURE_CUBE_MAP_ARB" to "0x8513",
"GL_TEXTURE_BINDING_CUBE_MAP_ARB" to "0x8514",
"GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB" to "0x8515",
"GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB" to "0x8516",
"GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB" to "0x8517",
"GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB" to "0x8518",
"GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB" to "0x8519",
"GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB" to "0x851A",
"GL_PROXY_TEXTURE_CUBE_MAP_ARB" to "0x851B",
"GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB" to "0x851C"
)
file(
"TextureCubeMapArray", ARB, "GL_ARB_texture_cube_map_array",
"GL_TEXTURE_CUBE_MAP_ARRAY_ARB" to "0x9009",
"GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB" to "0x900A",
"GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB" to "0x900B",
"GL_SAMPLER_CUBE_MAP_ARRAY_ARB" to "0x900C",
"GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB" to "0x900D",
"GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB" to "0x900E",
"GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB" to "0x900F"
)
file(
"TextureEnvCombine", ARB, "GL_ARB_texture_env_combine",
"GL_COMBINE_ARB" to "0x8570",
"GL_COMBINE_RGB_ARB" to "0x8571",
"GL_COMBINE_ALPHA_ARB" to "0x8572",
"GL_SOURCE0_RGB_ARB" to "0x8580",
"GL_SOURCE1_RGB_ARB" to "0x8581",
"GL_SOURCE2_RGB_ARB" to "0x8582",
"GL_SOURCE0_ALPHA_ARB" to "0x8588",
"GL_SOURCE1_ALPHA_ARB" to "0x8589",
"GL_SOURCE2_ALPHA_ARB" to "0x858A",
"GL_OPERAND0_RGB_ARB" to "0x8590",
"GL_OPERAND1_RGB_ARB" to "0x8591",
"GL_OPERAND2_RGB_ARB" to "0x8592",
"GL_OPERAND0_ALPHA_ARB" to "0x8598",
"GL_OPERAND1_ALPHA_ARB" to "0x8599",
"GL_OPERAND2_ALPHA_ARB" to "0x859A",
"GL_RGB_SCALE_ARB" to "0x8573",
"GL_ADD_SIGNED_ARB" to "0x8574",
"GL_INTERPOLATE_ARB" to "0x8575",
"GL_SUBTRACT_ARB" to "0x84E7",
"GL_CONSTANT_ARB" to "0x8576",
"GL_PRIMARY_COLOR_ARB" to "0x8577",
"GL_PREVIOUS_ARB" to "0x8578"
)
file(
"TextureEnvDot3", ARB, "GL_ARB_texture_env_dot3",
"GL_DOT3_RGB_ARB" to "0x86AE",
"GL_DOT3_RGBA_ARB" to "0x86AF"
)
file(
"TextureFilterMinmax", ARB, "GL_ARB_texture_filter_minmax",
"GL_TEXTURE_REDUCTION_MODE_ARB" to "0x9366",
"GL_WEIGHTED_AVERAGE_ARB" to "0x9367"
)
file(
"TextureFloat", ARB, "GL_ARB_texture_float",
"GL_TEXTURE_RED_TYPE_ARB" to "0x8C10",
"GL_TEXTURE_GREEN_TYPE_ARB" to "0x8C11",
"GL_TEXTURE_BLUE_TYPE_ARB" to "0x8C12",
"GL_TEXTURE_ALPHA_TYPE_ARB" to "0x8C13",
"GL_TEXTURE_LUMINANCE_TYPE_ARB" to "0x8C14",
"GL_TEXTURE_INTENSITY_TYPE_ARB" to "0x8C15",
"GL_TEXTURE_DEPTH_TYPE_ARB" to "0x8C16",
"GL_UNSIGNED_NORMALIZED_ARB" to "0x8C17",
"GL_RGBA32F_ARB" to "0x8814",
"GL_RGB32F_ARB" to "0x8815",
"GL_ALPHA32F_ARB" to "0x8816",
"GL_INTENSITY32F_ARB" to "0x8817",
"GL_LUMINANCE32F_ARB" to "0x8818",
"GL_LUMINANCE_ALPHA32F_ARB" to "0x8819",
"GL_RGBA16F_ARB" to "0x881A",
"GL_RGB16F_ARB" to "0x881B",
"GL_ALPHA16F_ARB" to "0x881C",
"GL_INTENSITY16F_ARB" to "0x881D",
"GL_LUMINANCE16F_ARB" to "0x881E",
"GL_LUMINANCE_ALPHA16F_ARB" to "0x881F"
)
file(
"TextureGather", ARB, "GL_ARB_texture_gather",
"GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB" to "0x8E5E",
"GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB" to "0x8E5F",
"GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB" to "0x8F9F"
)
file(
"TextureMirroredRepeat", ARB, "GL_ARB_texture_mirrored_repeat",
"GL_MIRRORED_REPEAT_ARB" to "0x8370"
)
file(
"TextureRectangle", ARB, "GL_ARB_texture_rectangle",
"GL_TEXTURE_RECTANGLE_ARB" to "0x84F5",
"GL_TEXTURE_BINDING_RECTANGLE_ARB" to "0x84F6",
"GL_PROXY_TEXTURE_RECTANGLE_ARB" to "0x84F7",
"GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB" to "0x84F8"
)
file(
"TransformFeedbackOverflowQuery", ARB, "GL_ARB_transform_feedback_overflow_query",
"GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB" to "0x82EC",
"GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB" to "0x82ED"
)
file("TransposeMatrix", ARB, "GL_ARB_transpose_matrix") {
"GL_TRANSPOSE_MODELVIEW_MATRIX_ARB"("0x84E3")
"GL_TRANSPOSE_PROJECTION_MATRIX_ARB"("0x84E4")
"GL_TRANSPOSE_TEXTURE_MATRIX_ARB"("0x84E5")
"GL_TRANSPOSE_COLOR_MATRIX_ARB"("0x84E6")
"glLoadTransposeMatrixfARB"(void, address("m", "const GLfloat*"))
"glLoadTransposeMatrixdARB"(void, address("m", "const GLdouble*"))
"glMultTransposeMatrixfARB"(void, address("m", "const GLfloat*"))
"glMultTransposeMatrixdARB"(void, address("m", "const GLdouble*"))
}
file("VertexBlend", ARB, "GL_ARB_vertex_blend") {
"GL_MAX_VERTEX_UNITS_ARB"("0x86A4")
"GL_ACTIVE_VERTEX_UNITS_ARB"("0x86A5")
"GL_WEIGHT_SUM_UNITY_ARB"("0x86A6")
"GL_VERTEX_BLEND_ARB"("0x86A7")
"GL_CURRENT_WEIGHT_ARB"("0x86A8")
"GL_WEIGHT_ARRAY_TYPE_ARB"("0x86A9")
"GL_WEIGHT_ARRAY_STRIDE_ARB"("0x86AA")
"GL_WEIGHT_ARRAY_SIZE_ARB"("0x86AB")
"GL_WEIGHT_ARRAY_POINTER_ARB"("0x86AC")
"GL_WEIGHT_ARRAY_ARB"("0x86AD")
"GL_MODELVIEW0_ARB"("0x1700")
"GL_MODELVIEW1_ARB"("0x850A")
"GL_MODELVIEW2_ARB"("0x8722")
"GL_MODELVIEW3_ARB"("0x8723")
"GL_MODELVIEW4_ARB"("0x8724")
"GL_MODELVIEW5_ARB"("0x8725")
"GL_MODELVIEW6_ARB"("0x8726")
"GL_MODELVIEW7_ARB"("0x8727")
"GL_MODELVIEW8_ARB"("0x8728")
"GL_MODELVIEW9_ARB"("0x8729")
"GL_MODELVIEW10_ARB"("0x872A")
"GL_MODELVIEW11_ARB"("0x872B")
"GL_MODELVIEW12_ARB"("0x872C")
"GL_MODELVIEW13_ARB"("0x872D")
"GL_MODELVIEW14_ARB"("0x872E")
"GL_MODELVIEW15_ARB"("0x872F")
"GL_MODELVIEW16_ARB"("0x8730")
"GL_MODELVIEW17_ARB"("0x8731")
"GL_MODELVIEW18_ARB"("0x8732")
"GL_MODELVIEW19_ARB"("0x8733")
"GL_MODELVIEW20_ARB"("0x8734")
"GL_MODELVIEW21_ARB"("0x8735")
"GL_MODELVIEW22_ARB"("0x8736")
"GL_MODELVIEW23_ARB"("0x8737")
"GL_MODELVIEW24_ARB"("0x8738")
"GL_MODELVIEW25_ARB"("0x8739")
"GL_MODELVIEW26_ARB"("0x873A")
"GL_MODELVIEW27_ARB"("0x873B")
"GL_MODELVIEW28_ARB"("0x873C")
"GL_MODELVIEW29_ARB"("0x873D")
"GL_MODELVIEW30_ARB"("0x873E")
"GL_MODELVIEW31_ARB"("0x873F")
"glWeightbvARB"(void, GLint("size"), address("weights", "const GLbyte*"))
"glWeightsvARB"(void, GLint("size"), address("weights", "const GLshort*"))
"glWeightivARB"(void, GLint("size"), address("weights", "const GLint*"))
"glWeightfvARB"(void, GLint("size"), address("weights", "const GLfloat*"))
"glWeightdvARB"(void, GLint("size"), address("weights", "const GLdouble*"))
"glWeightubvARB"(void, GLint("size"), address("weights", "const GLubyte*"))
"glWeightusvARB"(void, GLint("size"), address("weights", "const GLushort*"))
"glWeightuivARB"(void, GLint("size"), address("weights", "const GLuint*"))
"glWeightPointerARB"(void, GLint("size"), GLenum("type"), GLsizei("stride"), address("pointer", "const void*"))
"glVertexBlendARB"(void, GLint("count"))
}
file("VertexBufferObject", ARB, "GL_ARB_vertex_buffer_object") {
"GL_BUFFER_SIZE_ARB"("0x8764")
"GL_BUFFER_USAGE_ARB"("0x8765")
"GL_ARRAY_BUFFER_ARB"("0x8892")
"GL_ELEMENT_ARRAY_BUFFER_ARB"("0x8893")
"GL_ARRAY_BUFFER_BINDING_ARB"("0x8894")
"GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB"("0x8895")
"GL_VERTEX_ARRAY_BUFFER_BINDING_ARB"("0x8896")
"GL_NORMAL_ARRAY_BUFFER_BINDING_ARB"("0x8897")
"GL_COLOR_ARRAY_BUFFER_BINDING_ARB"("0x8898")
"GL_INDEX_ARRAY_BUFFER_BINDING_ARB"("0x8899")
"GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB"("0x889A")
"GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB"("0x889B")
"GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB"("0x889C")
"GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB"("0x889D")
"GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB"("0x889E")
"GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB"("0x889F")
"GL_READ_ONLY_ARB"("0x88B8")
"GL_WRITE_ONLY_ARB"("0x88B9")
"GL_READ_WRITE_ARB"("0x88BA")
"GL_BUFFER_ACCESS_ARB"("0x88BB")
"GL_BUFFER_MAPPED_ARB"("0x88BC")
"GL_BUFFER_MAP_POINTER_ARB"("0x88BD")
"GL_STREAM_DRAW_ARB"("0x88E0")
"GL_STREAM_READ_ARB"("0x88E1")
"GL_STREAM_COPY_ARB"("0x88E2")
"GL_STATIC_DRAW_ARB"("0x88E4")
"GL_STATIC_READ_ARB"("0x88E5")
"GL_STATIC_COPY_ARB"("0x88E6")
"GL_DYNAMIC_DRAW_ARB"("0x88E8")
"GL_DYNAMIC_READ_ARB"("0x88E9")
"GL_DYNAMIC_COPY_ARB"("0x88EA")
"glBindBufferARB"(void, GLenum("target"), GLuint("buffer"))
"glDeleteBuffersARB"(void, GLsizei("n"), address("buffers", "const GLuint*"))
"glGenBuffersARB"(void, GLsizei("n"), address("buffers", "GLuint*"))
"glIsBufferARB"(boolean, GLuint("buffer"))
"glBufferDataARB"(
void,
GLenum("target"),
GLsizeiptrARB("size"),
address("data", "const void*"),
GLenum("usage")
)
"glBufferSubDataARB"(
void,
GLenum("target"),
GLintptrARB("offset"),
GLsizeiptrARB("size"),
address("data", "const void*")
)
"glGetBufferSubDataARB"(
void,
GLenum("target"),
GLintptrARB("offset"),
GLsizeiptrARB("size"),
address("data", "void*")
)
"glMapBufferARB"(address, GLenum("target"), GLenum("access"), nativeType = "void*")
"glUnmapBufferARB"(boolean, GLenum("target"))
"glGetBufferParameterivARB"(void, GLenum("target"), GLenum("pname"), address("params", "GLint*"))
"glGetBufferPointervARB"(void, GLenum("target"), GLenum("pname"), address("params", "void**"))
}
file("VertexProgram", ARB, "GL_ARB_vertex_program") {
"GL_COLOR_SUM_ARB"("0x8458")
"GL_VERTEX_PROGRAM_ARB"("0x8620")
"GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB"("0x8622")
"GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB"("0x8623")
"GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB"("0x8624")
"GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB"("0x8625")
"GL_CURRENT_VERTEX_ATTRIB_ARB"("0x8626")
"GL_VERTEX_PROGRAM_POINT_SIZE_ARB"("0x8642")
"GL_VERTEX_PROGRAM_TWO_SIDE_ARB"("0x8643")
"GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB"("0x8645")
"GL_MAX_VERTEX_ATTRIBS_ARB"("0x8869")
"GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB"("0x886A")
"GL_PROGRAM_ADDRESS_REGISTERS_ARB"("0x88B0")
"GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB"("0x88B1")
"GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB"("0x88B2")
"GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB"("0x88B3")
"glVertexAttrib1dARB"(void, GLuint("index"), GLdouble("x"))
"glVertexAttrib1dvARB"(void, GLuint("index"), address("v", "const GLdouble *"))
"glVertexAttrib1fARB"(void, GLuint("index"), GLfloat("x"))
"glVertexAttrib1fvARB"(void, GLuint("index"), address("v", "const GLfloat *"))
"glVertexAttrib1sARB"(void, GLuint("index"), GLshort("x"))
"glVertexAttrib1svARB"(void, GLuint("index"), address("v", "const GLshort *"))
"glVertexAttrib2dARB"(void, GLuint("index"), GLdouble("x"), GLdouble("y"))
"glVertexAttrib2dvARB"(void, GLuint("index"), address("v", "const GLdouble *"))
"glVertexAttrib2fARB"(void, GLuint("index"), GLfloat("x"), GLfloat("y"))
"glVertexAttrib2fvARB"(void, GLuint("index"), address("v", "const GLfloat *"))
"glVertexAttrib2sARB"(void, GLuint("index"), GLshort("x"), GLshort("y"))
"glVertexAttrib2svARB"(void, GLuint("index"), address("v", "const GLshort *"))
"glVertexAttrib3dARB"(void, GLuint("index"), GLdouble("x"), GLdouble("y"), GLdouble("z"))
"glVertexAttrib3dvARB"(void, GLuint("index"), address("v", "const GLdouble *"))
"glVertexAttrib3fARB"(void, GLuint("index"), GLfloat("x"), GLfloat("y"), GLfloat("z"))
"glVertexAttrib3fvARB"(void, GLuint("index"), address("v", "const GLfloat *"))
"glVertexAttrib3sARB"(void, GLuint("index"), GLshort("x"), GLshort("y"), GLshort("z"))
"glVertexAttrib3svARB"(void, GLuint("index"), address("v", "const GLshort *"))
"glVertexAttrib4NbvARB"(void, GLuint("index"), address("v", "const GLbyte *"))
"glVertexAttrib4NivARB"(void, GLuint("index"), address("v", "const GLint *"))
"glVertexAttrib4NsvARB"(void, GLuint("index"), address("v", "const GLshort *"))
"glVertexAttrib4NubARB"(void, GLuint("index"), GLubyte("x"), GLubyte("y"), GLubyte("z"), GLubyte("w"))
"glVertexAttrib4NubvARB"(void, GLuint("index"), address("v", "const GLubyte *"))
"glVertexAttrib4NuivARB"(void, GLuint("index"), address("v", "const GLuint *"))
"glVertexAttrib4NusvARB"(void, GLuint("index"), address("v", "const GLushort *"))
"glVertexAttrib4bvARB"(void, GLuint("index"), address("v", "const GLbyte *"))
"glVertexAttrib4dARB"(void, GLuint("index"), GLdouble("x"), GLdouble("y"), GLdouble("z"), GLdouble("w"))
"glVertexAttrib4dvARB"(void, GLuint("index"), address("v", "const GLdouble *"))
"glVertexAttrib4fARB"(void, GLuint("index"), GLfloat("x"), GLfloat("y"), GLfloat("z"), GLfloat("w"))
"glVertexAttrib4fvARB"(void, GLuint("index"), address("v", "const GLfloat *"))
"glVertexAttrib4ivARB"(void, GLuint("index"), address("v", "const GLint *"))
"glVertexAttrib4sARB"(void, GLuint("index"), GLshort("x"), GLshort("y"), GLshort("z"), GLshort("w"))
"glVertexAttrib4svARB"(void, GLuint("index"), address("v", "const GLshort *"))
"glVertexAttrib4ubvARB"(void, GLuint("index"), address("v", "const GLubyte *"))
"glVertexAttrib4uivARB"(void, GLuint("index"), address("v", "const GLuint *"))
"glVertexAttrib4usvARB"(void, GLuint("index"), address("v", "const GLushort *"))
"glVertexAttribPointerARB"(
void,
GLuint("index"),
GLint("size"),
GLenum("type"),
GLboolean("normalized"),
GLsizei("stride"),
address("pointer", "const void *")
)
"glEnableVertexAttribArrayARB"(void, GLuint("index"))
"glDisableVertexAttribArrayARB"(void, GLuint("index"))
"glGetVertexAttribdvARB"(void, GLuint("index"), GLenum("pname"), address("params", "GLdouble *"))
"glGetVertexAttribfvARB"(void, GLuint("index"), GLenum("pname"), address("params", "GLfloat *"))
"glGetVertexAttribivARB"(void, GLuint("index"), GLenum("pname"), address("params", "GLint *"))
"glGetVertexAttribPointervARB"(void, GLuint("index"), GLenum("pname"), address("pointer", "void **"))
}
file("VertexShader", ARB, "GL_ARB_vertex_shader") {
"GL_VERTEX_SHADER_ARB"("0x8B31")
"GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB"("0x8B4A")
"GL_MAX_VARYING_FLOATS_ARB"("0x8B4B")
"GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB"("0x8B4C")
"GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB"("0x8B4D")
"GL_OBJECT_ACTIVE_ATTRIBUTES_ARB"("0x8B89")
"GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB"("0x8B8A")
"glBindAttribLocationARB"(
void,
GLhandleARB("programObj"),
GLuint("index"),
address("name", "const GLcharARB *")
)
"glGetActiveAttribARB"(
void,
GLhandleARB("programObj"),
GLuint("index"),
GLsizei("maxLength"),
address("length", "GLsizei *"),
address("size", "GLint *"),
address("type", "GLenum *"),
address("name", "GLcharARB *")
)
"glGetAttribLocationARB"(GLint, GLhandleARB("programObj"), address("name", "const GLcharARB *"))
}
file("ViewportArray", ARB, "GL_ARB_viewport_array") {
"glDepthRangeArraydvNV"(void, GLuint("first"), GLsizei("count"), address("v", "const GLdouble *"))
"glDepthRangeIndexeddNV"(void, GLuint("index"), GLdouble("n"), GLdouble("f"))
}
file("WindowPos", ARB, "GL_ARB_window_pos") {
"glWindowPos2dARB"(void, GLdouble("x"), GLdouble("y"))
"glWindowPos2dvARB"(void, address("v", "const GLdouble *"))
"glWindowPos2fARB"(void, GLfloat("x"), GLfloat("y"))
"glWindowPos2fvARB"(void, address("v", "const GLfloat *"))
"glWindowPos2iARB"(void, GLint("x"), GLint("y"))
"glWindowPos2ivARB"(void, address("v", "const GLint *"))
"glWindowPos2sARB"(void, GLshort("x"), GLshort("y"))
"glWindowPos2svARB"(void, address("v", "const GLshort *"))
"glWindowPos3dARB"(void, GLdouble("x"), GLdouble("y"), GLdouble("z"))
"glWindowPos3dvARB"(void, address("v", "const GLdouble *"))
"glWindowPos3fARB"(void, GLfloat("x"), GLfloat("y"), GLfloat("z"))
"glWindowPos3fvARB"(void, address("v", "const GLfloat *"))
"glWindowPos3iARB"(void, GLint("x"), GLint("y"), GLint("z"))
"glWindowPos3ivARB"(void, address("v", "const GLint *"))
"glWindowPos3sARB"(void, GLshort("x"), GLshort("y"), GLshort("z"))
"glWindowPos3svARB"(void, address("v", "const GLshort *"))
}
}
| 4 | Java | 3 | 9 | 9277e69a0da1a2106892c480f73473f892c7d041 | 73,469 | overrungl | MIT License |
app/src/main/java/com/earth/angel/event/SearchEvent.kt | engineerrep | 643,933,914 | false | {"Java": 2291635, "Kotlin": 1651449} | package com.earth.angel.event
class SearchEvent(
var etstr: String,
var type: Int
) | 1 | null | 1 | 1 | 415e0417870b6ff2c84a9798d1f3f3a4e6921354 | 92 | EarthAngel | MIT License |
kotlin-graphql-test/src/main/kotlin/com/junyharangstudy/kotlingraphqltest/api/software/model/dto/request/SoftwareUpdateRequestDto.kt | junyharang-coding-study | 722,094,129 | false | {"Markdown": 253, "Ignore List": 19, "Gradle Kotlin DSL": 2, "XML": 46, "Shell": 2, "Batchfile": 2, "INI": 8, "Kotlin": 76, "YAML": 31, "GraphQL": 45, "Scala": 182, "SQL": 8, "Java": 166, "Motorola 68K Assembly": 9, "Java Properties": 2, "JavaScript": 1335, "JSON with Comments": 17, "JSON": 219, "Dotenv": 1, "Text": 137, "HTML": 6, "EditorConfig": 4, "Protocol Buffer": 14, "Jest Snapshot": 1, "TypeScript": 94, "Makefile": 1, "PureBasic": 4, "robots.txt": 1, "SVG": 1, "CSS": 3, "Gradle": 2} | package com.junyharangstudy.kotlingraphqltest.api.software.model.dto.request
class SoftwareUpdateRequestDto (
var usedBy: String?,
var developedBy: String?,
var description: String?
) | 0 | Java | 3 | 13 | 06f407225b4f544848bb9943cbd425de411276b9 | 196 | GraphQL-Study | MIT License |
XBase/src/main/java/com/danny/xbase/base/Application.kt | dannycx | 643,140,932 | false | {"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 58, "INI": 8, "Proguard": 9, "Kotlin": 149, "XML": 117, "Java": 130, "JSON": 2} | package com.danny.xbase.base
import android.app.Application
import java.lang.ref.WeakReference
/**
* application对象
*
* @author danny
* @since 2020-11-20
*/
object Application {
private var application: WeakReference<Application>? = null
fun register(app: Application) {
synchronized(com.danny.xbase.base.Application::class.java) {
application = WeakReference(app)
}
}
fun get(): Application? {
synchronized(com.danny.xbase.base.Application::class.java) {
return application?.get()
}
}
} | 0 | Java | 0 | 0 | 31020de9d942f1d0013c1bf7a8115decd229e296 | 571 | XLib | Apache License 2.0 |
src/test/java/hes/sudoku/kt/LogicSolverKtTest.kt | Hes-Siemelink | 590,624,559 | false | {"Java": 26516, "Kotlin": 22675} | package hes.sudoku.kt
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
class LogicSolverKtTest {
@Test
fun eliminateBasedOnUniqueSets() {
val cell_0 = Cell(0, 0).replaceCandidates(setOf(1, 2, 3))
val cell_1 = Cell(0, 1).replaceCandidates(setOf(2, 3))
val cell_2 = Cell(0, 2).replaceCandidates(setOf(2, 3))
val cell_3 = Cell(0, 1).replaceCandidates(setOf(4, 5, 6, 7, 8, 9))
val group = Group("Test Group")
group.addCell(cell_0)
group.addCell(cell_1)
group.addCell(cell_2)
group.addCell(cell_3)
val eliminations: MutableSet<Move> = LinkedHashSet()
eliminateBasedOnUniqueSets(group, eliminations)
Assertions.assertThat(eliminations).hasSize(2)
Assertions.assertThat(eliminations).contains(Move(cell_0, 2))
Assertions.assertThat(eliminations).contains(Move(cell_0, 3))
}
} | 1 | null | 1 | 1 | 097317f176b73f6ef2349dead413669ca4935ccf | 923 | Sudoku | MIT License |
app/src/main/java/br/com/renancsdev/dtiblog/ui/excluir/ExcluirFragment.kt | RenanCostaSilva | 805,452,810 | false | {"Gradle Kotlin DSL": 3, "Java Properties": 5, "Shell": 1, "Text": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "Ignore List": 2, "Kotlin": 36, "XML": 39, "INI": 3, "Java": 2, "PureBasic": 2} | package br.com.renancsdev.dtiblog.ui.excluir
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import br.com.renancsdev.dtiblog.adapter.excluir.RecyclerViewDeletarListaPost
import br.com.renancsdev.dtiblog.adapter.listar.RecyclerViewListarPosts
import br.com.renancsdev.dtiblog.api.builder.ApiClient
import br.com.renancsdev.dtiblog.api.model.Postagem
import br.com.renancsdev.dtiblog.databinding.FragmentExcluirBinding
import br.com.renancsdev.dtiblog.extension.esconder
import br.com.renancsdev.dtiblog.extension.mostrar
import br.com.renancsdev.dtiblog.extension.toast
import br.com.renancsdev.dtiblog.model.Posts
import br.com.renancsdev.dtiblog.repository.Resultado
import br.com.renancsdev.dtiblog.ui.criar.CriarViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ExcluirFragment : Fragment() {
private var _binding: FragmentExcluirBinding? = null
private val binding get() = _binding!!
private val viewModel by viewModel<ExcluirViewModel>()
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View {
//val notificationsViewModel = ViewModelProvider(this).get(ExcluirViewModel::class.java)
_binding = FragmentExcluirBinding.inflate(inflater, container, false)
val root: View = binding.root
listarPostagensLiveData()
//excluirPostagem()
esconderComponentes()
return root
}
override fun onResume() {
super.onResume()
//listarPostagens()
listarPostagensLiveData()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun esconderComponentes(){
binding.tvListaDeletarNadaEncontrado.esconder()
}
/* ViewModel */
private fun listarPostagensLiveData(){
viewModel.buscaListaUsuarios().observe( binding.root.context as AppCompatActivity) {
it?.let { resultado ->
when (resultado) {
is Resultado.Sucesso -> {
resultado.dado?.let { postagens ->
configurarAdapter(postagens , binding)
true
} ?: false
}
is Resultado.Erro -> {
mostarMensagemDeErro404()
false
}
}
} ?: false
}
}
/* Fim ViewModel */
private fun mostarMensagemDeErro404(){
binding.rvListarDeletarPostagem.esconder()
binding.tvListaDeletarNadaEncontrado.mostrar()
binding.tvListaDeletarNadaEncontrado.text = "Nenhuma postagem encontrada !"
}
/*private fun excluirPostagem(){
CoroutineScope(Dispatchers.IO).launch {
chamadaApiExcluir()
}
}*/
/*private fun chamadaApiExcluir(){
ApiClient.apiService.getAllPost().apply {
enqueue(object : Callback<ArrayList<Postagem>> {
override fun onResponse(call: Call<ArrayList<Postagem>>, response: Response<ArrayList<Postagem>>) {
if(response.code() == 200){
configurarAdapter(response.body()!! , binding)
}
else if(response.code() == 404){
mostarErroPostagemNaoEncontrada()
}
}
override fun onFailure(call: Call<ArrayList<Postagem>>, t: Throwable) {
mostarErroRequisicaoPostagem()
binding.root.context.toast("Failed to get response")
}
})
}
}*/
private fun configurarAdapter(listaPost: ArrayList<Postagem> , excluirBinding: FragmentExcluirBinding){
binding.rvListarDeletarPostagem.apply {
layoutManager = LinearLayoutManager(binding.root.context)
adapter = RecyclerViewDeletarListaPost(listaPost , excluirBinding)
}
}
private fun mostarErroPostagemNaoEncontrada(){
binding.rvListarDeletarPostagem.esconder()
binding.tvListaDeletarNadaEncontrado.mostrar()
binding.tvListaDeletarNadaEncontrado.text = "Nenhuma postagem encontrada !"
}
private fun mostarErroRequisicaoPostagem(){
binding.rvListarDeletarPostagem.esconder()
binding.tvListaDeletarNadaEncontrado.mostrar()
binding.tvListaDeletarNadaEncontrado.text = "Nenhuma postagem encontrada !"
}
} | 0 | Java | 0 | 0 | c7d4d383be74b652bfda2242f06e8c2e7a33cec7 | 5,044 | DTIBlog | Apache License 2.0 |
library_network/src/main/java/com/yyt/librarynetwork/converter/MyGsonRequestBodyConverter.kt | c786909486 | 514,179,909 | false | {"Gradle": 9, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "INI": 5, "Proguard": 6, "Kotlin": 80, "XML": 48, "Java": 56} | package com.yyt.librarynetwork.converter
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer
import retrofit2.Converter
import java.io.IOException
import java.io.OutputStreamWriter
import java.io.Writer
import java.nio.charset.Charset
/**
*@packageName com.yyt.librarynetwork.converter
*@author kzcai
*@date 2020/6/14
*/
class MyGsonRequestBodyConverter<T:Any>(
gson: Gson,
adapter: TypeAdapter<out Any>
) :
Converter<T?, RequestBody?> {
private val gson: Gson
private val adapter: TypeAdapter<T>
@Throws(IOException::class)
override fun convert(value: T?): RequestBody? {
val buffer = Buffer()
val writer: Writer = OutputStreamWriter(
buffer.outputStream(),
UTF_8
)
val jsonWriter = gson.newJsonWriter(writer)
adapter.write(jsonWriter, value)
jsonWriter.close()
return buffer.readByteString()
.toRequestBody(MEDIA_TYPE)
}
companion object {
private val MEDIA_TYPE: MediaType = "application/json; charset=UTF-8".toMediaType()
private val UTF_8 = Charset.forName("UTF-8")
}
init {
this.gson = gson
this.adapter = adapter as TypeAdapter<T>
}
}
| 0 | Java | 0 | 0 | de2681d4b6a0ed9459cea57b78ea7efa5a49f702 | 1,404 | BaseMvvmModel | Apache License 2.0 |
common/src/main/java/com/star/wars/common/base/BaseView.kt | aldefy | 377,213,065 | false | {"Gradle": 11, "Java Properties": 2, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 2, "INI": 6, "Proguard": 7, "XML": 91, "Kotlin": 158, "Java": 2, "JSON": 9} | package com.star.wars.common.base
import android.content.Context
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.*
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
abstract class BaseView<V : ViewModel, S : ViewState>(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), StarWarsLifecycleDelegate, LifecycleOwner {
abstract val clazz: Class<V>
val _state = PublishSubject.create<S>()
val state = _state.hide()
val compositeBag = CompositeDisposable()
abstract val registry: LifecycleRegistry
override fun getLifecycle(): Lifecycle {
return registry
}
override fun onDestroy() {
_state.onComplete()
compositeBag.clear()
}
override fun onAppBackgrounded() {
}
override fun onAppForegrounded() {
}
override fun onStart() {
}
override fun onStop() {
}
override fun onCreate() {
}
override fun onResume() {
}
override fun onPause() {
}
}
| 1 | null | 1 | 1 | 581db6c4af7547f3adb960980bf9fa8d973b6962 | 1,157 | StarWarsApp | Apache License 2.0 |
critter/core/src/main/kotlin/dev/morphia/critter/parser/java/CritterParser.kt | thachlp | 790,257,498 | true | {"Markdown": 10, "Shell": 2, "Batchfile": 2, "Kotlin": 43, "Java": 994, "Java Properties": 4, "INI": 8, "Gradle Kotlin DSL": 2} | package dev.morphia.critter.parser.java
import dev.morphia.config.MorphiaConfig
import dev.morphia.critter.conventions.CritterDefaultsConvention
import dev.morphia.critter.parser.noArgCtor
import dev.morphia.mapping.Mapper
import io.github.dmlloyd.classfile.ClassBuilder
import io.github.dmlloyd.classfile.ClassFile
import io.github.dmlloyd.classfile.attribute.InnerClassInfo
import io.github.dmlloyd.classfile.attribute.InnerClassesAttribute
import io.github.dmlloyd.classfile.extras.reflect.AccessFlag.SYNTHETIC
import io.github.dmlloyd.classfile.extras.reflect.ClassFileFormatVersion.RELEASE_17
import io.quarkus.gizmo.ClassCreator
import java.io.File
import java.io.FileOutputStream
import java.lang.constant.ClassDesc
import java.util.Optional
object CritterParser {
var outputGenerated: File? = null
val critterClassLoader = CritterClassLoader(Thread.currentThread().contextClassLoader)
fun gizmo(input: File): Class<*> {
val model = ClassFile.of().parse(input.readBytes())
val modelName = model.thisClass().name().stringValue()
val name = "${modelName}_InternalCritter"
val innerClassDesc = ClassDesc.of(name.replace('/', '.'))
val outerClassDesc = ClassDesc.of(modelName.replace('/', '.'))
val conventions = listOf(CritterDefaultsConvention() /*,
if (mapper.getConfig().propertyDiscovery() == FIELDS) FieldDiscovery() else MethodDiscovery(),
ConfigureProperties()*/)
val creator =
ClassCreator.builder()
.classOutput(critterClassLoader)
.className(name)
.superClass(Annotation::class.javaObjectType)
val b =
ClassFile.of().build(innerClassDesc) { builder: ClassBuilder ->
builder.withVersion(RELEASE_17.major(), 0)
builder.with(
InnerClassesAttribute.of(
InnerClassInfo.of(
innerClassDesc,
Optional.of(outerClassDesc),
Optional.of(innerClassDesc.displayName()),
SYNTHETIC
)
)
)
builder.noArgCtor()
conventions.forEach { convention ->
convention.apply(Mapper(MorphiaConfig.load()), builder, model)
}
model.fields().forEach {}
}
println("**************** b = ${b.size}")
outputGenerated?.let {
val file =
File(outputGenerated, "${name.substringAfterLast("/").replace("$", "\\\$")}.class")
println("**************** file = ${file.absoluteFile}")
file.parentFile.mkdirs()
FileOutputStream(file).use { it.write(b) }
}
critterClassLoader.register(name.replace('/', '.'), b)
return critterClassLoader.loadClass(name.replace('/', '.'))
}
fun parser(input: File): Class<*> {
val model = ClassFile.of().parse(input.readBytes())
val modelName = model.thisClass().name().stringValue()
val name = "${modelName}_InternalCritter"
val innerClassDesc = ClassDesc.of(name.replace('/', '.'))
val outerClassDesc = ClassDesc.of(modelName.replace('/', '.'))
val conventions = listOf(CritterDefaultsConvention() /*,
if (mapper.getConfig().propertyDiscovery() == FIELDS) FieldDiscovery() else MethodDiscovery(),
ConfigureProperties()*/)
val b =
ClassFile.of().build(innerClassDesc) { builder: ClassBuilder ->
builder.withVersion(RELEASE_17.major(), 0)
builder.with(
InnerClassesAttribute.of(
InnerClassInfo.of(
innerClassDesc,
Optional.of(outerClassDesc),
Optional.of(innerClassDesc.displayName()),
SYNTHETIC
)
)
)
builder.noArgCtor()
conventions.forEach { convention ->
convention.apply(Mapper(MorphiaConfig.load()), builder, model)
}
model.fields().forEach {}
}
println("**************** b = ${b.size}")
outputGenerated?.let {
val file =
File(outputGenerated, "${name.substringAfterLast("/").replace("$", "\\\$")}.class")
println("**************** file = ${file.absoluteFile}")
file.parentFile.mkdirs()
FileOutputStream(file).use { it.write(b) }
}
critterClassLoader.register(name.replace('/', '.'), b)
return critterClassLoader.loadClass(name.replace('/', '.'))
}
}
| 0 | Java | 0 | 0 | d220079dea743be8053d18f0f99325a455ccb6b6 | 4,848 | morphia | Apache License 2.0 |
product-import/src/main/kotlin/com/luanvv/microservices/bookstore/product_import/processors/BookManipulationProcessor.kt | luanvuhlu | 374,749,577 | false | {"Java": 37673, "Python": 14826, "Kotlin": 8026, "Batchfile": 1633, "Shell": 1432, "Dockerfile": 188} | package com.luanvv.microservices.bookstore.product_import.processors
import com.fasterxml.jackson.annotation.JsonProperty
import com.luanvv.microservices.bookstore.product_import.entities.Book
import com.luanvv.microservices.bookstore.product_import.services.BookService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.function.Consumer
@Configuration
class BookManipulationProcessor {
@Bean
fun processBookManipulation(
bookService: BookService
): Consumer<BookEvent> = Consumer<BookEvent> { book ->
bookService.save(book.toEntity())
}
}
data class BookEvent(
var id: Int = 0,
var title: String = "",
var author: String = "",
var genre: String = "",
var height: Int = 0,
var publisher: String = "",
var isbn_10: String = "",
var status: String = "",
) {
fun toEntity(): Book = Book(
title = title,
author = author,
genre = genre,
height = height,
publisher = publisher,
isbn10 = isbn_10,
status = status,
)
} | 1 | null | 1 | 1 | aaba1645f79dca718bde1ea8e77deb2101051423 | 1,121 | bookstore-microservices | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/koawalib/opmodes/OpModes.kt | Chonks1000000 | 562,622,515 | true | {"Java Properties": 1, "Gradle": 6, "Shell": 1, "Markdown": 9, "Batchfile": 1, "Text": 4, "Ignore List": 2, "XML": 19, "INI": 1, "Java": 87, "Kotlin": 55} | package org.firstinspires.ftc.teamcode.koawalib.opmodes
import com.asiankoala.koawalib.util.Alliance
import com.qualcomm.robotcore.eventloop.opmode.Autonomous
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
@TeleOp(name = "\uD83E\uDD76")
class KBlueOp : KTeleOp(Alliance.BLUE)
@TeleOp(name = "\uD83E\uDD75")
class KRedOp : KTeleOp(Alliance.RED)
@Autonomous(name = "\uD83E\uDD76 CLOSE")
class BlueCloseAuto : KAuto(Alliance.BLUE, true)
@Autonomous(name = "\uD83E\uDD76 FAR")
class BlueFarAuto : KAuto(Alliance.BLUE, false)
@Autonomous(name = "\uD83E\uDD75 CLOSE")
class RedCloseAuto : KAuto(Alliance.RED, true)
@Autonomous(name = "\uD83E\uDD75 FAR")
class RedFarAuto : KAuto(Alliance.RED, false) | 0 | Java | 0 | 0 | 80321ac8bbbf7176346d543c504f2158dd3a040a | 707 | Testing | BSD 3-Clause Clear License |
plugins/kotlin/idea/tests/testData/editor/quickDoc/InlineValueClass.kt | JetBrains | 2,489,216 | false | {"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | @JvmInline value class Class<caret>ModifierEValue(val p: Int)
//INFO: <div class='definition'><pre><span style="color:#808000;">@</span><span style="color:#808000;"><a href="psi_element://kotlin.jvm.JvmInline">JvmInline</a></span>
//INFO: <span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">final</span> <span style="color:#000080;font-weight:bold;">value</span> <span style="color:#000080;font-weight:bold;">class</span> <span style="color:#000000;">ClassModifierEValue</span></pre></div><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> InlineValueClass.kt<br/></div>
| 1 | null | 1 | 1 | 0d546ea6a419c7cb168bc3633937a826d4a91b7c | 663 | intellij-community | Apache License 2.0 |
src/main/test/java/GeneratorMaterialJSON.kt | MSh4de | 377,134,599 | false | {"Java": 188452, "Kotlin": 133231, "Dockerfile": 140} | import com.fasterxml.jackson.databind.ObjectMapper
import eu.mshade.enderframe.item.Material
import java.io.File
fun main() {
val file = File("materials.json")
val objectMapper = ObjectMapper()
val jsonNode = objectMapper.createObjectNode()
var id = 0
Material.getRegisteredNamespacedKeys().forEach{
jsonNode.put(it.key.lowercase(), id++)
}
objectMapper.writerWithDefaultPrettyPrinter().writeValue(file, jsonNode)
} | 1 | null | 1 | 1 | dd53d29546e6c42f620e11493523799182357435 | 457 | EnderChest | MIT License |
lib/common/src/main/java/com/tongsr/common/svga/bitmap/SVGABitmapFileDecoder.kt | ujffdi | 628,844,063 | false | {"Java": 1874289, "Kotlin": 463042, "Groovy": 31947} | package com.tongsr.common.svga.bitmap
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.tongsr.common.svga.bitmap.SVGABitmapDecoder
/**
* 通过文件解码 Bitmap
*
* Create by im_dsd 2020/7/7 17:50
*/
internal object SVGABitmapFileDecoder : SVGABitmapDecoder<String>() {
override fun onDecode(data: String, ops: BitmapFactory.Options): Bitmap? {
return BitmapFactory.decodeFile(data, ops)
}
} | 1 | null | 1 | 1 | d5004ca96f384cb26dbc610617107c3f12f05211 | 435 | Eyepetizer | Apache License 2.0 |
test-index/src/AllFuckingTests.kt | adolfoeliazat | 93,302,907 | false | {"Java": 30937521, "PHP": 7642921, "Kotlin": 2980528, "JavaScript": 2555709, "TypeScript": 222563, "HTML": 46734, "Batchfile": 23511, "Lex": 15020, "OCaml": 6730, "C#": 4124, "Protocol Buffer": 2621, "AutoHotkey": 2556, "Shell": 843, "Vim Script": 591, "Python": 62} | package vgrechka.testindex
import org.junit.runner.RunWith
import org.junit.runners.Suite
import vgrechka.*
import vgrechka.botinok.*
import vgrechka.spewgentests.*
import java.io.File
@RunWith(Suite::class) @Suite.SuiteClasses(
SpewGenTestSuite::class,
SharedJVMTestSuite::class,
BotinokTests::class
)
class AllFuckingTests
| 1 | null | 1 | 1 | 6d40f5900d94037139ed97cdc926db90749d5768 | 341 | fucking-everything | Apache License 2.0 |
baseclasses_ads/src/main/java/com/appspiriment/baseclasses/ads/AdUtils.kt | appspiriment | 187,779,013 | false | {"Markdown": 3, "Gradle": 7, "Java Properties": 2, "Shell": 1, "Ignore List": 6, "Batchfile": 1, "INI": 5, "Proguard": 5, "XML": 21, "Kotlin": 22, "Java": 2} | package com.appspiriment.baseclasses.ads
import android.content.Context
import android.content.SharedPreferences
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.preference.PreferenceManager
import com.google.android.gms.ads.*
/*****************************
* method to get shared Prefs
*****************************/
object AdUtils {
private var mInterstitialAd: InterstitialAd? = null
val KEY_LAST_AD_SHOWN_AT = "~lastInter~"
fun getSharedPrefs(context: Context) =
PreferenceManager.getDefaultSharedPreferences(context)
/*****************************
* method to get shared Prefs
*****************************/
fun saveCurrentInterstitialTime(context: Context) {
getSharedPrefs(context).edit()
.putLong(KEY_LAST_AD_SHOWN_AT, System.currentTimeMillis()).apply()
}
/*****************************
* method to get shared Prefs
*****************************/
fun getTimeElapsedFromLastInterstitial(
context: Context,
adTimeInterval: Int
): Boolean {
val previousTimestamp = getSharedPrefs(context).getLong(
KEY_LAST_AD_SHOWN_AT,
System.currentTimeMillis() - (adTimeInterval + 1000)
)
return (System.currentTimeMillis() - previousTimestamp) > adTimeInterval
}
/*****************************
* method to get shared Prefs
*****************************/
fun isTurnForInterstitial(context: Context, adInterval: Int, adTimeInterval: Int): Boolean {
if (adInterval < 1) return false
val KEY_INTER_AD_NUM = "~intrAd~"
val ads = getSharedPrefs(context).getInt(KEY_INTER_AD_NUM, 0)
val isTurn = ads >= adInterval
getSharedPrefs(context).edit().putInt(KEY_INTER_AD_NUM, if (isTurn) 0 else (ads + 1))
.apply()
return isTurn && getTimeElapsedFromLastInterstitial(context, adTimeInterval)
}
/***************************************
* On Backpress
***************************************/
fun getBannerAdSize(context: Context, windowManager: WindowManager): AdSize? {
val display = windowManager.defaultDisplay
val outMetrics = DisplayMetrics()
display.getMetrics(outMetrics)
val widthPixels = outMetrics.widthPixels.toFloat()
val density = outMetrics.density
val adWidth = (widthPixels / density).toInt()
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
context, adWidth
)
}
/*****************************
* method to get shared Prefs
*****************************/
fun getBannerAdView(
context: Context,
bannerAdId: String,
windowManager: WindowManager? = null,
onFailAction: (AdView) -> Unit = {}
): AdView {
return AdView(context).apply {
adUnitId = bannerAdId
adSize = windowManager?.let { getBannerAdSize(context, it) } ?: AdSize.BANNER
adListener = object : AdListener() {
override fun onAdFailedToLoad(p0: Int) {
val adview = when (adSize) {
AdSize.SMART_BANNER ->
AdView(context).apply {
adSize = AdSize.BANNER
}
AdSize.BANNER -> null
else -> AdView(context).apply {
adSize = AdSize.SMART_BANNER
}
}
adview?.run {
loadAd(AdRequest.Builder().build())
onFailAction(this)
}
}
}
loadAd(AdRequest.Builder().build())
}
}
/*****************************
* method to get shared Prefs
*****************************/
fun loadInterstitialAd(
context: Context,
adUnitId: String
) {
if (mInterstitialAd == null) {
mInterstitialAd = InterstitialAd(context).apply {
this.adUnitId = adUnitId
adListener = object : AdListener() {
override fun onAdClosed() {
loadAd(AdRequest.Builder().build())
}
}
}
}
mInterstitialAd?.run {
if (!isLoaded && !isLoading)
loadAd(AdRequest.Builder().build())
}
}
/*****************************
* method to get shared Prefs
*****************************/
fun showInterstitialAd(
context: Context,
adUnitId: String,
adTimeInterval: Int,
adInterval: Int
) {
loadInterstitialAd(context, adUnitId)
mInterstitialAd?.run {
if (isTurnForInterstitial(context, adInterval, adTimeInterval)) {
if (isLoaded) {
show()
saveCurrentInterstitialTime(context)
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 7c590ebd65b823b6e1261f08b6a9f0d3288de4d1 | 5,076 | AndroidUtils | Apache License 2.0 |
app/src/main/java/ca/pkay/rcloneexplorer/util/WifiConnectivitiyUtil.kt | djpohly | 518,070,698 | true | {"Java Properties": 2, "YAML": 3, "Gradle": 5, "Shell": 1, "Roff Manpage": 1, "Markdown": 7, "Batchfile": 1, "Text": 4, "Ignore List": 4, "Proguard": 2, "XML": 270, "Java": 143, "Kotlin": 7} | package ca.pkay.rcloneexplorer.util
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
class WifiConnectivitiyUtil {
companion object {
/**
* Check if wifi is connected. Also respects if wifi is metered.
*/
fun checkWifiOnAndConnected(mContext: Context): Boolean {
val wifiMgr = mContext.getSystemService(Context.WIFI_SERVICE) as WifiManager? ?: return false
return if (wifiMgr.isWifiEnabled) {
// Wi-Fi adapter is ON
// WifiManager requires location access. This is not available, so we query the metered instead.
val cm = mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
(!cm.isActiveNetworkMetered)
} else {
FLog.e("SyncService.TAG", "Wifi not turned on.")
false // Wi-Fi adapter is OFF
}
}
}
} | 0 | null | 0 | 0 | 2f700ed60af92150581237042d3d7679f0698cde | 980 | extRact | MIT License |
clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/models/CustomLabel3Filter.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | /**
* Pinterest REST API
* Pinterest's REST API
*
* The version of the OpenAPI document: 5.12.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
import org.openapitools.server.models.CatalogsProductGroupMultipleStringCriteria
/**
*
* @param CUSTOM_LABEL_3
*/
data class CustomLabel3Filter(
val CUSTOM_LABEL_3: CatalogsProductGroupMultipleStringCriteria
)
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 541 | pinterest-sdk | MIT License |
app/src/main/java/com/ayaanle/h_suuq/utils/Notifications.kt | ayaanlehashi11 | 525,490,944 | false | {"Java": 16247, "Kotlin": 6918} | package com.ayaanle.h_suuq.utils
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.core.content.ContextCompat.getSystemService
class Notifications {
lateinit var notificationManager : NotificationManager
lateinit var notificationChannel : NotificationChannel
lateinit var builder : Notification.Builder
private val channelId = "i.apps.notifications"
private val description = "Test notification"
public constructor()
{
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
button.setOnClickListener{
val intent = Intent(this , afterNotification::class.java)
val pendingintent = PendingIntent.getActivities(this , 0, arrayOf(intent), PendingIntent.FLAG_UPDATE_CURRENT)
val contentView = RemoteViews(packageName , R.layout.activity_after_notification)
notificationChannel = NotificationChannel(channelId , description , NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.GREEN
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
builder = Notification.Builder(this , channelId)
.setContent(contentView)
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setLargeIcon(BitmapFactory.decodeResource(this.resources , R.drawable.ic_launcher_background))
.setContentIntent(pendingintent)
notificationManager.notify(1234 , builder.build())
}
}
} | 1 | null | 1 | 1 | 0c74b9f6d16b0dad623f3dc704f584c48ba7f012 | 1,842 | Z-Suuq | MIT License |
idea/src/org/jetbrains/jet/plugin/debugger/render/KotlinObjectRenderer.kt | virtuoushub | 27,313,453 | true | {"Markdown": 21, "XML": 504, "Ant Build System": 33, "Ignore List": 8, "Kotlin": 14560, "Java": 4036, "Protocol Buffer": 2, "Roff": 18, "Roff Manpage": 4, "Text": 3020, "JAR Manifest": 1, "INI": 6, "HTML": 102, "Groovy": 7, "Gradle": 62, "Maven POM": 39, "Java Properties": 10, "CSS": 10, "JavaScript": 53, "JFlex": 3, "Shell": 8, "Batchfile": 8} | /*
* Copyright 2010-2014 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.jet.plugin.debugger.render
import com.intellij.debugger.ui.tree.render.ClassRenderer
import com.sun.jdi.Type
import com.intellij.debugger.engine.evaluation.EvaluationContext
import com.sun.jdi.ObjectReference
import com.sun.jdi.Field
import com.sun.jdi.ClassType
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl
import com.intellij.debugger.ui.tree.NodeDescriptorFactory
import com.intellij.debugger.ui.tree.FieldDescriptor
import com.intellij.debugger.ui.impl.watch.FieldDescriptorImpl
import com.intellij.openapi.project.Project
import com.intellij.debugger.impl.DebuggerContextImpl
import org.jetbrains.jet.lang.resolve.java.JvmAbi
import com.intellij.debugger.ui.tree.ValueDescriptor
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.debugger.settings.NodeRendererSettings
import com.intellij.psi.PsiClass
import com.intellij.psi.JavaPsiFacade
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.impl.DebuggerContextUtil
import com.intellij.psi.search.GlobalSearchScope
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.ClassNotPreparedException
import com.intellij.psi.PsiElement
import org.jetbrains.jet.lang.psi.JetClass
import org.jetbrains.jet.lang.resolve.java.JvmClassName
import com.sun.jdi.ReferenceType
import org.jetbrains.jet.codegen.AsmUtil
import org.jetbrains.jet.lang.psi.JetClassOrObject
import org.jetbrains.jet.lang.psi.psiUtil.getStrictParentOfType
public open class KotlinObjectRenderer : ClassRenderer() {
override fun isApplicable(jdiType: Type?): Boolean {
if (!super.isApplicable(jdiType)) return false
var isCustomRendererApplicable = false
NodeRendererSettings.getInstance().getCustomRenderers().iterateRenderers {
isCustomRendererApplicable = it.isApplicable(jdiType)
!isCustomRendererApplicable
}
if (isCustomRendererApplicable) return false
return jdiType.isKotlinClass()
}
override fun createFieldDescriptor(
parentDescriptor: ValueDescriptorImpl?,
nodeDescriptorFactory: NodeDescriptorFactory?,
objRef: ObjectReference?,
field: Field?,
evaluationContext: EvaluationContext?
): FieldDescriptor {
if (field?.declaringType().isKotlinClass()) {
return KotlinObjectFieldDescriptor(evaluationContext?.getProject(), objRef, field)
}
return super.createFieldDescriptor(parentDescriptor, nodeDescriptorFactory, objRef, field, evaluationContext)
}
override fun calcLabel(
descriptor: ValueDescriptor?,
evaluationContext: EvaluationContext?,
labelListener: DescriptorLabelListener?
): String? {
val toStringRenderer = NodeRendererSettings.getInstance().getToStringRenderer()
if (toStringRenderer.isApplicable(descriptor?.getValue()?.type())) {
return toStringRenderer.calcLabel(descriptor, evaluationContext, labelListener)
}
return super.calcLabel(descriptor, evaluationContext, labelListener)
}
}
public class KotlinObjectFieldDescriptor(
project: Project?,
objRef: ObjectReference?,
field: Field?
) : FieldDescriptorImpl(project, objRef, field) {
override fun getSourcePosition(project: Project?, context: DebuggerContextImpl?, nearest: Boolean): SourcePosition? {
if (context == null || context.getFrameProxy() == null) return null
val fieldName = getField().name()
if (fieldName == AsmUtil.CAPTURED_THIS_FIELD || fieldName == AsmUtil.CAPTURED_RECEIVER_FIELD) {
return null
}
val type = getField().declaringType()
val myClass = findClassByType(type, context)?.getNavigationElement()
if (myClass !is JetClassOrObject) {
return null
}
val field = myClass.getDeclarations().firstOrNull { fieldName == it.getName() }
if (field == null) return null
if (nearest) {
return DebuggerContextUtil.findNearest(context, field, myClass.getContainingFile())
}
return SourcePosition.createFromOffset(field.getContainingFile(), field.getTextOffset())
}
private fun findClassByType(type: ReferenceType, context: DebuggerContextImpl): PsiElement? {
val session = context.getDebuggerSession()
val scope = if (session != null) session.getSearchScope() else GlobalSearchScope.allScope(myProject)
val className = JvmClassName.byInternalName(type.name()).getFqNameForClassNameWithoutDollars().asString()
val myClass = JavaPsiFacade.getInstance(myProject).findClass(className, scope)
if (myClass != null) return myClass
val position = getLastSourcePosition(type, context)
if (position != null) {
val element = position.getElementAt()
if (element != null) {
return element.getStrictParentOfType<JetClassOrObject>()
}
}
return null
}
private fun getLastSourcePosition(type: ReferenceType, context: DebuggerContextImpl): SourcePosition? {
val debugProcess = context.getDebugProcess()
if (debugProcess != null) {
try {
val locations = type.allLineLocations()
if (!locations.isEmpty()) {
val lastLocation = locations.get(locations.size() - 1)
return debugProcess.getPositionManager().getSourcePosition(lastLocation)
}
}
catch (ignored: AbsentInformationException) {
}
catch (ignored: ClassNotPreparedException) {
}
}
return null
}
}
private fun Type?.isKotlinClass(): Boolean {
return this is ClassType && this.allInterfaces().any { it.name() == JvmAbi.K_OBJECT.asString() }
}
| 0 | Java | 0 | 0 | 99ec8952e192d3f95bb1974e71bbfca1d2e92c78 | 6,496 | kotlin | Apache License 2.0 |
app/src/main/java/com/jagoancoding/tobuy/util/PurchaseUtil.kt | f4ww4z | 138,449,858 | false | {"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 2, "Kotlin": 14, "XML": 22, "Java": 1, "SVG": 2} | package com.jagoancoding.tobuy.util
import com.jagoancoding.tobuy.db.Purchase
object PurchaseUtil {
fun List<Purchase>.sumUpPurchases() = filter { it.included }.map { it.totalPrice }.sum()
} | 3 | Kotlin | 0 | 1 | 84e174ff8f4575e7e28cecfd5b19066416e24027 | 197 | tobuy | MIT License |
ui/revenuecatui/src/main/kotlin/com/revenuecat/purchases/ui/revenuecatui/fonts/CustomFontProvider.kt | RevenueCat | 127,346,826 | false | {"Gemfile.lock": 1, "Gradle": 21, "Markdown": 16, "Java Properties": 10, "Ruby": 3, "Shell": 5, "Text": 1, "Ignore List": 17, "Batchfile": 4, "YAML": 6, "XML": 223, "INI": 5, "Proguard": 14, "Kotlin": 685, "JSON": 5, "TOML": 4, "Java": 44, "Gradle Kotlin DSL": 2, "HTML": 1} | package com.revenuecat.purchases.ui.revenuecatui.fonts
import androidx.compose.ui.text.font.FontFamily
/**
* Class that allows to provide a font family for all text styles.
* @param fontFamily the [FontFamily] to be used for all text styles.
*/
class CustomFontProvider(private val fontFamily: FontFamily) : FontProvider {
override fun getFont(type: TypographyType) = fontFamily
}
| 1 | null | 1 | 1 | 5deff6cbebe4712ef3633053ceb6d217179f4fa6 | 390 | purchases-android | MIT License |
studypatch/src/main/java/com/xdf/studypatch/callback/PatchManipulateImp.kt | wangqiang58 | 665,320,909 | false | {"Java": 152782, "Groovy": 117978, "Kotlin": 64993} | package com.xdf.studypatch.callback
import android.content.Context
import com.meituan.robust.Patch
import com.meituan.robust.PatchManipulate
import com.xdf.studypatch.manager.RobustManager
import com.xdf.studypatch.util.FileUtils
import com.xdf.studypatch.util.PatchCoderUtil
import java.io.File
/**
*
@author: wangqiang
@date: 2023/8/5
@desc:
* Robust 暴露给业务方的几个接口
* 1、获取补丁列表(定制逻辑:单次只下发一个补丁,采用覆盖安装的逻辑,一个补丁包实现目标版本的所有bug fix)
* 2、判断补丁是否存在
* 3、校验补丁状态
*
* 原注释⬇
*
* We recommend you rewrite your own PatchManipulate class ,adding your special patch Strategy,in the demo we just load the patch directly
* Pay attention to the difference of patch's LocalPath and patch's TempPath
* We recommend LocalPath store the origin patch.jar which may be encrypted,while TempPath is the true runnable jar
* <br>
* 我们推荐继承PatchManipulate实现你们App独特的A补丁加载策略,其中setLocalPath设置补丁的原始路径,这个路径存储的补丁是加密过得,setTempPath存储解密之后的补丁,是可以执行的jar文件
* setTempPath设置的补丁加载完毕即刻删除,如果不需要加密和解密补丁,两者没有啥区别
*
*/
class PatchManipulateImp(private val patchBean: com.xdf.studypatch.model.PatchBean) : PatchManipulate() {
override fun fetchPatchList(context: Context?): MutableList<Patch> {
val list = mutableListOf<com.meituan.robust.Patch>()
list.add(createPatch())
return list
}
override fun verifyPatch(context: Context?, patch: Patch?): Boolean {
patch ?: return false
val patchFile = File(patch.localPath)
//patch文件是否存在
if (!patchFile.exists()) {
RobustManager.callbackImpl?.exceptionNotify(Throwable("no patch execute in path ${patch.localPath} patchFile is not exit"), "PatchManipulateImp verifyPatch 46")
RobustManager.callbackImpl?.ensurePatchExist(patch.name, patch.localPath, false)
return false
}
val localSign= PatchCoderUtil.encodeMd5ToBase64(patchFile)
//校验文件MD5
if (patchBean.signed== localSign) {
//放到app的私有目录
patch.tempPath =
context?.cacheDir.toString() + File.separator + "robust" + File.separator + "patch"
//in the sample we just copy the file
val isSuccess= FileUtils.copyFile(patch.localPath, patch.tempPath)
if (!isSuccess){
RobustManager.callbackImpl?.exceptionNotify(
Throwable("copy source patch to local patch error, no patch execute in path " + patch.tempPath),
"PatchManipulateImp verifyPatch 62"
)
RobustManager.callbackImpl?.verifyPatch(patch.name, patch.localPath, false,localSign,patchBean.signed)
return false
}
RobustManager.callbackImpl?.verifyPatch(patch.name, patch.localPath, true,localSign,patchBean.signed)
return true
} else {
RobustManager.callbackImpl?.exceptionNotify(
Throwable("sign is not math localSign=${localSign} remoteSign=${patchBean.signed}"),
"PatchManipulateImp verifyPatch 72"
)
RobustManager.callbackImpl?.verifyPatch(patch.name, patch.localPath, false,localSign,patchBean.signed)
return false
}
}
/**
* 原注释:you may download your patches here, you can check whether patch is in the phone
*
* 包装path一定存在我们可以在最开始的时候做下载,不在此处
* @param patch
* @return 是否存在
*/
override fun ensurePatchExist(patch: com.meituan.robust.Patch?): Boolean {
return true
}
/**
* 将业务方传递的数据包装成Robust接收的补丁包Patch
*/
private fun createPatch(): Patch {
val patch = com.meituan.robust.Patch()
// 补丁名称
patch.name = patchBean.patchVersion
// 补丁文件的物理存储路径
patch.localPath = RobustManager.getPatchLocalPath(patchBean.patchVersion)
// setPatchesInfoImplClassFullName 设置项各个App可以独立定制,
// 需要确保的是setPatchesInfoImplClassFullName设置的包名是和xml配置项patchPackname保持一致,
// 而且类名必须是:PatchesInfoImpl
// **请注意这里的设置**
patch.patchesInfoImplClassFullName =
RobustManager.getPatchDelegate().getPatchesInfoImplClassFullName()
return patch
}
} | 1 | null | 1 | 1 | dff654b11f57588e7a1687e7335725fc334b0416 | 4,136 | patcher_mobile | Apache License 2.0 |
executioncontext/installationcontext/src/test/java/org/jetbrains/bsp/bazel/installationcontext/InstallationContextConstructorTest.kt | steveniemitz | 485,935,051 | true | {"Shell": 3, "Markdown": 10, "Java": 138, "Kotlin": 46, "C++": 1, "Scala": 10} | package org.jetbrains.bsp.bazel.installationcontext
import com.google.common.net.HostAndPort
import io.kotest.matchers.shouldBe
import io.vavr.control.Option
import io.vavr.control.Try
import org.jetbrains.bsp.bazel.installationcontext.entities.InstallationContextDebuggerAddressEntity
import org.jetbrains.bsp.bazel.installationcontext.entities.InstallationContextJavaPathEntity
import org.jetbrains.bsp.bazel.projectview.model.ProjectView
import org.jetbrains.bsp.bazel.projectview.model.sections.ProjectViewDebuggerAddressSection
import org.jetbrains.bsp.bazel.projectview.model.sections.ProjectViewJavaPathSection
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.nio.file.Paths
class InstallationContextConstructorTest {
private lateinit var installationContextConstructor: InstallationContextConstructor
@BeforeEach
fun beforeEach() {
// given
this.installationContextConstructor =
InstallationContextConstructor(Option.of(Paths.get("/path/to/projectview.bazelproject")))
}
@Nested
@DisplayName("fun construct(projectViewTry: Try<ProjectView> ): Try<WorkspaceContext> tests")
inner class ConstructProjectViewTryTest {
@Test
fun `should return failure if project view is failure`() {
// given
val projectViewTry = Try.failure<ProjectView>(Exception("exception message"))
// when
val installationContextTry = installationContextConstructor.construct(projectViewTry)
// then
installationContextTry.isFailure shouldBe true
installationContextTry.cause::class shouldBe Exception::class
installationContextTry.cause.message shouldBe "exception message"
}
}
@Nested
@DisplayName("fun construct(projectView: ProjectView): Try<WorkspaceContext> tests")
inner class ConstructProjectViewTest {
@Test
fun `should return success if project view is valid`() {
// given
val projectView =
ProjectView.Builder(
javaPath = ProjectViewJavaPathSection(Paths.get("/path/to/java")),
debuggerAddress = ProjectViewDebuggerAddressSection(HostAndPort.fromString("host:8000"))
)
.build()
// when
val installationContextTry = installationContextConstructor.construct(projectView)
// then
installationContextTry.isSuccess shouldBe true
val installationContext = installationContextTry.get()
val expectedJavaPath = InstallationContextJavaPathEntity(Paths.get("/path/to/java"))
installationContext.javaPath shouldBe expectedJavaPath
val expectedDebuggerAddress = InstallationContextDebuggerAddressEntity(HostAndPort.fromString("host:8000"))
installationContext.debuggerAddress.get() shouldBe expectedDebuggerAddress
}
}
}
| 0 | null | 0 | 0 | 36b98966249b6616f86c035b7f48c8ca816d3188 | 3,067 | bazel-bsp | Apache License 2.0 |
hobbits/src/test/kotlin/org/apache/tuweni/hobbits/HobbitsTransportTest.kt | Consensys | 693,991,624 | true | {"SVG": 2, "Java Properties": 2, "Markdown": 64, "Gradle": 64, "Shell": 3, "EditorConfig": 1, "YAML": 13760, "Git Attributes": 1, "Batchfile": 1, "Text": 33, "Ignore List": 2, "Git Config": 1, "Kotlin": 393, "TOML": 8, "Java": 443, "XML": 18, "JSON": 17343, "JavaScript": 4, "CSS": 1, "HTML": 8, "SQL": 5, "INI": 3, "ANTLR": 2, "Public Key": 1, "Dockerfile": 2} | // Copyright The Tuweni Authors
// SPDX-License-Identifier: Apache-2.0
package org.apache.tuweni.hobbits
import io.vertx.core.Vertx
import kotlinx.coroutines.runBlocking
import org.apache.tuweni.bytes.Bytes
import org.apache.tuweni.concurrent.AsyncResult
import org.apache.tuweni.concurrent.coroutines.await
import org.apache.tuweni.junit.VertxExtension
import org.apache.tuweni.junit.VertxInstance
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import java.util.concurrent.atomic.AtomicInteger
@ExtendWith(VertxExtension::class)
class HobbitsTransportTest {
@Test
fun testLifecycle(@VertxInstance vertx: Vertx) = runBlocking {
val server = HobbitsTransport(vertx)
server.start()
server.start()
server.stop()
}
@Test
fun sendMessageBeforeStart(@VertxInstance vertx: Vertx) = runBlocking {
val server = HobbitsTransport(vertx)
val exception: IllegalStateException = assertThrows {
runBlocking {
server.sendMessage(
Message(protocol = Protocol.RPC, headers = Bytes.EMPTY, body = Bytes.EMPTY),
Transport.TCP,
"localhost",
9000,
)
}
}
assertEquals("Server not started", exception.message)
}
@Test
fun registerEndpointAfterStart(@VertxInstance vertx: Vertx) = runBlocking {
val server = HobbitsTransport(vertx)
server.start()
val exception: IllegalStateException = assertThrows {
server.createHTTPEndpoint(networkInterface = "127.0.0.1", handler = {})
}
assertEquals("Server already started", exception.message)
}
@Test
fun sendMessage(@VertxInstance vertx: Vertx) = runBlocking {
val completion = AsyncResult.incomplete<Bytes>()
val listening = vertx.createNetServer()
listening.connectHandler {
it.handler {
completion.complete(Bytes.wrapBuffer(it))
}
}.listen(0, "localhost") {
runBlocking {
val server = HobbitsTransport(vertx)
server.start()
val msg = Message(protocol = Protocol.RPC, headers = Bytes.EMPTY, body = Bytes.EMPTY)
server.sendMessage(msg, Transport.TCP, "localhost", listening.actualPort())
val result = completion.await()
assertEquals(msg.toBytes(), result)
}
}
}
@Test
fun registerEndpoints(@VertxInstance vertx: Vertx) = runBlocking {
val server = HobbitsTransport(vertx)
val httpPort = AtomicInteger()
val tcpPort = AtomicInteger()
val wsPort = AtomicInteger()
server.createHTTPEndpoint("myhttp", "localhost", port = 0, handler = {}, portUpdateListener = httpPort::set)
server.createUDPEndpoint("myudp", "localhost", handler = {}, port = 32009)
server.createTCPEndpoint("mytcp", "localhost", port = 0, handler = {}, portUpdateListener = tcpPort::set)
server.createWSEndpoint("myws", "localhost", port = 0, handler = {}, portUpdateListener = wsPort::set)
server.start()
assertNotEquals(0, tcpPort.get())
assertNotEquals(0, httpPort.get())
assertNotEquals(0, wsPort.get())
server.stop()
}
}
| 1 | Java | 2 | 0 | d780a654afc90f5fd3c16540d592259487e0a190 | 3,209 | tuweni | Apache License 2.0 |
translatorCompiler/src/main/kotlin/net/earthcomputer/multiconnect/compiler/node/CastOp.kt | LostLuma | 504,882,998 | true | {"Java Properties": 2, "Batchfile": 2, "Gradle": 5, "Shell": 3, "Text": 26, "Markdown": 3, "Ignore List": 1, "JSON": 61, "Java": 808, "Gradle Kotlin DSL": 6, "Kotlin": 67, "XML": 3, "YAML": 3, "Groovy": 1, "Graphviz (DOT)": 3, "SVG": 3, "INI": 1, "Python": 3, "JavaScript": 1} | package net.earthcomputer.multiconnect.compiler.node
import net.earthcomputer.multiconnect.compiler.Emitter
import net.earthcomputer.multiconnect.compiler.McType
class CastOp(fromType: McType, private val toType: McType) : McNodeOp {
override val paramTypes = listOf(fromType)
override val returnType = toType
override val isExpensive = true
override val precedence = Precedence.CAST
override fun emit(node: McNode, emitter: Emitter) {
emitter.append("(")
toType.emit(emitter)
emitter.append(") ")
node.inputs[0].emit(emitter, precedence)
}
}
| 0 | null | 0 | 0 | ee5cbf489d9d03e9cd12b43e26d75e367666d973 | 601 | multiconnect | MIT License |
app/src/main/java/com/earth/angel/gift/adapter/RecommendGroupsAdapter.kt | engineerrep | 643,933,914 | false | {"Java": 2291635, "Kotlin": 1651449} | package com.earth.angel.gift.adapter
import android.content.Context
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.helper.widget.Layer
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.earth.angel.R
import com.earth.angel.base.clickWithTrigger
import com.earth.libbase.entity.GiftHouseEntity
class RecommendGroupsAdapter(
mContext: Context?,
userProfileBeans: MutableList<GiftHouseEntity>?,
var upDade: (houseNumber: Long) -> Unit = {}
) : BaseQuickAdapter<GiftHouseEntity, BaseViewHolder>(
R.layout.item_group_recommend,
userProfileBeans
) {
private val mLayoutInflater: LayoutInflater = LayoutInflater.from(mContext)
override fun convert(holder: BaseViewHolder, item: GiftHouseEntity) {
var ivHeader: ImageView? = holder.getView(R.id.iv)
var ivJoined: Layer? = holder.getView(R.id.lyJoined)
var tvDistance: TextView? = holder.getView(R.id.tv)
var tvmessage: TextView? = holder.getView(R.id.tvmessage)
item?.houseLogo?.let {
Glide.with(context)
.load(it)
// .apply(RequestOptions.bitmapTransform(BlurTransformation(5, 8)))
.into(ivHeader!!)
}
item?.houseName?.let {
tvDistance?.text=it
}
ivJoined?.clickWithTrigger{
upDade(item.houseNumber)
}
item?.members?.let {
tvmessage?.text= "[ $it people]"
}
}
} | 1 | null | 1 | 1 | 415e0417870b6ff2c84a9798d1f3f3a4e6921354 | 1,630 | EarthAngel | MIT License |
XTool/src/main/java/com/danny/xtool/net/NetType.kt | dannycx | 643,140,932 | false | {"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 58, "INI": 8, "Proguard": 9, "Kotlin": 149, "XML": 117, "Java": 130, "JSON": 2} | /*
* Copyright (c) 2023-2023 x
*/
package com.danny.xtool.net
/**
* 网络类型
*
* @author x
* @since 2023-06-02
*/
enum class NetType(private var des: String) {
NETWORK_WIFI("WiFi"), NETWORK_5G("5G"), NETWORK_4G("4G"), NETWORK_3G("3G")
, NETWORK_2G("2G"), NETWORK_UNKNOWN("Unknown"), NETWORK_NO("No network");
override fun toString(): String {
return des
}
}
| 0 | Java | 0 | 0 | 31020de9d942f1d0013c1bf7a8115decd229e296 | 392 | XLib | Apache License 2.0 |
src/main/kotlin/com/koresframework/kores/type/KoresTypeResolver.kt | JonathanxD | 58,418,392 | false | {"Gradle": 5, "YAML": 3, "TOML": 2, "Markdown": 7208, "INI": 2, "Shell": 1, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Java": 69, "Kotlin": 218, "SVG": 2, "HTML": 12, "JavaScript": 7, "CSS": 9, "JSON": 1} | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2022 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <<EMAIL>>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.koresframework.kores.type
import com.github.jonathanxd.iutils.`object`.Either
import com.github.jonathanxd.iutils.`object`.specialized.EitherObjBoolean
import com.koresframework.kores.base.*
import com.koresframework.kores.common.KoresNothing
import com.koresframework.kores.type.KoresTypeResolver.DefaultResolver.resolve
import com.koresframework.kores.util.KoresTypeResolverFunc
import com.koresframework.kores.util.conversion.getTypeDeclaration
import com.koresframework.kores.util.conversion.toRepresentation
import com.koresframework.kores.util.conversion.typeDeclaration
import java.lang.reflect.Type
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeKind
import javax.lang.model.util.Elements
/**
* Type resolver. Type resolvers should never throws an error when it is unable to resolve
* result of an operation. The operation should return an [Either] instance which contains
* either the exception describing fail of resolution or the result of resolution.
*/
interface KoresTypeResolver<out T> {
/**
* Resolves [type] to [T]
*/
fun resolve(type: Type): Either<Exception, out T>
/**
* Resolves super class of [type].
*
* Should return null [Type] if there is no super class.
*/
fun getSuperclass(type: Type): Either<Exception, Type?>
/**
* Resolves super interfaces of [type].
*/
fun getInterfaces(type: Type): Either<Exception, List<Type>>
/**
* Checks if [type] is assignable from [from] using default resolvers.
*
* @return True if [type] is assignable from [from].
*/
fun isAssignableFrom(type: Type, from: Type): EitherObjBoolean<Exception> =
this.isAssignableFrom(type, from, Type::defaultResolver)
/**
* Checks if [type] is assignable [from] using resolvers provided by [resolverProvider]
*
* @return True if [type] is assignable from [from].
*/
fun isAssignableFrom(
type: Type,
from: Type,
resolverProvider: (Type) -> KoresTypeResolver<*>
): EitherObjBoolean<Exception>
/**
* Resolves or create [TypeDeclaration] from [type] structure and elements.
*/
fun resolveTypeDeclaration(type: Type): Either<Exception, TypeDeclaration>
/**
* Resolves or create a list of all [FieldDeclaration] present in [type].
*
* The default implementation delegates the call to [resolveTypeDeclaration]
* and extract property value.
*/
fun resolveFields(type: Type): Either<Exception, List<FieldDeclaration>> =
this.resolveTypeDeclaration(type).mapRight { it.fields }
/**
* Resolves or create a list of all [ConstructorDeclaration] present in [type].
*
* The default implementation delegates the call to [resolveTypeDeclaration]
* and extract property value.
*/
fun resolveConstructors(type: Type): Either<Exception, List<ConstructorDeclaration>> =
this.resolveTypeDeclaration(type).flatMapRight {
(it as? ConstructorsHolder)?.let {
Either.right<Exception, List<ConstructorDeclaration>>(it.constructors)
} ?: Either.left<Exception, List<ConstructorDeclaration>>(
IllegalArgumentException(
"Type $type is not a ConstructorHolder"
)
)
}
/**
* Resolves or create a list of all [MethodDeclaration] present in [type].
*
* The default implementation delegates the call to [resolveTypeDeclaration]
* and extract property value.
*/
fun resolveMethods(type: Type): Either<Exception, List<MethodDeclaration>> =
this.resolveTypeDeclaration(type).mapRight { it.methods }
/**
* Common implementation of resolver.
*/
abstract class CommonResolver<out T> : KoresTypeResolver<T> {
override fun getSuperclass(type: Type): Either<Exception, Type?> {
val concreteType = type.concreteType
if (concreteType is LoadedKoresType<*>)
return Either.right(concreteType.loadedType.superclass?.koresType)
if (concreteType is TypeElementKoresType)
return Either.right(concreteType.typeElement.superclass?.let {
if (it.kind != TypeKind.NONE) it.getKoresType(concreteType.elements)
else null
})
if (concreteType is SuperClassHolder)
return Either.right(concreteType.superClass.koresType)
if (concreteType is InheritanceProvider)
return Either.right(concreteType.superclass)
return Either.left(IllegalArgumentException("Can't resolve super class of $type: Unknown type."))
}
override fun getInterfaces(type: Type): Either<Exception, List<Type>> {
val concreteType = type.concreteType
if (concreteType is LoadedKoresType<*>)
return Either.right(concreteType.loadedType.interfaces?.map { it.koresType }.orEmpty())
if (concreteType is TypeElementKoresType)
return Either.right(concreteType.typeElement.interfaces?.filter { it.kind != TypeKind.NONE }
?.map { it.getKoresType(concreteType.elements) }.orEmpty())
if (concreteType is ImplementationHolder)
return Either.right(concreteType.implementations.map { it.koresType }.toList())
if (concreteType is InheritanceProvider)
return Either.right(concreteType.superinterfaces.toList())
return Either.left(IllegalArgumentException("Can't resolve super interfaces of $type: Unknown type."))
}
override fun isAssignableFrom(
type: Type,
from: Type,
resolverProvider: (Type) -> KoresTypeResolver<*>
): EitherObjBoolean<Exception> {
// Should I do something like TypeInfo#isAssignableFrom for GenericTypes?
val concreteKoresType = type.concreteType
val concreteFrom = from.concreteType
if (concreteKoresType.`is`(concreteFrom))
return EitherObjBoolean.right(true)
if (concreteKoresType is LoadedKoresType<*> && concreteFrom is LoadedKoresType<*>)
return EitherObjBoolean.right(
concreteKoresType.loadedType.isAssignableFrom(
concreteFrom.loadedType
)
)
val superClass =
concreteFrom.let { resolverProvider(it).getSuperclass(it) }.rightOrNull()
?.concreteType
if (superClass != null) {
if (superClass.`is`(concreteKoresType)
||
superClass.let {
resolverProvider(it).isAssignableFrom(
concreteKoresType,
it,
resolverProvider
)
.let {
if (it.isLeft) return EitherObjBoolean.left(it.left) else it.right
}
}
) {
return EitherObjBoolean.right(true)
}
}
val superinterfaces =
concreteFrom.let { resolverProvider(it).getInterfaces(it) }.rightOrNull().orEmpty()
if (superinterfaces.isNotEmpty()) {
if (superinterfaces.any { it.`is`(concreteKoresType) }
||
superinterfaces.any {
resolverProvider(it).isAssignableFrom(
concreteKoresType,
it,
resolverProvider
)
.let {
if (it.isLeft) return EitherObjBoolean.left(it.left) else it.right
}
}) {
return EitherObjBoolean.right(true)
}
}
return EitherObjBoolean.right(false)
}
override fun resolveTypeDeclaration(type: Type): Either<Exception, TypeDeclaration> {
val concreteType = type.concreteType
if (concreteType is LoadedKoresType<*>)
return Either.right(concreteType.loadedType.typeDeclaration)
if (concreteType is TypeElementKoresType)
return Either.right(concreteType.typeElement.getTypeDeclaration(concreteType.elements))
if (concreteType is TypeDeclaration)
return Either.right(concreteType.toRepresentation())
return Either.left(IllegalArgumentException("Cannot create TypeDeclaration representation from $type"))
}
}
/**
* Resolver that resolves [KoresType] to Java [Class]. This may resolve to [KoresNothing.type]
* is class loader fails to find class.
*/
class Java(val classLoader: ClassLoader) : CommonResolver<Class<*>>() {
override fun resolve(type: Type): Either<Exception, out Class<*>> {
val concreteType = type.concreteType
if (concreteType is LoadedKoresType<*>)
return Either.right(concreteType.loadedType)
return when (type.javaSpecName) {
"V" -> Either.right(Void.TYPE)
"Z" -> Either.right(Boolean::class.javaPrimitiveType!!)
"C" -> Either.right(Char::class.javaPrimitiveType!!)
"B" -> Either.right(Byte::class.javaPrimitiveType!!)
"S" -> Either.right(Short::class.javaPrimitiveType!!)
"I" -> Either.right(Int::class.javaPrimitiveType!!)
"F" -> Either.right(Float::class.javaPrimitiveType!!)
"D" -> Either.right(Double::class.javaPrimitiveType!!)
"J" -> Either.right(Long::class.javaPrimitiveType!!)
else -> try {
Either.right<Exception, Class<*>>(classLoader.loadClass(type.binaryName))
} catch (t: ClassNotFoundException) {
Either.left<Exception, Class<*>>(t)
}
}
}
}
/**
* Resolver that resolves [KoresType] to Javax Model [TypeElement], or to `null`
* if type cannot be found.
*/
class Model(val elements: Elements) : CommonResolver<TypeElement?>() {
override fun resolve(type: Type): Either<Exception, out TypeElement> =
((type.concreteType as? TypeElementKoresType)?.typeElement
?: elements.getTypeElement(type.canonicalName))?.let {
Either.right<Exception, TypeElement>(it)
}
?: Either.left<Exception, TypeElement>(IllegalArgumentException("Cannot resolve '$type' in Model Elements."))
}
/**
* Default resolver that returns the same instance for [resolve] method.
*/
object DefaultResolver : CommonResolver<Type>() {
override fun resolve(type: Type): Either<Exception, Type> = Either.right(type)
}
/**
* Kores Resolver.
*/
class Kores(val resolverFunc: KoresTypeResolverFunc? = null) :
CommonResolver<TypeDeclaration?>() {
override fun resolve(type: Type): Either<Exception, out TypeDeclaration> =
((type.concreteType as? TypeDeclaration)
?: (resolverFunc?.apply(type.canonicalName) as? TypeDeclaration))?.let {
Either.right<Exception, TypeDeclaration>(it)
}
?: Either.left<Exception, TypeDeclaration>(IllegalArgumentException("Cannot resolve '$type' Kores Declaration."))
}
/**
* This is a resolver which support multiple resolvers. This resolver
* always returns first **valid resolved value** for each operation.
*
* A valid resolved value depends on operations, see documentation.
*/
class Multi<T> : KoresTypeResolver<T?> {
private val resolvers = mutableListOf<KoresTypeResolver<T?>>()
/**
* Adds a resolver
*/
fun addResolver(resolver: KoresTypeResolver<T?>) {
this.resolvers += resolver
}
/**
* Removes a resolver
*/
fun removeResolver(resolver: KoresTypeResolver<T?>) {
this.resolvers -= resolver
}
/**
* Adds a resolver
*/
operator fun plusAssign(resolver: KoresTypeResolver<T?>) {
this.resolvers += resolver
}
/**
* Removes a resolver
*/
operator fun minusAssign(resolver: KoresTypeResolver<T?>) {
this.resolvers -= resolver
}
/**
* First non-null and [non-nothing][KoresNothing] value is returned, or `null` if no
* valid value was found.
*/
@Suppress("UNCHECKED_CAST")
override fun resolve(type: Type): Either<Exception, out T?> =
resolvers.map { it.resolve(type) }.firstOrNull { it.isRight }
?: Either.left<Exception, T?>(
IllegalArgumentException(
"None of provided resolvers was" +
" able to resolve $type. Provided resolvers: '${resolvers.joinToString()}'"
)
)
/**
* First non-null and [non-nothing][KoresNothing] value is returned, or `null` if no
* valid value was found.
*/
override fun getSuperclass(type: Type): Either<Exception, Type?> =
resolvers.map { it.getSuperclass(type) }
.firstOrNull { it.isRight }
?: Either.left<Exception, Type?>(
IllegalArgumentException(
"None of provided resolvers was" +
" able to resolve $type super class. Provided resolvers: '${resolvers.joinToString()}'"
)
)
/**
* First bigger list is returned.
*/
override fun getInterfaces(type: Type): Either<Exception, List<Type>> =
resolvers.map { it.getInterfaces(type) }
.filter { it.isRight }
.sortedByDescending { it.right.size }
.firstOrNull()
?: Either.left<Exception, List<Type>>(
IllegalArgumentException(
"None of provided resolvers was" +
" able to resolve $type super interfaces. Provided resolvers: '${resolvers.joinToString()}'"
)
)
/**
* Returns true if any resolver returns true for this operation.
*/
override fun isAssignableFrom(
type: Type,
from: Type,
resolverProvider: (Type) -> KoresTypeResolver<*>
): EitherObjBoolean<Exception> =
resolvers.map { it.isAssignableFrom(type, from, resolverProvider) }
.firstOrNull { it.isRight && it.right }
?: EitherObjBoolean.left<Exception>(
IllegalArgumentException(
"None of provided resolvers was" +
" able to resolve whether $type is assignable from $from. Provided resolvers: '${resolvers.joinToString()}'"
)
)
override fun resolveTypeDeclaration(type: Type): Either<Exception, TypeDeclaration> =
resolvers.map { it.resolveTypeDeclaration(type) }
.firstOrNull { it.isRight }
?: Either.left<Exception, TypeDeclaration>(
IllegalArgumentException(
"None of provided resolvers was" +
" able to resolve TypeDeclaration representation of $type."
)
)
}
class Two<out A, out B, out X>(
val first: KoresTypeResolver<A>,
val second: KoresTypeResolver<B>
) : KoresTypeResolver<X> where A : X, B : X {
@Suppress("UNCHECKED_CAST")
override fun resolve(type: Type): Either<Exception, out X> =
(this.first.resolve(type) as Either<Exception, X>).flatMapLeft {
this.second.resolve(type) as Either<Exception, X>
}
override fun getSuperclass(type: Type): Either<Exception, Type?> =
this.first.getSuperclass(type).flatMapLeft {
this.second.getSuperclass(type)
}
override fun getInterfaces(type: Type): Either<Exception, List<Type>> =
this.first.getInterfaces(type).flatMapLeft {
this.second.getInterfaces(type)
}
override fun isAssignableFrom(
type: Type,
from: Type,
resolverProvider: (Type) -> KoresTypeResolver<*>
): EitherObjBoolean<Exception> =
this.first.isAssignableFrom(type, from, resolverProvider).flatMapLeft {
this.second.isAssignableFrom(type, from, resolverProvider)
}
override fun resolveTypeDeclaration(type: Type): Either<Exception, TypeDeclaration> =
this.first.resolveTypeDeclaration(type).flatMapLeft {
this.second.resolveTypeDeclaration(type)
}
}
} | 6 | Kotlin | 0 | 4 | 236f7db6eeef7e6238f0ae0dab3f3b05fc531abb | 18,996 | CodeAPI | MIT License |
sceneview/src/main/kotlin/io/github/sceneview/SceneView.kt | vrolnes | 479,101,426 | true | {"Java Properties": 4, "YAML": 7, "Markdown": 3, "Gradle": 10, "Shell": 2, "Batchfile": 3, "Text": 2, "Ignore List": 9, "XML": 45, "Kotlin": 68, "Proguard": 4, "Java": 175, "Unity3D Asset": 13, "Groovy": 1} | package io.github.sceneview
import android.annotation.SuppressLint
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Color.BLACK
import android.graphics.PixelFormat
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.*
import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.findFragment
import androidx.lifecycle.*
import com.google.android.filament.Colors
import com.google.android.filament.Entity
import com.google.android.filament.LightManager
import com.google.android.filament.View
import com.google.android.filament.utils.HDRLoader
import com.google.android.filament.utils.KTXLoader
import com.google.ar.sceneform.*
import com.google.ar.sceneform.collision.CollisionSystem
import com.google.ar.sceneform.rendering.EngineInstance
import com.google.ar.sceneform.rendering.ModelRenderable
import com.google.ar.sceneform.rendering.Renderer
import com.google.ar.sceneform.ux.FootprintSelectionVisualizer
import com.google.ar.sceneform.ux.TransformationSystem
import com.gorisse.thomas.lifecycle.lifecycleScope
import io.github.sceneview.collision.pickHitTest
import io.github.sceneview.environment.Environment
import io.github.sceneview.environment.createEnvironment
import io.github.sceneview.environment.loadEnvironment
import io.github.sceneview.light.*
import io.github.sceneview.model.GLBLoader
import io.github.sceneview.node.Node
import io.github.sceneview.node.NodeParent
import io.github.sceneview.utils.*
const val defaultIbl = "sceneview/environments/indoor_studio/indoor_studio_ibl.ktx"
const val defaultSkybox = "sceneview/environments/indoor_studio/indoor_studio_skybox.ktx"
const val defaultNodeSelector = "sceneview/models/node_selector.glb"
/**
* ### A SurfaceView that manages rendering and interactions with the 3D scene.
*
* Maintains the scene graph, a hierarchical organization of a scene's content.
* A scene can have zero or more child nodes and each node can have zero or more child nodes.
* The Scene also provides hit testing, a way to detect which node is touched by a MotionEvent or
* Ray.
*/
open class SceneView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : SurfaceView(context, attrs, defStyleAttr, defStyleRes),
SceneLifecycleOwner,
DefaultLifecycleObserver,
Choreographer.FrameCallback,
NodeParent {
companion object {
val defaultMainLight: Light by lazy {
LightManager.Builder(LightManager.Type.DIRECTIONAL).apply {
val (r, g, b) = Colors.cct(6_500.0f)
color(r, g, b)
intensity(100_000.0f)
direction(0.28f, -0.6f, -0.76f)
castShadows(true)
}.build()
}
}
override val activity
get() = try {
findFragment<Fragment>().requireActivity()
} catch (e: Exception) {
context.getActivity()!!
}
open val sceneLifecycle: SceneLifecycle by lazy { SceneLifecycle(context, this) }
override fun getLifecycle() = sceneLifecycle
private val parentLifecycleObserver = LifecycleEventObserver { _, event ->
lifecycle.currentState = event.targetState
}
override var _children = listOf<Node>()
// TODO : Move to the Render when Kotlined it
var currentFrameTime: FrameTime = FrameTime(0)
/**
* ### The camera that is used to render the scene
*
* The camera is a type of node.
*/
//TODO : Move it to Lifecycle and NodeParent when Kotlined
open val camera: Camera by lazy { Camera(this) }
val collisionSystem = CollisionSystem()
/**
* ### The renderer used for this view
*/
override val renderer by lazy { Renderer(this, camera) }
// TODO: Remove this nightmare class quick and replace it with the new Filament Pick system
private val nodesTouchEventDispatcher by lazy { TouchEventSystem() }
private val surfaceGestureDetector by lazy { SurfaceGestureDetector() }
/**
* ### The transformation system
*
* Used by [TransformableNode] for detecting gestures and coordinating which node is selected.
* Can be overridden to create a custom transformation system.
*/
val nodeGestureRecognizer by lazy {
TransformationSystem(resources.displayMetrics, FootprintSelectionVisualizer())
}
var nodeSelectorModel: ModelRenderable?
get() = (nodeGestureRecognizer.selectionVisualizer as? FootprintSelectionVisualizer)?.footprintRenderable
set(value) {
(nodeGestureRecognizer.selectionVisualizer as? FootprintSelectionVisualizer)?.footprintRenderable =
value
}
/**
* ### Defines the lighting environment and the skybox of the scene
*
* Environments are usually captured as high-resolution HDR equirectangular images and processed
* by the cmgen tool to generate the data needed by IndirectLight.
*
* You can also process an hdr at runtime but this is more consuming.
*
* - Currently IndirectLight is intended to be used for "distant probes", that is, to represent
* global illumination from a distant (i.e. at infinity) environment, such as the sky or distant
* mountains.
* Only a single IndirectLight can be used in a Scene. This limitation will be lifted in the future.
*
* - When added to a Scene, the Skybox fills all untouched pixels.
*
* @see [KTXLoader.loadEnvironment]
* @see [HDRLoader.loadEnvironment]
*/
var environment: Environment? = null
set(value) {
renderer.setEnvironment(value)
field = value
updateBackground()
}
/**
* ### The main directional light of the scene
*
* Usually the Sun.
*/
@Entity
var mainLight: Light? = null
set(value) {
field = value
renderer.setMainLight(value)
}
var onOpenGLNotSupported: ((exception: Exception) -> Unit)? = null
/**
* ### Invoked when an frame is processed
*
* Registers a callback to be invoked when a valid Frame is processing.
*
* The callback to be invoked once per frame **immediately before the scene
* is updated**.
*
* The callback will only be invoked if the Frame is considered as valid.
*/
var onFrame: ((frameTime: FrameTime) -> Unit)? = null
/**
* ### Register a callback to be invoked when the scene is touched.
*
* You should not use this callback in you have anything on your scene.
* Node selection, gestures recognizer and surface gesture recognizer won't be updated if you
* return true.
*
* **Have a look at [onTouch] or other gestures listeners**
*
* Called even if the touch is not over a node, in which case [PickHitResult.getNode]
* will be null.
*
* - `pickHitResult` - represents the node that was touched if any
* - `motionEvent` - the motion event
* - `return` true if the listener has consumed the event
*/
var onTouchEvent: ((pickHitResult: PickHitResult, motionEvent: MotionEvent) -> Boolean)? = null
/**
* ### Register a callback to be invoked on the surface singleTap
*
* Called even if the touch is not over a selectable node, in which case `node` will be null.
*
* - `selectedNode` - The node that was hit by the hit test. Null when there is no hit
* - `motionEvent` - The original [MotionEvent]
*/
var onTouch: ((selectedNode: Node?, motionEvent: MotionEvent) -> Boolean)? = null
init {
try {
// TODO : Remove it here when moved Filament to lifecycle aware
EngineInstance.getEngine()
mainLight = defaultMainLight
environment = KTXLoader.createEnvironment(context.fileBufferLocal(defaultIbl))
lifecycleScope.launchWhenCreated {
nodeSelectorModel = GLBLoader.loadModel(context, defaultNodeSelector)?.apply {
collisionShape = null
BuildConfig.VERSION_NAME
}
}
updateBackground()
} catch (exception: Exception) {
// TODO: This is actually a none sens to call listener on init. Move the try/catch when
// Filament is kotlined
onOpenGLNotSupported(exception)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
lifecycle.addObserver(this)
findViewTreeLifecycleOwner()?.let { parentLifecycleOwner ->
parentLifecycleOwner.lifecycle.addObserver(parentLifecycleObserver)
lifecycle.currentState = parentLifecycleOwner.lifecycle.currentState
}
}
fun Context.getActivity(): ComponentActivity? = this as? ComponentActivity
?: (this as? ContextWrapper)?.baseContext?.getActivity()
override fun onDetachedFromWindow() {
findViewTreeLifecycleOwner()?.lifecycle?.removeObserver(parentLifecycleObserver)
lifecycle.currentState = Lifecycle.State.DESTROYED
super.onDetachedFromWindow()
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
renderer.onResume()
// Start the drawing when the renderer is resumed. Remove and re-add the callback
// to avoid getting called twice.
Choreographer.getInstance().removeFrameCallback(this)
Choreographer.getInstance().postFrameCallback(this)
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
Choreographer.getInstance().removeFrameCallback(this)
renderer.onPause()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
renderer.destroyAllResources()
camera.destroy()
environment?.destroy()
environment = null
mainLight?.destroy()
mainLight = null
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
//TODO move to lifecycle when Rendere is kotlined
val width = right - left
val height = bottom - top
renderer.setDesiredSize(width, height)
lifecycle.dispatchEvent<SceneLifecycleObserver> {
onSurfaceChanged(width, height)
}
}
fun onOpenGLNotSupported(exception: Exception) {
onOpenGLNotSupported?.invoke(exception)
}
var lastNanoseconds = 0L
/**
* Callback that occurs for each display frame. Updates the scene and reposts itself to be called
* by the choreographer on the next frame.
*/
override fun doFrame(frameTimeNanos: Long) {
// Always post the callback for the next frame.
Choreographer.getInstance().postFrameCallback(this)
currentFrameTime = FrameTime(frameTimeNanos, currentFrameTime.nanoseconds)
doFrame(currentFrameTime)
}
open fun doFrame(frameTime: FrameTime) {
if (renderer.render(frameTime.nanoseconds)) {
lifecycle.dispatchEvent<SceneLifecycleObserver> {
onFrame(frameTime)
}
onFrame?.invoke(frameTime)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(motionEvent: MotionEvent): Boolean {
// This makes sure that the view's onTouchListener is called.
if (!super.onTouchEvent(motionEvent)) {
onTouchEvent(pickHitTest(motionEvent, focusableOnly = true), motionEvent)
return true
}
return true
}
override fun setBackgroundDrawable(background: Drawable?) {
super.setBackgroundDrawable(background)
if (holder != null) {
updateBackground()
}
}
private fun updateBackground() {
if ((background is ColorDrawable && background.alpha == 255) || environment?.skybox != null) {
backgroundColor = colorOf(color = (background as? ColorDrawable)?.color ?: BLACK)
isTransparent = false
} else {
backgroundColor = colorOf(a = 0.0f)
isTransparent = true
}
}
var backgroundColor: Color? = null
set(value) {
if (field != value) {
field = value
renderer.setClearColor(backgroundColor)
}
}
/**
* ### Set the background to transparent.
*/
var isTransparent: Boolean = false
set(value) {
if (field != value) {
field = value
setZOrderOnTop(value)
holder.setFormat(if (value) PixelFormat.TRANSLUCENT else PixelFormat.OPAQUE)
renderer.filamentView.blendMode =
if (value) View.BlendMode.TRANSLUCENT else View.BlendMode.OPAQUE
}
}
// TODO: See if we still need it
// /**
// * Set the background to a given [Drawable], or remove the background.
// * If the background is a [ColorDrawable], then the background color of the [SceneView] is set
// * to [ColorDrawable.getColor] (the alpha of the color is ignored).
// * Otherwise, default to the behavior of [SurfaceView.setBackground].
// */
// override fun setBackground(background: Drawable?) {
// if (background is ColorDrawable) {
// backgroundColor = Color(background.color)
// renderer.setClearColor(backgroundColor)
// } else {
// super.setBackground(background)
// backgroundColor = null
// renderer.setDefaultClearColor()
// }
// }
/**
* To capture the contents of this view, designate a [Surface] onto which this SceneView
* should be mirrored. Use [android.media.MediaRecorder.getSurface], [ ][android.media.MediaCodec.createInputSurface] or [ ][android.media.MediaCodec.createPersistentInputSurface] to obtain the input surface for
* recording. This will incur a rendering performance cost and should only be set when capturing
* this view. To stop the additional rendering, call stopMirroringToSurface.
*
* @param surface the Surface onto which the rendered scene should be mirrored.
* @param left the left edge of the rectangle into which the view should be mirrored on surface.
* @param bottom the bottom edge of the rectangle into which the view should be mirrored on
* surface.
* @param width the width of the rectangle into which the SceneView should be mirrored on surface.
* @param height the height of the rectangle into which the SceneView should be mirrored on
* surface.
*/
fun startMirroringToSurface(surface: Surface, left: Int, bottom: Int, width: Int, height: Int) =
renderer.startMirroring(surface, left, bottom, width, height)
/**
* When capturing is complete, call this method to stop mirroring the SceneView to the specified
* [Surface]. If this is not called, the additional performance cost will remain.
*
*
* The application is responsible for calling [Surface.release] on the Surface when
* done.
*/
fun stopMirroringToSurface(surface: Surface) = renderer.stopMirroring(surface)
/**
* ### Invoked when the scene is touched.
*
* Called even if the touch is not over a node, in which case [PickHitResult.getNode]
* will be null.
*
* @param pickHitResult represents the node that was touched
* @param motionEvent the motion event
*/
open fun onTouchEvent(pickHitResult: PickHitResult, motionEvent: MotionEvent) {
if (onTouchEvent?.invoke(pickHitResult, motionEvent) != true) {
nodesTouchEventDispatcher.onTouchEvent(pickHitResult, motionEvent)
nodeGestureRecognizer.onTouch(pickHitResult, motionEvent)
surfaceGestureDetector.onTouchEvent(pickHitResult, motionEvent)
}
}
open fun onTouch(selectedNode: Node?, motionEvent: MotionEvent): Boolean {
return onTouch?.invoke(selectedNode, motionEvent) ?: false
}
override fun setOnClickListener(listener: OnClickListener?) {
onTouch = listener?.let {
{ _, _ ->
it.onClick(this)
true
}
}
}
inner class SurfaceGestureDetector : GestureDetector(context, OnGestureListener()) {
lateinit var pickHitResult: PickHitResult
fun onTouchEvent(pickHitResult: PickHitResult, motionEvent: MotionEvent): Boolean {
this.pickHitResult = pickHitResult
return onTouchEvent(motionEvent)
}
}
inner class OnGestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(motionEvent: MotionEvent): Boolean {
val hitTestResult = surfaceGestureDetector.pickHitResult
onTouch(hitTestResult.node, motionEvent)
return true
}
override fun onDown(e: MotionEvent): Boolean {
return true
}
}
}
/**
* A SurfaceView that integrates with ARCore and renders a scene.
*/
interface SceneLifecycleOwner : LifecycleOwner {
val activity: ComponentActivity
val renderer: Renderer
}
open class SceneLifecycle(context: Context, open val owner: SceneLifecycleOwner) :
DefaultLifecycle(context, owner) {
val activity get() = owner.activity
val renderer get() = owner.renderer
}
interface SceneLifecycleObserver : DefaultLifecycleObserver {
/**
* Records a change in surface dimensions.
*
* @param width the updated width of the surface.
* @param height the updated height of the surface.
*/
fun onSurfaceChanged(width: Int, height: Int) {
}
fun onFrame(frameTime: FrameTime) {
}
} | 0 | null | 0 | 0 | 7ad2ec401649fa45031d84a28140eb58d2dda7e6 | 17,929 | sceneview-android | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.