content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package node.express.middleware
import node.express.Response
import node.express.Request
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder
import node.express.Body
import io.netty.handler.codec.http.multipart.Attribute
import io.netty.handler.codec.http.multipart.InterfaceHttpData
import java.util.HashSet
import node.express.RouteHandler
/**
* Body parser for URL encoded data
*/
public fun urlEncodedBodyParser(): RouteHandler.()->Unit {
return {
if (req.body == null) {
try {
val decoder = HttpPostRequestDecoder(DefaultHttpDataFactory(false), req.request)
val data = decoder.getBodyHttpDatas()!!
if (data.size() > 0) {
req.attributes.put("body", UrlEncodedBody(decoder))
}
} catch (e: Throwable) {
// ignored
}
}
next()
}
}
private class UrlEncodedBody(decoder: HttpPostRequestDecoder): Body {
val decoder = decoder
private fun getAttribute(key: String): Attribute? {
return decoder.getBodyHttpData(key) as? Attribute
}
override fun get(key: String): Any? {
return getAttribute(key)?.getString()
}
override fun asInt(key: String): Int? {
return getAttribute(key)?.getString()?.toInt()
}
override fun asString(key: String): String? {
return getAttribute(key)?.getString()
}
override fun asDouble(key: String): Double? {
return getAttribute(key)?.getString()?.toDouble()
}
override fun asInt(index: Int): Int? {
throw UnsupportedOperationException()
}
override fun asString(index: Int): String? {
throw UnsupportedOperationException()
}
override fun asNative(): Any {
return decoder
}
public override fun size(): Int {
return decoder.getBodyHttpDatas()!!.size()
}
public override fun isEmpty(): Boolean {
return size() == 0
}
public override fun containsKey(key: Any?): Boolean {
return decoder.getBodyHttpDatas()!!.find { it.getName() == key } != null
}
public override fun containsValue(value: Any?): Boolean {
throw UnsupportedOperationException()
}
public override fun get(key: Any?): Any? {
return this.get(key as String)
}
public override fun keySet(): Set<String> {
return HashSet(decoder.getBodyHttpDatas()!!.map { it.getName()!! })
}
public override fun values(): Collection<Any?> {
return decoder.getBodyHttpDatas()!!.map { (it as Attribute).getValue() }
}
public override fun entrySet(): Set<Map.Entry<String, Any?>> {
return HashSet(decoder.getBodyHttpDatas()!!.map { BodyEntry(it as Attribute) })
}
private data class BodyEntry(val att: Attribute): Map.Entry<String, Any?> {
public override fun hashCode(): Int {
return att.hashCode()
}
public override fun equals(other: Any?): Boolean {
return att.equals(other)
}
public override fun getKey(): String {
return att.getName()!!
}
public override fun getValue(): Any? {
return att.getValue()
}
}
} | src/main/kotlin/node/express/middleware/UrlEncodedBodyParser.kt | 3722083455 |
package ch.difty.scipamato.core.web.sync
import ch.difty.scipamato.core.ScipamatoCoreApplication
import ch.difty.scipamato.core.ScipamatoSession
import ch.difty.scipamato.core.auth.Roles
import ch.difty.scipamato.core.sync.launcher.SyncJobLauncher
import ch.difty.scipamato.core.web.common.BasePage
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton
import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons
import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation
import org.apache.wicket.event.Broadcast
import org.apache.wicket.event.IEvent
import org.apache.wicket.model.StringResourceModel
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.apache.wicket.spring.injection.annot.SpringBean
import java.time.Duration
@Suppress("serial")
@AuthorizeInstantiation(Roles.USER, Roles.ADMIN)
class RefDataSyncPage(parameters: PageParameters) : BasePage<Void>(parameters) {
@SpringBean
private lateinit var jobLauncher: SyncJobLauncher
override fun onInitialize() {
super.onInitialize()
queue(BootstrapForm<Void>("synchForm"))
queue(newButton("synchronize"))
queue(SyncResultListPanel("syncResults"))
}
private fun newButton(id: String): BootstrapAjaxButton {
val labelModel = StringResourceModel("button.$id.label", this, null)
return object : BootstrapAjaxButton(id, labelModel, Buttons.Type.Primary) {
override fun onSubmit(target: AjaxRequestTarget) {
super.onSubmit(target)
ScipamatoCoreApplication.getApplication().launchSyncTask(SyncBatchTask(jobLauncher))
page.send(page, Broadcast.DEPTH, BatchJobLaunchedEvent(target))
info(StringResourceModel("feedback.msg.started", this, null).string)
target.add(this)
}
override fun onConfigure() {
super.onConfigure()
if (ScipamatoSession.get().syncJobResult.isRunning) {
isEnabled = false
label = StringResourceModel("button.$id-wip.label", this, null)
} else {
isEnabled = true
label = StringResourceModel("button.$id.label", this, null)
}
}
}
}
@Suppress("MagicNumber")
override fun onEvent(event: IEvent<*>) {
(event.payload as? BatchJobLaunchedEvent)?.let { jobLaunchedEvent ->
[email protected](AjaxSelfUpdatingTimerBehavior(Duration.ofSeconds(5)))
jobLaunchedEvent.target.add(this@RefDataSyncPage)
}
}
companion object {
private const val serialVersionUID = 1L
}
}
| core/core-web/src/main/java/ch/difty/scipamato/core/web/sync/RefDataSyncPage.kt | 3960459266 |
package net.twisterrob.challenges.leetcode2020april.week1.counting_elements
class Solution {
fun countElements(arr: IntArray): Int {
val elements = arr
// get interesting numbers close to each other in known position
.sorted()
// reduce duplication to allow for checking the next item
.distinct()
// [1,2,3] -> [(1,2), (2,3)]
.zipWithNext()
// check if the adjacent element are adjacent on the number line
.filter { it.first + 1 == it.second }
// only look at the element that needs counting
.map(Pair<Int, Int>::first)
// store for quick lookup
.toHashSet()
return arr.count { it in elements }
}
}
| LeetCode2020April/week1/src/main/kotlin/net/twisterrob/challenges/leetcode2020april/week1/counting_elements/Solution.kt | 3189558846 |
package com.linroid.jni
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.linroid.jni", appContext.packageName)
}
}
| Android/jni/app/src/androidTest/java/com/linroid/jni/ExampleInstrumentedTest.kt | 3848299682 |
/*
Copyright 2017 StepStone Services
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.stepstone.stepper.sample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Toast
import com.stepstone.stepper.StepperLayout
import com.stepstone.stepper.VerificationError
import com.stepstone.stepper.sample.adapter.FormFragmentStepAdapter
import butterknife.BindView
import butterknife.ButterKnife
class ProceedProgrammaticallyActivity : AppCompatActivity(), StepperLayout.StepperListener, OnProceedListener {
companion object {
private const val CURRENT_STEP_POSITION_KEY = "position"
}
@BindView(R.id.stepperLayout)
lateinit var stepperLayout: StepperLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = "Stepper sample"
setContentView(R.layout.activity_default_dots)
ButterKnife.bind(this)
val startingStepPosition = savedInstanceState?.getInt(CURRENT_STEP_POSITION_KEY) ?: 0
stepperLayout.setAdapter(FormFragmentStepAdapter(supportFragmentManager, this), startingStepPosition)
stepperLayout.setListener(this)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(CURRENT_STEP_POSITION_KEY, stepperLayout.currentStepPosition)
super.onSaveInstanceState(outState)
}
override fun onBackPressed() {
val currentStepPosition = stepperLayout.currentStepPosition
if (currentStepPosition > 0) {
stepperLayout.onBackClicked()
} else {
finish()
}
}
override fun onCompleted(completeButton: View) {
Toast.makeText(this, "onCompleted!", Toast.LENGTH_SHORT).show()
}
override fun onError(verificationError: VerificationError) {}
override fun onStepSelected(newStepPosition: Int) {}
override fun onReturn() {}
override fun onProceed() {
stepperLayout.proceed()
}
}
| sample/src/main/java/com/stepstone/stepper/sample/ProceedProgrammaticallyActivity.kt | 373792989 |
/*
Copyright 2013 Dániel Sólyom
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 ds.violin.v1.util.common
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FilterInputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import android.app.Activity
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.net.Uri
import android.provider.MediaStore
object Bitmaps {
/**
*
* @param url
* @return
* @throws IOException
* @throws OutOfMemoryError
*/
@Throws(IOException::class, OutOfMemoryError::class)
fun downloadImage(url: URL): Bitmap {
var stream: InputStream? = null
try {
stream = getFlushedHttpStream(url)
return BitmapFactory.decodeStream(stream)
} catch (e: IOException) {
throw e
} catch (e: OutOfMemoryError) {
throw e
} finally {
if (stream != null) {
stream.close()
}
}
}
/**
*
* @param url
* @return
* @throws IOException
* @throws OutOfMemoryError
*/
@Throws(IOException::class, OutOfMemoryError::class)
fun downloadImageAsByteArray(url: URL): ByteArray {
var stream: InputStream? = null
try {
stream = getFlushedHttpStream(url)
return Files.getFileAsByteArray(stream)
} catch (e: IOException) {
throw e
} catch (e: OutOfMemoryError) {
throw e
} finally {
if (stream != null) {
stream.close()
}
}
}
/**
*
* @param bytes
* @return
*/
fun createBitmap(bytes: ByteArray): Bitmap {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
/**
* create a thumbnail (png, 100 quality) from byte array
* this first creates a bitmap from the byte array, then scales that bitmap
* !please note: this does not checks if the input byteArray is 'small' enough to create the bitmap
*
* @param byteArray
* @param width
* @param height
* @throws OutOfMemoryError
* @return
*/
@Throws(OutOfMemoryError::class)
fun createThumbnail(byteArray: ByteArray, width: Int, height: Int): Bitmap {
val tmp = createBitmap(byteArray)
val result = Bitmap.createScaledBitmap(tmp, width, height, false)
tmp.recycle()
return result
}
/**
* create a thumbnail's byte array
* this first creates a bitmap from the byte array, then scales that bitmap and converts that to byte array
* !please note: this does not checks if the input byteArray is 'small' enough to create the bitmap(s)
*
* @param byteArray
* @param maxWidth
* @param maxHeight
* @throws OutOfMemoryError
* @return
*/
@Throws(OutOfMemoryError::class)
@JvmOverloads fun createThumbnailByteArray(byteArray: ByteArray, maxWidth: Int, maxHeight: Int,
format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 100): ByteArray {
var thumbnailByteArray = byteArray
val point = findNewBitmapSize(thumbnailByteArray, maxWidth, maxHeight) ?: return thumbnailByteArray
val tmp = createThumbnail(thumbnailByteArray, point.x, point.y)
thumbnailByteArray = compressBitmapToByteArray(tmp, format, quality)
tmp.recycle()
return thumbnailByteArray
}
/**
* gives back another bitmap resized so size is inside maxWidth and maxHeight
* !note: does not recycle the input bitmap and may return the original bitmap (if no scaling was necessary)
*
* @param bmp
* @param maxWidth
* @param maxHeight
* @return
*/
fun resizeBitmap(bmp: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
val point = findNewBitmapSize(bmp.width, bmp.height, maxWidth, maxHeight)
return Bitmap.createScaledBitmap(bmp, point.x, point.y, true)
}
/**
* gives back another bitmap resized so size is inside maxWidth and maxHeight
* !note: may return the original bitmap (if no scaling was necessary)
*
* @param bmp
* @param maxWidth
* @param maxHeight
* @param recycle
* @return
*/
fun resizeBitmap(bmp: Bitmap, maxWidth: Int, maxHeight: Int, recycle: Boolean): Bitmap {
val bw = bmp.width
val bh = bmp.height
val point = findNewBitmapSize(bw, bh, maxWidth, maxHeight)
if (bw == point.x && bh == point.y) {
return bmp
}
val ret = Bitmap.createScaledBitmap(bmp, point.x, point.y, true)
if (recycle) {
bmp.recycle()
}
return ret
}
/**
*
* @param byteArray
* @param maxWidth
* @param maxHeight
* @return
*/
fun findNewBitmapSize(byteArray: ByteArray, maxWidth: Int, maxHeight: Int): Point? {
//Decode image size from byte array
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, o)
return findNewBitmapSize(o.outWidth, o.outHeight, maxWidth, maxHeight)
}
/**
*
* @param oWidth
* @param oHeight
* @param maxWidth
* @param maxHeight
* @return
*/
fun findNewBitmapSize(oWidth: Int, oHeight: Int, maxWidth: Int, maxHeight: Int): Point {
// use image size ratio to find out real width and height
if (oWidth > maxWidth || oHeight > maxHeight) {
var nw = maxWidth
var nh = maxHeight
val rw = maxWidth.toDouble() / oWidth
val rh = maxHeight.toDouble() / oHeight
if (rw > rh) {
nw = (oWidth * rh).toInt()
} else {
nh = (oHeight * rw).toInt()
}
return Point(nw, nh)
} else {
return if (maxWidth > maxHeight) Point(maxHeight, maxHeight) else Point(maxWidth, maxWidth)
}
}
/**
*
* @param byteArray
* @param approxWidth
* @param approxHeight
* @return
*/
fun createThumbnailApprox(byteArray: ByteArray, approxWidth: Int, approxHeight: Int): Bitmap? {
try {
//Decode image size
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, o)
var bmp: Bitmap?
var scale = 1
if (o.outHeight > approxHeight || o.outWidth > approxWidth) {
scale = Math.max(Math.pow(2.0, Math.ceil(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(),
Math.pow(2.0, Math.ceil(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt())
}
//Decode with inSampleSize
val o2 = BitmapFactory.Options()
o2.inSampleSize = scale
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, o2)
return bmp
} catch (e: Throwable) {
e.printStackTrace()
return null
}
}
/**
* @param bmp
* @return
*/
fun compressBitmapToByteArray(bmp: Bitmap): ByteArray {
val stream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream)
return stream.toByteArray()
}
/**
*
* @param bmp
* @param format
* @param quality
* @return
*/
fun compressBitmapToByteArray(bmp: Bitmap, format: Bitmap.CompressFormat, quality: Int): ByteArray {
val stream = ByteArrayOutputStream()
bmp.compress(format, quality, stream)
return stream.toByteArray()
}
/**
*
* @param context
* @param uri
* @param approxWidth
* @param approxHeight
* @return
*/
fun getThumbnailInternal(context: Context, uri: Uri, approxWidth: Int, approxHeight: Int): Bitmap? {
try {
var `is`: InputStream = context.contentResolver.openInputStream(uri)
//Decode image size
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
BitmapFactory.decodeStream(`is`, null, o)
`is`.close()
var bmp: Bitmap?
var scale = 1
if (o.outHeight > approxHeight || o.outWidth > approxWidth) {
scale = Math.max(Math.pow(2.0, Math.ceil(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(),
Math.pow(2.0, Math.ceil(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt())
}
//Decode with inSampleSize
val o2 = BitmapFactory.Options()
o2.inSampleSize = scale
`is` = context.contentResolver.openInputStream(uri)
bmp = BitmapFactory.decodeStream(`is`, null, o2)
`is`.close()
return bmp
} catch (e: Throwable) {
e.printStackTrace()
return null
}
}
/**
*
* @param imageFileName
* @param approxWidth
* @param approxHeight
* @return
*/
fun getThumbnail(imageFileName: String, approxWidth: Int, approxHeight: Int): Bitmap? {
val f = File(imageFileName)
if (!f.exists()) {
return null
}
try {
//Decode image size
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
var fis = FileInputStream(f)
BitmapFactory.decodeStream(fis, null, o)
fis.close()
var bmp: Bitmap?
var scale = 1
if (o.outHeight > approxHeight || o.outWidth > approxWidth) {
scale = Math.max(Math.pow(2.0, Math.floor(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(),
Math.pow(2.0, Math.floor(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt())
}
//Decode with inSampleSize
val o2 = BitmapFactory.Options()
o2.inSampleSize = scale
fis = FileInputStream(f)
bmp = BitmapFactory.decodeStream(fis, null, o2)
fis.close()
return bmp
} catch (e: Throwable) {
throw e
}
}
/**
*
* @param url
* @param approxWidth
* @param approxHeight
* @return
*/
@Throws(IOException::class)
fun getResizedImageFromHttpStream(url: URL, approxWidth: Int, approxHeight: Int): Bitmap {
var stream: InputStream? = null
try {
//Decode image size
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
stream = getFlushedHttpStream(url)
BitmapFactory.decodeStream(stream, null, o)
Debug.logD("Bitmaps", "original size: " + o.outWidth + "x" + o.outHeight + " ")
var bmp: Bitmap?
var scale = 1
if (o.outHeight > approxHeight || o.outWidth > approxWidth) {
scale = Math.max(Math.pow(2.0, Math.ceil(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(),
Math.pow(2.0, Math.ceil(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt())
}
//Decode with inSampleSize
val o2 = BitmapFactory.Options()
o2.inSampleSize = scale
stream = getFlushedHttpStream(url)
bmp = BitmapFactory.decodeStream(stream, null, o2)
Debug.logD("Bitmaps", "new size: " + bmp!!.width + "x" + bmp.height + " ")
return bmp
} catch (e: IOException) {
e.printStackTrace()
throw e
} finally {
if (stream != null) {
stream.close()
}
}
}
/**
*
* @param activity
* @param uri
* @return
*/
fun getImageFileNameFromUri(activity: Activity, uri: Uri): String? {
val ret: String?
try {
val proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor = activity.contentResolver.query(uri, proj, null, null, null)
val index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
ret = cursor.getString(index)
cursor.close()
} catch (e: Exception) {
ret = null
}
return ret
}
/**
* @param url
* @return
* @throws IOException
*/
@Throws(IOException::class)
fun getFlushedHttpStream(url: URL): FlushedInputStream {
val conn = url.openConnection() as HttpURLConnection
conn.doInput = true
conn.useCaches = false
conn.connect()
val stream = conn.inputStream
try {
stream.reset()
} catch (e: Throwable) {
}
return FlushedInputStream(stream)
}
// manipulations
fun fastBlur(sentBitmap: Bitmap, radius: Int, fromX: Int, fromY: Int,
width: Int, height: Int, brightnessMod: Float, scale: Float): Bitmap? {
var usedradius = radius
// Stack Blur v1.0 from
// http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
//
// Java Author: Mario Klingemann <mario at quasimondo.com>
// http://incubator.quasimondo.com
// created Feburary 29, 2004
// Android port : Yahel Bouaziz <yahel at kayenko.com>
// http://www.kayenko.com
// ported april 5th, 2012
// This is a compromise between Gaussian Blur and Box blur
// It creates much better looking blurs than Box Blur, but is
// 7x faster than my Gaussian Blur implementation.
//
// I called it Stack Blur because this describes best how this
// filter works internally: it creates a kind of moving stack
// of colors whilst scanning through the image. Thereby it
// just has to add one new block of color to the right side
// of the stack and remove the leftmost color. The remaining
// colors on the topmost layer of the stack are either added on
// or reduced by one, depending on if they are on the right or
// on the left side of the stack.
//
// If you are using this algorithm in your code please add
// the following line:
//
// Stack Blur Algorithm by Mario Klingemann <[email protected]>
// added brightness modification by DS (january 7th, 2013)
// implemented for kotlin by DS (2016)
val bitmap: Bitmap
if (scale == 1.0f) {
bitmap = sentBitmap.copy(sentBitmap.config, true)
} else {
bitmap = Bitmap.createScaledBitmap(sentBitmap,
(sentBitmap.width * scale).toInt(), (sentBitmap.height * scale).toInt(), false)
}
if (usedradius < 1) {
return null
}
val w = (width * scale).toInt()
val h = (height * scale).toInt()
val pix = IntArray(w * h)
bitmap.getPixels(pix, 0, w, fromX, fromY, w, h)
val wm = w - 1
val hm = h - 1
val wh = w * h
val div = usedradius + usedradius + 1
val r = IntArray(wh)
val g = IntArray(wh)
val b = IntArray(wh)
var rsum: Int
var gsum: Int
var bsum: Int
var x: Int
var y: Int
var i: Int
var p: Int
var yp: Int
var yi: Int
var yw: Int
val vmin = IntArray(Math.max(w, h))
var divsum = div + 1 shr 1
divsum *= divsum
val dv = IntArray(256 * divsum)
i = 0
while (i < 256 * divsum) {
dv[i] = i / divsum
i++
}
yi = 0
yw = yi
val stack = Array(div) { IntArray(3) }
var stackpointer: Int
var stackstart: Int
var sir: IntArray
var rbs: Int
val r1 = usedradius + 1
var routsum: Int
var goutsum: Int
var boutsum: Int
var rinsum: Int
var ginsum: Int
var binsum: Int
val originRadius = usedradius
y = 0
while (y < h) {
bsum = 0
gsum = 0
rsum = 0
boutsum = 0
goutsum = 0
routsum = 0
binsum = 0
ginsum = 0
rinsum = 0
i = -usedradius
while (i <= usedradius) {
p = pix[yi + Math.min(wm, Math.max(i, 0))]
sir = stack[i + usedradius]
sir[0] = p and 0xff0000 shr 16
sir[1] = p and 0x00ff00 shr 8
sir[2] = p and 0x0000ff
rbs = r1 - Math.abs(i)
rsum += sir[0] * rbs
gsum += sir[1] * rbs
bsum += sir[2] * rbs
if (i > 0) {
rinsum += sir[0]
ginsum += sir[1]
binsum += sir[2]
} else {
routsum += sir[0]
goutsum += sir[1]
boutsum += sir[2]
}
i++
}
stackpointer = usedradius
x = 0
while (x < w) {
r[yi] = dv[rsum]
g[yi] = dv[gsum]
b[yi] = dv[bsum]
rsum -= routsum
gsum -= goutsum
bsum -= boutsum
stackstart = stackpointer - usedradius + div
sir = stack[stackstart % div]
routsum -= sir[0]
goutsum -= sir[1]
boutsum -= sir[2]
if (y == 0) {
vmin[x] = Math.min(x + usedradius + 1, wm)
}
p = pix[yw + vmin[x]]
sir[0] = p and 0xff0000 shr 16
sir[1] = p and 0x00ff00 shr 8
sir[2] = p and 0x0000ff
rinsum += sir[0]
ginsum += sir[1]
binsum += sir[2]
rsum += rinsum
gsum += ginsum
bsum += binsum
stackpointer = (stackpointer + 1) % div
sir = stack[stackpointer % div]
routsum += sir[0]
goutsum += sir[1]
boutsum += sir[2]
rinsum -= sir[0]
ginsum -= sir[1]
binsum -= sir[2]
yi++
x++
}
yw += w
y++
}
usedradius = originRadius
x = 0
while (x < w) {
bsum = 0
gsum = 0
rsum = 0
boutsum = 0
goutsum = 0
routsum = 0
binsum = 0
ginsum = 0
rinsum = 0
yp = -usedradius * w
i = -usedradius
while (i <= usedradius) {
yi = Math.max(0, yp) + x
sir = stack[i + usedradius]
sir[0] = r[yi]
sir[1] = g[yi]
sir[2] = b[yi]
rbs = r1 - Math.abs(i)
rsum += r[yi] * rbs
gsum += g[yi] * rbs
bsum += b[yi] * rbs
if (i > 0) {
rinsum += sir[0]
ginsum += sir[1]
binsum += sir[2]
} else {
routsum += sir[0]
goutsum += sir[1]
boutsum += sir[2]
}
if (i < hm) {
yp += w
}
i++
}
yi = x
stackpointer = usedradius
y = 0
while (y < h) {
pix[yi] = 0xff000000.toInt() or ((dv[rsum] * brightnessMod).toInt() shl 16) or ((dv[gsum] * brightnessMod).toInt() shl 8) or (dv[bsum] * brightnessMod).toInt()
rsum -= routsum
gsum -= goutsum
bsum -= boutsum
stackstart = stackpointer - usedradius + div
sir = stack[stackstart % div]
routsum -= sir[0]
goutsum -= sir[1]
boutsum -= sir[2]
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w
}
p = x + vmin[y]
sir[0] = r[p]
sir[1] = g[p]
sir[2] = b[p]
rinsum += sir[0]
ginsum += sir[1]
binsum += sir[2]
rsum += rinsum
gsum += ginsum
bsum += binsum
stackpointer = (stackpointer + 1) % div
sir = stack[stackpointer]
routsum += sir[0]
goutsum += sir[1]
boutsum += sir[2]
rinsum -= sir[0]
ginsum -= sir[1]
binsum -= sir[2]
yi += w
y++
}
x++
}
bitmap.setPixels(pix, 0, w, fromX, fromY, w, h)
return bitmap
}
// for jpegs
class FlushedInputStream(inputStream: InputStream) : FilterInputStream(inputStream) {
@Throws(IOException::class)
override fun skip(n: Long): Long {
var totalBytesSkipped = 0L
while (totalBytesSkipped < n) {
var bytesSkipped = `in`.skip(n - totalBytesSkipped)
if (bytesSkipped == 0L) {
val byteSkipped = read()
if (byteSkipped < 0) {
break // we reached EOF
} else {
bytesSkipped = 1 // we read one byte
}
}
totalBytesSkipped += bytesSkipped
}
return totalBytesSkipped
}
}
}
| ViolinDS/app/src/main/java/ds/violin/v1/util/common/Bitmaps.kt | 4294775325 |
package com.jospint.droiddevs.architecturecomponents.util.extension
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
})
}
| ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/util/extension/EditTexts.kt | 3355655703 |
/*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle
import java.util.*
import org.gradle.api.DefaultTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
/**
* A task that generates a dependency versions `.properties` file.
*/
abstract class WriteVersions : DefaultTask() {
/**
* Versions to add to the file.
*
* The map key is a string in the format of `<group ID>_<artifact name>`, and the value
* is the version corresponding to those group ID and artifact name.
*
* @see WriteVersions.version
*/
@get:Input
abstract val versions: MapProperty<String, String>
/**
* The directory that hosts the generated file.
*/
@get:OutputDirectory
abstract val versionsFileLocation: DirectoryProperty
/**
* Adds a dependency version to write into the file.
*
* The given dependency notation is a Gradle artifact string of format:
* `"<group ID>:<artifact name>:<version>"`.
*
* @see WriteVersions.versions
* @see WriteVersions.includeOwnVersion
*/
fun version(dependencyNotation: String) {
val parts = dependencyNotation.split(":")
check(parts.size == 3) { "Invalid dependency notation: `$dependencyNotation`." }
versions.put("${parts[0]}_${parts[1]}", parts[2])
}
/**
* Enables the versions file to include the version of the project that owns this task.
*
* @see WriteVersions.version
* @see WriteVersions.versions
*/
fun includeOwnVersion() {
val groupId = project.group.toString()
val artifactId = project.artifactId
val version = project.version.toString()
versions.put("${groupId}_${artifactId}", version)
}
/**
* Creates a `.properties` file with versions, named after the value
* of [Project.artifactId] property.
*
* The name of the file would be: `versions-<artifactId>.properties`.
*
* By default, value of [Project.artifactId] property is a project's name with "spine-" prefix.
* For example, if a project's name is "tools", then the name of the file would be:
* `versions-spine-tools.properties`.
*/
@TaskAction
fun writeFile() {
versions.finalizeValue()
versionsFileLocation.finalizeValue()
val values = versions.get()
val properties = Properties()
properties.putAll(values)
val outputDir = versionsFileLocation.get().asFile
outputDir.mkdirs()
val fileName = resourceFileName()
val file = outputDir.resolve(fileName)
file.createNewFile()
file.writer().use {
properties.store(it, "Dependency versions supplied by the `$path` task.")
}
}
private fun resourceFileName(): String {
val artifactId = project.artifactId
return "versions-${artifactId}.properties"
}
}
/**
* A plugin that enables storing dependency versions into a resource file.
*
* Dependency version may be used by Gradle plugins at runtime.
*
* The plugin adds one task — `writeVersions`, which generates a `.properties` file with some
* dependency versions.
*
* The generated file will be available in classpath of the target project under the name:
* `versions-<project name>.properties`, where `<project name>` is the name of the target
* Gradle project.
*/
@Suppress("unused")
class VersionWriter : Plugin<Project> {
override fun apply(target: Project): Unit = with (target.tasks) {
val task = register("writeVersions", WriteVersions::class.java) {
versionsFileLocation.convention(project.layout.buildDirectory.dir(name))
includeOwnVersion()
project.sourceSets
.getByName("main")
.resources
.srcDir(versionsFileLocation)
}
getByName("processResources").dependsOn(task)
}
}
| buildSrc/src/main/kotlin/io/spine/internal/gradle/VersionWriter.kt | 2871180512 |
package uk.co.ribot.androidboilerplate
import android.app.Application
import android.support.annotation.VisibleForTesting
import com.squareup.leakcanary.LeakCanary
import timber.log.Timber
import uk.co.ribot.androidboilerplate.injection.component.ApplicationComponent
import uk.co.ribot.androidboilerplate.injection.component.DaggerApplicationComponent
import uk.co.ribot.androidboilerplate.injection.module.ApplicationModule
open class BoilerplateApplication: Application() {
lateinit var applicationComponent: ApplicationComponent
private set
override fun onCreate() {
super.onCreate()
if (LeakCanary.isInAnalyzerProcess(this))
return
LeakCanary.install(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
initDaggerComponent()
}
@VisibleForTesting
fun initDaggerComponent() {
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
}
}
| app/src/main/kotlin/uk/co/ribot/androidboilerplate/BoilerplateApplication.kt | 3998453549 |
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isPartOf
import io.gitlab.arturbosch.detekt.rules.isPartOfString
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression
/**
* This rule reports if tabs are used in Kotlin files.
* According to
* [Google's Kotlin style guide](https://android.github.io/kotlin-guides/style.html#whitespace-characters)
* the only whitespace chars that are allowed in a source file are the line terminator sequence
* and the ASCII horizontal space character (0x20). Strings containing tabs are allowed.
*/
class NoTabs(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"Checks if tabs are used in Kotlin files.",
Debt.FIVE_MINS
)
fun findTabs(file: KtFile) {
file.collectWhitespaces()
.filter { it.isTab() }
.forEach { report(CodeSmell(issue, Entity.from(it), "Tab character is in use.")) }
}
private fun KtFile.collectWhitespaces(): List<PsiWhiteSpace> {
val list = mutableListOf<PsiWhiteSpace>()
this.accept(object : DetektVisitor() {
override fun visitWhiteSpace(space: PsiWhiteSpace) {
list.add(space)
super.visitWhiteSpace(space)
}
})
return list
}
private fun PsiWhiteSpace.isTab(): Boolean {
return (!isPartOfString() || isStringInterpolated()) && text.contains('\t')
}
private fun PsiWhiteSpace.isStringInterpolated(): Boolean =
this.isPartOf<KtStringTemplateEntryWithExpression>()
}
| detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/NoTabs.kt | 2845960038 |
package net.nemerosa.ontrack.extension.indicators.ui
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategory
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCompliance
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.model.structure.NameDescription.Companion.nd
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.Signature
import org.junit.Before
import org.junit.Test
import kotlin.test.assertSame
class IndicatorControllerTest {
private lateinit var projectIndicatorService: ProjectIndicatorService
private lateinit var controller: IndicatorController
@Before
fun before() {
projectIndicatorService = mock()
controller = IndicatorController(projectIndicatorService)
}
@Test
fun getUpdateFormForIndicator() {
val form = Form.create()
whenever(projectIndicatorService.getUpdateFormForIndicator(ID.of(1), "type")).thenReturn(form)
val returnedForm = controller.getUpdateFormForIndicator(ID.of(1), "type")
assertSame(form, returnedForm)
}
@Test
fun updateIndicator() {
val value = ProjectIndicator(
project = Project.of(nd("P", "")).withId(ID.of(1)),
type = ProjectIndicatorType(
id = "type",
name = "Type",
link = null,
category = IndicatorCategory("category", "Category", null),
source = null,
computed = false,
deprecated = null
),
value = mapOf("value" to "true").asJson(),
compliance = IndicatorCompliance(100),
comment = null,
signature = Signature.anonymous()
)
val input = mapOf("value" to "true").asJson()
whenever(projectIndicatorService.updateIndicator(ID.of(1), "type", input)).thenReturn(value)
val returned = controller.updateIndicator(ID.of(1), "type", input)
assertSame(value, returned)
}
@Test
fun deleteIndicator() {
controller.deleteIndicator(ID.of(1), "type")
verify(projectIndicatorService).deleteIndicator(ID.of(1), "type")
}
} | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/IndicatorControllerTest.kt | 2387213795 |
package ch.bailu.aat_gtk.view.menu.provider
import ch.bailu.aat_gtk.lib.menu.MenuModelBuilder
import ch.bailu.aat_gtk.solid.GtkMapDirectories
import ch.bailu.aat_gtk.view.UiController
import ch.bailu.aat_lib.map.MapContext
import ch.bailu.aat_lib.preferences.map.SolidMapTileStack
import ch.bailu.aat_lib.preferences.map.SolidOverlayFileList
import ch.bailu.aat_lib.resources.Res
import ch.bailu.foc.FocFactory
import ch.bailu.gtk.gtk.Window
class MapMenu(
private val uiController: UiController,
private val mapContext: MapContext,
mapDirectories: GtkMapDirectories,
focFactory: FocFactory,
window: Window
) : MenuProvider {
private val srender = mapDirectories.createSolidRenderTheme()
private val renderMenu = SolidFileSelectorMenu(srender, window)
private val soverlay = SolidOverlayFileList(srender.storage, focFactory)
private val overlayMenu = SolidCheckMenu(soverlay)
private val soffline = mapDirectories.createSolidFile()
private val offlineMenu = SolidFileSelectorMenu(soffline, window)
private val stiles = SolidMapTileStack(srender)
private val tilesMenu = SolidCheckMenu(stiles)
override fun createMenu(): MenuModelBuilder {
return MenuModelBuilder()
.submenu(stiles.label, tilesMenu.createMenu())
.submenu(soverlay.label, overlayMenu.createMenu())
.submenu(soffline.label, offlineMenu.createMenu())
.submenu(srender.label, renderMenu.createMenu())
.label(Res.str().intro_settings()) {
uiController.showPreferencesMap()
}
.label(Res.str().tt_info_reload()) {
mapContext.mapView.reDownloadTiles()
}
}
override fun createCustomWidgets(): Array<CustomWidget> {
return tilesMenu.createCustomWidgets() +
overlayMenu.createCustomWidgets() +
offlineMenu.createCustomWidgets() +
renderMenu.createCustomWidgets()
}
}
| aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/menu/provider/MapMenu.kt | 2262188668 |
package com.beust.kobalt.maven
import java.io.File
/**
* Represents a dependency that doesn't have a version: "org.testng:testng:". Such dependencies
* eventually resolve to the latest version of the artifact.
*/
open class UnversionedDep(open val groupId: String, open val artifactId: String) {
open fun toMetadataXmlPath(fileSystem: Boolean = true, isLocal: Boolean, version: String? = null) : String {
var result = toDirectory("", fileSystem) + if (isLocal) "maven-metadata-local.xml" else "maven-metadata.xml"
if (! File(result).exists() && version != null) {
result = toDirectory("", fileSystem) + version + File.separator +
if (isLocal) "maven-metadata-local.xml" else "maven-metadata.xml"
}
return result
}
/**
* Turn this dependency to a directory. If fileSystem is true, use the file system
* dependent path separator, otherwise, use '/' (used to create URL's).
*/
fun toDirectory(v: String, fileSystem: Boolean = true, trailingSlash: Boolean = true): String {
val sep = if (fileSystem) File.separator else "/"
val l = listOf(groupId.replace(".", sep), artifactId, v)
val result = l.joinToString(sep)
return if (trailingSlash && ! result.endsWith(sep)) result + sep else result
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/UnversionedDep.kt | 1990430995 |
package com.beust.kobalt
import com.beust.kobalt.api.KobaltContext
import com.beust.kobalt.app.MainModule
import com.beust.kobalt.internal.ILogger
import com.beust.kobalt.internal.KobaltSettings
import com.beust.kobalt.internal.KobaltSettingsXml
import com.beust.kobalt.maven.LocalRepo
import com.beust.kobalt.maven.aether.KobaltMavenResolver
import com.beust.kobalt.misc.kobaltLog
import com.google.common.eventbus.EventBus
import com.google.inject.Provider
import com.google.inject.Scopes
import java.io.File
import java.util.concurrent.ExecutorService
val LOCAL_CACHE = File(SystemProperties.homeDir + File.separatorChar + ".kobalt-test")
val TEST_KOBALT_SETTINGS = KobaltSettings(KobaltSettingsXml()).apply {
localCache = LOCAL_CACHE
}
class TestLocalRepo: LocalRepo(TEST_KOBALT_SETTINGS)
class TestModule : MainModule(Args(), TEST_KOBALT_SETTINGS) {
override fun configureTest() {
val localRepo = TestLocalRepo()
bind(LocalRepo::class.java).toInstance(localRepo)
// val localAether = Aether(LOCAL_CACHE, TEST_KOBALT_SETTINGS, EventBus())
val testResolver = KobaltMavenResolver(KobaltSettings(KobaltSettingsXml()), Args(), TestLocalRepo(), EventBus())
bind(KobaltMavenResolver::class.java).to(testResolver)
bind(KobaltContext::class.java).toProvider(Provider<KobaltContext> {
KobaltContext(args).apply {
resolver = testResolver
logger = object: ILogger {
override fun log(tag: CharSequence, level: Int, message: CharSequence, newLine: Boolean) {
kobaltLog(1, "TestLog: [$tag $level] " + message)
}
}
}
}).`in`(Scopes.SINGLETON)
}
override fun bindExecutors() {
// in tests do nothing to bind new executors for each tests
// this avoids tests submitting tasks after pool shutdown
}
}
| src/test/kotlin/com/beust/kobalt/TestModule.kt | 2083273787 |
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.preview
import androidx.test.espresso.intent.rule.IntentsTestRule
import com.nextcloud.client.TestActivity
import com.owncloud.android.AbstractIT
import org.junit.Rule
class PreviewImageFragmentIT : AbstractIT() {
@get:Rule
val testActivityRule = IntentsTestRule(TestActivity::class.java, true, false)
// Disabled for now due to strange failing when using entire test suite
// Findings so far:
// PreviewImageFragmentIT runs fine when only running this
// running it in whole test suite fails
// manually tried to execute LoadBitmapTask, but this does not start "doInBackground", but only creates class
// @Test
// @ScreenshotTest
// fun corruptImage() {
// val activity = testActivityRule.launchActivity(null)
//
// val ocFile = OCFile("/test.png")
// val sut = PreviewImageFragment.newInstance(ocFile, true, false)
//
// activity.addFragment(sut)
//
// while (!sut.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
// shortSleep()
// }
//
// screenshot(activity)
// }
//
// @Test
// @ScreenshotTest
// fun validImage() {
// val activity = testActivityRule.launchActivity(null)
//
// val ocFile = OCFile("/test.png")
// ocFile.storagePath = getFile("imageFile.png").absolutePath
//
// val sut = PreviewImageFragment.newInstance(ocFile, true, false)
//
// activity.addFragment(sut)
//
// while (!sut.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
// shortSleep()
// }
//
// screenshot(activity)
// }
}
| app/src/androidTest/java/com/owncloud/android/ui/preview/PreviewImageFragmentIT.kt | 3330791079 |
package com.groupdocs.ui.modules
import com.groupdocs.ui.config.ComparerConfig
import org.koin.java.KoinJavaComponent.inject
open class BaseController {
protected val comparerConfig by inject<ComparerConfig>(ComparerConfig::class.java)
} | Demos/Ktor/src/main/kotlin/com/groupdocs/ui/modules/BaseController.kt | 679466013 |
//@file:JvmName("Log")
package de.jupf.staticlog
import de.jupf.staticlog.core.Logger
import de.jupf.staticlog.core.LogLevel
import de.jupf.staticlog.format.Builder
import de.jupf.staticlog.format.Indent
import de.jupf.staticlog.format.Line
import de.jupf.staticlog.format.LogFormat
import de.jupf.staticlog.printer.AndroidPrinter
import de.jupf.staticlog.printer.DesktopPrinter
import de.jupf.staticlog.printer.Printer
import java.util.*
/**
* The StaticLog main logging interface object
*
* @author J.Pfeifer
* @created on 03.02.2016.
*/
object Log {
internal val logInstance = Logger(4)
@JvmStatic var logLevel: LogLevel
get() = logInstance.logLevel
set(value) {
logInstance.logLevel = value
}
var filterTag: String
get() = logInstance.filterTag
set(value) { logInstance.filterTag = value }
@JvmStatic val slf4jLogInstancesMap: Map<String,Logger> = LinkedHashMap()
@JvmStatic
var slf4jLogLevel: LogLevel
get() = SLF4JBindingFacade.logLevel
set(value) {
SLF4JBindingFacade.logLevel = value
}
/**
* Returns a logger instance for Java
*/
@JvmStatic
fun javaInstance(): Logger {
return Logger(4)
}
/**
* Returns a logger instance for kotlin
*/
@JvmStatic
fun kotlinInstance(): Logger {
return Logger(3)
}
/**
* Adding the given [printer] to the printers used by this [Logger]
*/
@JvmStatic
fun addPrinter(printer: Printer) {
logInstance.addPrinter(printer)
}
/**
* Resets the [Printer] of this [Logger] to the default.
*/
@JvmStatic
fun setDefaultPrinter() {
logInstance.setDefaultPrinter()
}
/**
* Sets the given [printer] as the new and only printer for this [Logger].
*/
@JvmStatic
fun setPrinter(printer: Printer) {
logInstance.setPrinter(printer)
}
/**
* Logs a debug message.
*
* @param message The log message
* @param tag The tag the message is logged under
* @param throwable The log-related throwable
*/
@JvmStatic
fun debug(message: String, tag: String, throwable: Throwable) {
logInstance.debug(message, tag, throwable)
}
/**
* Logs a debug message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
* @param throwable The log-related throwable
*/
@JvmStatic
fun debug(message: String, throwable: Throwable) {
logInstance.debug(message, throwable)
}
/**
* Logs a debug message.
*
* @param message The log message
* @param tag The tag the message is logged under
*/
@JvmStatic
fun debug(message: String, tag: String) {
logInstance.debug(message, tag)
}
/**
* Logs a debug message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
*/
@JvmStatic
fun debug(message: String) {
logInstance.debug(message)
}
/**
* Logs an info message.
*
* @param message The log message
* @param tag The tag the message is logged under
* @param throwable The log-related throwable
*/
@JvmStatic
fun info(message: String, tag: String, throwable: Throwable) {
logInstance.info(message, tag, throwable)
}
/**
* Logs an info message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
* @param throwable The log-related throwable
*/
@JvmStatic
fun info(message: String, throwable: Throwable) {
logInstance.info(message, throwable)
}
/**
* Logs an info message.
*
* @param message The log message
* @param tag The tag the message is logged under
*/
@JvmStatic
fun info(message: String, tag: String) {
logInstance.info(message, tag)
}
/**
* Logs an info message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
*/
@JvmStatic
fun info(message: String) {
logInstance.info(message)
}
/**
* Logs a warning message.
*
* @param message The log message
* @param tag The tag the message is logged under
* @param throwable The log-related throwable
*/
@JvmStatic
fun warn(message: String, tag: String, throwable: Throwable) {
logInstance.warn(message, tag, throwable)
}
/**
* Logs a warning message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
* @param throwable The log-related throwable
*/
@JvmStatic
fun warn(message: String, throwable: Throwable) {
logInstance.warn(message, throwable)
}
/**
* Logs a warning message.
*
* @param message The log message
* @param tag The tag the message is logged under
*/
@JvmStatic
fun warn(message: String, tag: String) {
logInstance.warn(message, tag)
}
/**
* Logs a warning message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
*/
@JvmStatic
fun warn(message: String) {
logInstance.warn(message)
}
/**
* Logs an error message.
*
* @param message The log message
* @param tag The tag the message is logged under
* @param throwable The log-related throwable
*/
@JvmStatic
fun error(message: String, tag: String, throwable: Throwable) {
logInstance.error(message, tag, throwable)
}
/**
* Logs an error message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
* @param throwable The log-related throwable
*/
@JvmStatic
fun error(message: String, throwable: Throwable) {
logInstance.error(message, throwable)
}
/**
* Logs an error message.
*
* @param message The log message
* @param tag The tag the message is logged under
*/
@JvmStatic
fun error(message: String, tag: String) {
logInstance.error(message, tag)
}
/**
* Logs an error message.
* The tag will default to the class name the log is created from.
*
* @param message The log message
*/
@JvmStatic
fun error(message: String) {
logInstance.error(message)
}
/**
* This method deletes the old [LogFormat] and
* returns a handle to create the new format with.
*
* @return log format handle
*/
@JvmStatic
fun newFormat(): LogFormat {
return logInstance.newFormat()
}
/**
* Sets a tag filter for this Logger.
* Only messages with this tag will be printed.
*
* @param filterTag
*/
@JvmStatic
fun setTagFilter(filterTag: String) {
logInstance.filterTag = filterTag
}
/**
* Deletes a previously set tag filter.
*/
@JvmStatic
fun deleteTagFilter() {
logInstance.deleteTagFilter()
}
fun newFormat(buildFun: LogFormat.() -> Unit) {
logInstance.newFormat(buildFun)
}
object FormatOperations {
/**
* Creates a space [Builder] which prints [times] spaces.
*
* @param times number of spaces to print
*
* @return [Builder] for spaces
*/
@JvmStatic
fun space(times: Int): Builder {
return Log.logInstance.logFormat.space(times)
}
/**
* Creates a tab [Builder] which prints [times] tabs.
* @param times number of tabs to print
*
* @return [Builder] for tabs
*/
@JvmStatic
fun tab(times: Int): Builder {
return Log.logInstance.logFormat.tab(times)
}
/**
* Creates a date [Builder] which prints the actual date/time in the given [format].
* @param format String in a [SimpleDateFormat](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)
*
* @return [Builder] for spaces
*/
@JvmStatic
fun date(format: String): Builder {
return Log.logInstance.logFormat.date(format)
}
/**
* Creates a [Builder] which prints the current time in milliseconds.
*
* @return [Builder] for time since epoch
*/
@JvmStatic
fun epoch(): Builder {
return Log.logInstance.logFormat.epoch
}
/**
* Creates a [Builder] which prints the [LogLevel] of the log.
*
* @return [Builder] for current [LogLevel]
*/
@JvmStatic
fun level(): Builder {
return Log.logInstance.logFormat.level
}
/**
* Creates a [Builder] which prints the log message itself.
*
* @return [Builder] for the message
*/
@JvmStatic
fun message(): Builder {
return Log.logInstance.logFormat.message
}
/**
* Creates a [Builder] which prints the tag of the log.
*
* @return [Builder] for the tag
*/
@JvmStatic
fun tag(): Builder {
return Log.logInstance.logFormat.tag
}
/**
* Creates a [Builder] which prints the fully qualified name of the occurrence of the log.
*
* @return [Builder] for the occurrence
*/
@JvmStatic
fun occurrence(): Builder {
return Log.logInstance.logFormat.occurrence
}
/**
* Creates a Builder which prints the given [text]
*
* @param text the text to print
*
* @return [Builder] for [text]
*/
@JvmStatic
fun text(text: String): Builder {
return Log.logInstance.logFormat.text(text)
}
/**
* Creates a [Builder] which prints all added Builders.
*
* @return [Builder] for current [LogLevel]
*/
@JvmStatic
fun line(vararg builders: Builder): Builder {
val line = Line()
for (i in builders.indices) {
line.children.add(builders[i])
}
return line
}
@JvmStatic
fun indent(vararg builders: Builder): Builder {
val indent = Indent()
for (i in builders.indices) {
indent.children.add(builders[i])
}
return indent
}
}
}
| src/main/kotlin/de/jupf/staticlog/Log.kt | 2799593333 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.fabric.creator
import com.demonwav.mcdev.creator.buildsystem.BuildSystem
import com.demonwav.mcdev.platform.BaseTemplate
import com.demonwav.mcdev.platform.forge.inspections.sideonly.Side
import com.demonwav.mcdev.util.License
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_BUILD_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_GRADLE_PROPERTIES_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_MIXINS_JSON_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_MOD_JSON_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_SETTINGS_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_SUBMODULE_BUILD_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_SUBMODULE_GRADLE_PROPERTIES_TEMPLATE
import com.demonwav.mcdev.util.toPackageName
import com.intellij.openapi.project.Project
object FabricTemplate : BaseTemplate() {
private fun Project.applyGradleTemplate(
templateName: String,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
val props = mutableMapOf<String, Any>(
"GROUP_ID" to buildSystem.groupId,
"ARTIFACT_ID" to buildSystem.artifactId,
"VERSION" to buildSystem.version,
"MC_VERSION" to config.mcVersion,
"YARN_MAPPINGS" to config.yarnVersion,
"LOADER_VERSION" to config.loaderVersion.toString(),
"LOOM_VERSION" to config.loomVersion.toString(),
"JAVA_VERSION" to config.javaVersion.feature
)
config.yarnClassifier?.let {
props["YARN_CLASSIFIER"] = it
}
config.apiVersion?.let {
props["API_VERSION"] = it.toString()
}
config.apiMavenLocation?.let {
props["API_MAVEN_LOCATION"] = it
}
return applyTemplate(templateName, props)
}
fun applyBuildGradle(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_BUILD_GRADLE_TEMPLATE, buildSystem, config)
}
fun applyMultiModuleBuildGradle(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_SUBMODULE_BUILD_GRADLE_TEMPLATE, buildSystem, config)
}
fun applySettingsGradle(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_SETTINGS_GRADLE_TEMPLATE, buildSystem, config)
}
fun applyGradleProp(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_GRADLE_PROPERTIES_TEMPLATE, buildSystem, config)
}
fun applyMultiModuleGradleProp(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_SUBMODULE_GRADLE_PROPERTIES_TEMPLATE, buildSystem, config)
}
fun applyFabricModJsonTemplate(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
val props = mutableMapOf<String, Any>(
"ARTIFACT_ID" to buildSystem.artifactId,
"MOD_NAME" to config.pluginName,
"MOD_DESCRIPTION" to (config.description ?: ""),
"MOD_ENVIRONMENT" to when (config.environment) {
Side.CLIENT -> "client"
Side.SERVER -> "server"
else -> "*"
},
"LOADER_VERSION" to config.loaderVersion.toString(),
"MC_VERSION" to config.semanticMcVersion.toString(),
"JAVA_VERSION" to config.javaVersion.feature,
"LICENSE" to ((config.license ?: License.ALL_RIGHTS_RESERVED).id)
)
config.apiVersion?.let {
props["API_VERSION"] = it.toString()
}
if (config.mixins) {
props["MIXINS"] = "true"
}
return project.applyTemplate(FABRIC_MOD_JSON_TEMPLATE, props)
}
fun applyMixinConfigTemplate(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
val packageName = "${buildSystem.groupId.toPackageName()}.${buildSystem.artifactId.toPackageName()}.mixin"
val props = mapOf(
"PACKAGE_NAME" to packageName,
"JAVA_VERSION" to config.javaVersion.feature
)
return project.applyTemplate(FABRIC_MIXINS_JSON_TEMPLATE, props)
}
}
| src/main/kotlin/platform/fabric/creator/FabricTemplate.kt | 2805470795 |
package com.hewking.demo
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hewking.custom.R
import kotlinx.android.synthetic.main.activity_key_board.view.*
/**
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/7/23
* 修改人员:hewking
* 修改时间:2018/7/23
* 修改备注:
* Version: 1.0.0
*/
class DYRecordFragment : androidx.fragment.app.Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_dyrecord,container,false)
}
} | app/src/main/java/com/hewking/demo/DYRecordFragment.kt | 629057929 |
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.postgresql.messages.backend
object CloseComplete : ServerMessage(ServerMessage.CloseComplete) | postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/messages/backend/CloseComplete.kt | 259742719 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.util
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.lang.jvm.annotation.JvmAnnotationConstantValue
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiModifierListOwner
fun PsiMember.isInSpongePluginClass(): Boolean = this.containingClass?.isSpongePluginClass() == true
fun PsiClass.isSpongePluginClass(): Boolean = this.hasAnnotation(SpongeConstants.PLUGIN_ANNOTATION) ||
this.hasAnnotation(SpongeConstants.JVM_PLUGIN_ANNOTATION)
fun PsiElement.spongePluginClassId(): String? {
val clazz = this.findContainingClass() ?: return null
val annotation = clazz.getAnnotation(SpongeConstants.PLUGIN_ANNOTATION)
?: clazz.getAnnotation(SpongeConstants.JVM_PLUGIN_ANNOTATION)
return annotation?.findAttributeValue("id")?.constantStringValue
}
fun isInjected(element: PsiModifierListOwner, optionalSensitive: Boolean): Boolean {
val annotation = element.getAnnotation(SpongeConstants.INJECT_ANNOTATION) ?: return false
if (!optionalSensitive) {
return true
}
return !isInjectOptional(annotation)
}
fun isInjectOptional(annotation: PsiAnnotation): Boolean {
val optional = annotation.findAttribute("optional") ?: return false
val value = optional.attributeValue
return value is JvmAnnotationConstantValue && value.constantValue == true
}
| src/main/kotlin/platform/sponge/util/SpongeUtils.kt | 1306510732 |
package org.ojacquemart.eurobets.firebase.initdb.fixture
object Phases {
private val regexCleanEndOfFinalPhase = Regex("""_\d+$""")
private val regexCleanUnderscoreOrDash = Regex("[-|_]")
fun clean(phase: String): String {
return phase.replace(regexCleanEndOfFinalPhase, "").replace(regexCleanUnderscoreOrDash, "")
}
}
| src/main/kotlin/org/ojacquemart/eurobets/firebase/initdb/fixture/Phases.kt | 2830893769 |
public object `$$Anko$Factories$AppcompatV7View` {
public val TINTED_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatAutoCompleteTextView(ctx) else AutoCompleteTextView(ctx) }
public val TINTED_BUTTON = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatButton(ctx) else Button(ctx) }
public val TINTED_CHECK_BOX = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatCheckBox(ctx) else CheckBox(ctx) }
public val TINTED_CHECKED_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatCheckedTextView(ctx) else CheckedTextView(ctx) }
public val TINTED_EDIT_TEXT = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatEditText(ctx) else EditText(ctx) }
public val TINTED_MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatMultiAutoCompleteTextView(ctx) else MultiAutoCompleteTextView(ctx) }
public val TINTED_RADIO_BUTTON = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatRadioButton(ctx) else RadioButton(ctx) }
public val TINTED_RATING_BAR = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatRatingBar(ctx) else RatingBar(ctx) }
public val TINTED_SPINNER = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatSpinner(ctx) else Spinner(ctx) }
public val TINTED_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatTextView(ctx) else TextView(ctx) }
public val SEARCH_VIEW = { ctx: Context -> android.support.v7.widget.SearchView(ctx) }
public val SWITCH_COMPAT = { ctx: Context -> android.support.v7.widget.SwitchCompat(ctx) }
}
public inline fun ViewManager.tintedAutoCompleteTextView(): AutoCompleteTextView = tintedAutoCompleteTextView({})
public inline fun ViewManager.tintedAutoCompleteTextView(init: AutoCompleteTextView.() -> Unit): AutoCompleteTextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_AUTO_COMPLETE_TEXT_VIEW) { init() }
}
public inline fun ViewManager.tintedButton(): Button = tintedButton({})
public inline fun ViewManager.tintedButton(init: Button.() -> Unit): Button {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) { init() }
}
public inline fun ViewManager.tintedButton(text: CharSequence?): Button {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) {
setText(text)
}
}
public inline fun ViewManager.tintedButton(text: CharSequence?, init: Button.() -> Unit): Button {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedButton(text: Int): Button {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) {
setText(text)
}
}
public inline fun ViewManager.tintedButton(text: Int, init: Button.() -> Unit): Button {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedCheckBox(): CheckBox = tintedCheckBox({})
public inline fun ViewManager.tintedCheckBox(init: CheckBox.() -> Unit): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { init() }
}
public inline fun ViewManager.tintedCheckBox(text: CharSequence?): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
setText(text)
}
}
public inline fun ViewManager.tintedCheckBox(text: CharSequence?, init: CheckBox.() -> Unit): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedCheckBox(text: Int): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
setText(text)
}
}
public inline fun ViewManager.tintedCheckBox(text: Int, init: CheckBox.() -> Unit): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedCheckBox(text: CharSequence?, checked: Boolean): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.tintedCheckBox(text: CharSequence?, checked: Boolean, init: CheckBox.() -> Unit): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
init()
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.tintedCheckBox(text: Int, checked: Boolean): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.tintedCheckBox(text: Int, checked: Boolean, init: CheckBox.() -> Unit): CheckBox {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) {
init()
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.tintedCheckedTextView(): CheckedTextView = tintedCheckedTextView({})
public inline fun ViewManager.tintedCheckedTextView(init: CheckedTextView.() -> Unit): CheckedTextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECKED_TEXT_VIEW) { init() }
}
public inline fun ViewManager.tintedEditText(): EditText = tintedEditText({})
public inline fun ViewManager.tintedEditText(init: EditText.() -> Unit): EditText {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) { init() }
}
public inline fun ViewManager.tintedEditText(text: CharSequence?): EditText {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) {
setText(text)
}
}
public inline fun ViewManager.tintedEditText(text: CharSequence?, init: EditText.() -> Unit): EditText {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedEditText(text: Int): EditText {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) {
setText(text)
}
}
public inline fun ViewManager.tintedEditText(text: Int, init: EditText.() -> Unit): EditText {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedMultiAutoCompleteTextView(): MultiAutoCompleteTextView = tintedMultiAutoCompleteTextView({})
public inline fun ViewManager.tintedMultiAutoCompleteTextView(init: MultiAutoCompleteTextView.() -> Unit): MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() }
}
public inline fun ViewManager.tintedRadioButton(): RadioButton = tintedRadioButton({})
public inline fun ViewManager.tintedRadioButton(init: RadioButton.() -> Unit): RadioButton {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_RADIO_BUTTON) { init() }
}
public inline fun ViewManager.tintedRatingBar(): RatingBar = tintedRatingBar({})
public inline fun ViewManager.tintedRatingBar(init: RatingBar.() -> Unit): RatingBar {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_RATING_BAR) { init() }
}
public inline fun ViewManager.tintedSpinner(): Spinner = tintedSpinner({})
public inline fun ViewManager.tintedSpinner(init: Spinner.() -> Unit): Spinner {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_SPINNER) { init() }
}
public inline fun Context.tintedSpinner(): Spinner = tintedSpinner({})
public inline fun Context.tintedSpinner(init: Spinner.() -> Unit): Spinner {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_SPINNER) { init() }
}
public inline fun Activity.tintedSpinner(): Spinner = tintedSpinner({})
public inline fun Activity.tintedSpinner(init: Spinner.() -> Unit): Spinner {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_SPINNER) { init() }
}
public inline fun ViewManager.tintedTextView(): TextView = tintedTextView({})
public inline fun ViewManager.tintedTextView(init: TextView.() -> Unit): TextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) { init() }
}
public inline fun ViewManager.tintedTextView(text: CharSequence?): TextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) {
setText(text)
}
}
public inline fun ViewManager.tintedTextView(text: CharSequence?, init: TextView.() -> Unit): TextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) {
init()
setText(text)
}
}
public inline fun ViewManager.tintedTextView(text: Int): TextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) {
setText(text)
}
}
public inline fun ViewManager.tintedTextView(text: Int, init: TextView.() -> Unit): TextView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) {
init()
setText(text)
}
}
public inline fun ViewManager.searchView(): android.support.v7.widget.SearchView = searchView({})
public inline fun ViewManager.searchView(init: android.support.v7.widget.SearchView.() -> Unit): android.support.v7.widget.SearchView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.SEARCH_VIEW) { init() }
}
public inline fun Context.searchView(): android.support.v7.widget.SearchView = searchView({})
public inline fun Context.searchView(init: android.support.v7.widget.SearchView.() -> Unit): android.support.v7.widget.SearchView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.SEARCH_VIEW) { init() }
}
public inline fun Activity.searchView(): android.support.v7.widget.SearchView = searchView({})
public inline fun Activity.searchView(init: android.support.v7.widget.SearchView.() -> Unit): android.support.v7.widget.SearchView {
return ankoView(`$$Anko$Factories$AppcompatV7View`.SEARCH_VIEW) { init() }
}
public inline fun ViewManager.switchCompat(): android.support.v7.widget.SwitchCompat = switchCompat({})
public inline fun ViewManager.switchCompat(init: android.support.v7.widget.SwitchCompat.() -> Unit): android.support.v7.widget.SwitchCompat {
return ankoView(`$$Anko$Factories$AppcompatV7View`.SWITCH_COMPAT) { init() }
}
public object `$$Anko$Factories$AppcompatV7ViewGroup` {
public val ACTION_MENU_VIEW = { ctx: Context -> _ActionMenuView(ctx) }
public val LINEAR_LAYOUT_COMPAT = { ctx: Context -> _LinearLayoutCompat(ctx) }
public val TOOLBAR = { ctx: Context -> _Toolbar(ctx) }
}
public inline fun ViewManager.actionMenuView(): android.support.v7.widget.ActionMenuView = actionMenuView({})
public inline fun ViewManager.actionMenuView(init: _ActionMenuView.() -> Unit): android.support.v7.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.ACTION_MENU_VIEW) { init() }
}
public inline fun Context.actionMenuView(): android.support.v7.widget.ActionMenuView = actionMenuView({})
public inline fun Context.actionMenuView(init: _ActionMenuView.() -> Unit): android.support.v7.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.ACTION_MENU_VIEW) { init() }
}
public inline fun Activity.actionMenuView(): android.support.v7.widget.ActionMenuView = actionMenuView({})
public inline fun Activity.actionMenuView(init: _ActionMenuView.() -> Unit): android.support.v7.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.ACTION_MENU_VIEW) { init() }
}
public inline fun ViewManager.linearLayoutCompat(): android.support.v7.widget.LinearLayoutCompat = linearLayoutCompat({})
public inline fun ViewManager.linearLayoutCompat(init: _LinearLayoutCompat.() -> Unit): android.support.v7.widget.LinearLayoutCompat {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.LINEAR_LAYOUT_COMPAT) { init() }
}
public inline fun Context.linearLayoutCompat(): android.support.v7.widget.LinearLayoutCompat = linearLayoutCompat({})
public inline fun Context.linearLayoutCompat(init: _LinearLayoutCompat.() -> Unit): android.support.v7.widget.LinearLayoutCompat {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.LINEAR_LAYOUT_COMPAT) { init() }
}
public inline fun Activity.linearLayoutCompat(): android.support.v7.widget.LinearLayoutCompat = linearLayoutCompat({})
public inline fun Activity.linearLayoutCompat(init: _LinearLayoutCompat.() -> Unit): android.support.v7.widget.LinearLayoutCompat {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.LINEAR_LAYOUT_COMPAT) { init() }
}
public inline fun ViewManager.toolbar(): android.support.v7.widget.Toolbar = toolbar({})
public inline fun ViewManager.toolbar(init: _Toolbar.() -> Unit): android.support.v7.widget.Toolbar {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.TOOLBAR) { init() }
}
public inline fun Context.toolbar(): android.support.v7.widget.Toolbar = toolbar({})
public inline fun Context.toolbar(init: _Toolbar.() -> Unit): android.support.v7.widget.Toolbar {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.TOOLBAR) { init() }
}
public inline fun Activity.toolbar(): android.support.v7.widget.Toolbar = toolbar({})
public inline fun Activity.toolbar(init: _Toolbar.() -> Unit): android.support.v7.widget.Toolbar {
return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.TOOLBAR) { init() }
} | dsl/testData/functional/appcompat-v7/ViewTest.kt | 2571585486 |
package com.soywiz.korge.view
import com.soywiz.korge.input.*
import com.soywiz.korge.tests.*
import com.soywiz.korma.geom.*
import kotlin.test.*
class StageTest : ViewsForTesting() {
@Test
fun test() {
views.input.mouse.setTo(10.0, 20.0)
stage.scale(0.5, 0.5)
stage.mouse.currentPosGlobal
assertEquals(Point(20, 40), stage.mouseXY)
assertEquals(Point(20, 40), views.globalMouseXY)
}
}
| korge/src/commonTest/kotlin/com/soywiz/korge/view/StageTest.kt | 4067126258 |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.css.stylesheets
import o.katydid.css.styles.builders.KatydidStyleBuilderDsl
import o.katydid.css.stylesheets.KatydidPlaceholderRule
//---------------------------------------------------------------------------------------------------------------------
/**
* Class representing one style rule (selectors plus style properties) in a larger style sheet.
*/
@KatydidStyleBuilderDsl
internal class KatydidPlaceholderRuleImpl(
itsParent: KatydidCompositeCssRuleImpl,
itsName: String
) : KatydidAbstractStyleRuleImpl(itsParent), KatydidPlaceholderRule {
/** The placeholders extended by this placeholder. */
private val myExtendedPlaceholders = mutableListOf<KatydidPlaceholderRuleImpl>()
////
override val name = itsName
////
init {
require(name.matches(Regex("%[a-zA-Z-_]+"))) { "Invalid placeholder name: '$name'." }
}
////
override fun afterAddSelectors(addedSelectors: Collection<String>) {
for (placeholder in myExtendedPlaceholders) {
placeholder.addSelectors(addedSelectors)
}
}
override fun copy(parentOfCopy: KatydidCompositeCssRuleImpl): KatydidPlaceholderRuleImpl {
val result = KatydidPlaceholderRuleImpl(parentOfCopy, name)
result.addSelectors(selectors)
result.include(this)
result.addNestedRules(nestedRules.map { b -> b.copy(result) })
return result
}
override fun extend(vararg placeholderNames: String) {
require(properties.isEmpty()) { "Use of extend() must occur at the beginning of a placeholder rule." }
for (placeholderName in placeholderNames) {
val placeholder = parent.findPlaceholder(placeholderName)
?: throw IllegalArgumentException("Unknown placeholder rule to be extended: '$placeholderName'.")
myExtendedPlaceholders.add(placeholder)
}
}
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-CSS-JS/src/main/kotlin/i/katydid/css/stylesheets/KatydidPlaceholderRuleImpl.kt | 2427933097 |
package com.bennyhuo.coroutines.sample
import com.bennyhuo.coroutines.utils.log
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.experimental.CoroutineCallAdapterFactory
import kotlinx.coroutines.experimental.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import kotlin.coroutines.experimental.suspendCoroutine
//region common
private val gitHubServiceApi by lazy {
val retrofit = retrofit2.Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
retrofit.create(GitHubServiceApi::class.java)
}
interface GitHubServiceApi {
@GET("users/{login}")
fun getUserCallback(@Path("login") login: String): Call<User>
@GET("users/{login}")
fun getUserCoroutine(@Path("login") login: String): Deferred<User>
}
data class User(val id: String, val name: String, val url: String)
fun showUser(user: User) {
println(user)
}
fun showError(t: Throwable) {
t.printStackTrace()
}
//endregion
fun main(args: Array<String>) = runBlocking {
//useCallback()
//wrappedInSuspendFunction()
//useCoroutine()
//useTraditionalForLoop()
//useExtensionForEach()
//timeCost()
}
fun useCallback() {
gitHubServiceApi.getUserCallback("bennyhuo").enqueue(object : Callback<User> {
override fun onFailure(call: Call<User>, t: Throwable) {
showError(t)
}
override fun onResponse(call: Call<User>, response: Response<User>) {
response.body()?.let(::showUser) ?: showError(NullPointerException())
}
})
}
suspend fun wrappedInSuspendFunction() {
launch {
try {
showUser(async { getUser("bennyhuo") }.await())
} catch (e: Exception) {
showError(e)
}
}.join()
}
suspend fun getUser(login: String) = suspendCoroutine<User> { continuation ->
gitHubServiceApi.getUserCallback(login).enqueue(object : Callback<User> {
override fun onFailure(call: Call<User>, t: Throwable) {
continuation.resumeWithException(t)
}
override fun onResponse(call: Call<User>, response: Response<User>) {
response.body()?.let(continuation::resume) ?: continuation.resumeWithException(NullPointerException())
}
})
}
suspend fun useCoroutine() {
launch {
try {
showUser(gitHubServiceApi.getUserCoroutine("bennyhuo").await())
} catch (e: Exception) {
showError(e)
}
}.join()
}
suspend fun useTraditionalForLoop() {
launch {
for (login in listOf("JakeWharton", "abreslav", "yole", "elizarov")) {
try {
showUser(gitHubServiceApi.getUserCoroutine(login).await())
} catch (e: Exception) {
showError(e)
}
delay(1000)
}
}.join()
}
suspend fun useExtensionForEach() {
launch {
listOf("JakeWharton", "abreslav", "yole", "elizarov")
.forEach {
try {
showUser(gitHubServiceApi.getUserCoroutine(it).await())
} catch (e: Exception) {
showError(e)
}
delay(1000)
}
}.join()
}
suspend fun timeCost() {
launch {
cost {
listOf("JakeWharton", "abreslav", "yole", "elizarov")
.forEach {
cost {
try {
showUser(gitHubServiceApi.getUserCoroutine(it).await())
} catch (e: Exception) {
showError(e)
}
delay(1000)
}
}
}
}.join()
}
inline fun <T> cost(block: () -> T): T {
val start = System.currentTimeMillis()
val result = block()
val cost = System.currentTimeMillis() - start
log("Time Cost: ${cost}ms")
return result
} | Kotlin/Kotlin-coroutineSample/src/main/java/com/bennyhuo/coroutines/sample/Ex11_RetrofitDemo.kt | 213201999 |
@file:Suppress("NOTHING_TO_INLINE")
package com.devrapid.kotlinshaver
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
inline infix fun (() -> Unit).iff(condition: Any?): Any? {
return when (condition) {
is Boolean -> if (condition) this() else null
is Float, Double, Int, Long -> this()
is String -> if (condition.isNotBlank()) this() else null
is Collection<*> -> if (condition.isNotEmpty()) this() else null
else -> condition?.let { this() }
}
}
inline fun Any?.isNull() = null == this
inline fun Any?.isNotNull() = null != this
@OptIn(ExperimentalContracts::class)
inline fun Any?.isNullExp(): Boolean {
contract {
returns(false) implies (this@isNullExp == null)
}
return null == this
}
@OptIn(ExperimentalContracts::class)
inline fun Any?.isNotNullExp(): Boolean {
contract {
returns(true) implies (this@isNotNullExp != null)
}
return null != this
}
| kotlinshaver/src/main/java/com/devrapid/kotlinshaver/Kits.kt | 3304967277 |
package de.saschahlusiak.freebloks.network.message
import de.saschahlusiak.freebloks.network.*
class MessageGameFinish : Message(MessageType.GameFinish) {
override fun equals(other: Any?) = other is MessageGameFinish
override fun hashCode() = 0
} | game/src/main/java/de/saschahlusiak/freebloks/network/message/MessageGameFinish.kt | 3656801319 |
package org.mariotaku.ktextension
import java.io.InputStream
import java.io.OutputStream
import java.nio.charset.Charset
import java.util.*
/**
* Created by mariotaku on 2016/12/7.
*/
fun InputStream.toString(charset: Charset, close: Boolean = false): String {
val r = bufferedReader(charset)
if (close) return r.use { it.readText() }
return r.readText()
}
fun OutputStream.writeLine(string: String = "", charset: Charset = Charset.defaultCharset(),
crlf: Boolean = false) {
write(string.toByteArray(charset))
if (crlf) {
write("\r\n".toByteArray(charset))
} else {
write("\n".toByteArray(charset))
}
}
fun InputStream.expectLine(string: String = "", charset: Charset = Charset.defaultCharset(),
crlf: Boolean = false): Boolean {
if (!expectBytes(string.toByteArray(charset))) return false
if (crlf) {
if (!expectBytes("\r\n".toByteArray(charset))) return false
} else {
if (!expectBytes("\n".toByteArray(charset))) return false
}
return true
}
fun InputStream.expectBytes(bytes: ByteArray): Boolean {
val readBytes = ByteArray(bytes.size)
read(readBytes)
return Arrays.equals(readBytes, bytes)
} | twittnuker/src/main/kotlin/org/mariotaku/ktextension/StreamExtensions.kt | 4114629249 |
package glimpse.android.gles
import android.graphics.BitmapFactory
import android.opengl.GLES20
import android.opengl.GLUtils
import glimpse.Color
import glimpse.android.gles.delegates.EnableDisableDelegate
import glimpse.gles.*
import glimpse.gles.GLES
import glimpse.gles.delegates.EnumPairSetAndRememberDelegate
import glimpse.gles.delegates.EnumSetAndRememberDelegate
import glimpse.gles.delegates.SetAndRememberDelegate
import glimpse.shaders.ProgramHandle
import glimpse.shaders.ShaderHandle
import glimpse.shaders.ShaderType
import glimpse.textures.TextureHandle
import glimpse.textures.TextureMagnificationFilter
import glimpse.textures.TextureMinificationFilter
import glimpse.textures.TextureWrapping
import java.io.InputStream
import java.nio.Buffer
import java.nio.FloatBuffer
import java.nio.IntBuffer
/**
* Android implementation of GLES facade.
*/
object GLES : GLES {
override var viewport: Viewport by SetAndRememberDelegate(Viewport(1, 1)) {
GLES20.glViewport(0, 0, it.width, it.height)
}
override var clearColor: Color by SetAndRememberDelegate(Color.Companion.BLACK) {
GLES20.glClearColor(it.red, it.green, it.blue, it.alpha)
}
override var clearDepth: Float by SetAndRememberDelegate(1f) {
GLES20.glClearDepthf(it)
}
override var isDepthTest: Boolean by EnableDisableDelegate(GLES20.GL_DEPTH_TEST)
override var depthTestFunction: DepthTestFunction by EnumSetAndRememberDelegate(DepthTestFunction.LESS, depthTestFunctionMapping) {
GLES20.glDepthFunc(it)
}
override var isBlend: Boolean by EnableDisableDelegate(GLES20.GL_BLEND)
override var blendFunction: Pair<BlendFactor, BlendFactor> by EnumPairSetAndRememberDelegate(BlendFactor.ZERO to BlendFactor.ONE, blendFactorMapping) {
GLES20.glBlendFunc(it.first, it.second)
}
override var isCullFace: Boolean by EnableDisableDelegate(GLES20.GL_CULL_FACE)
override var cullFaceMode: CullFaceMode by EnumSetAndRememberDelegate(CullFaceMode.BACK, cullFaceModeMapping) {
GLES20.glCullFace(it)
}
override fun clearDepthBuffer() {
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT)
}
override fun clearColorBuffer() {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
}
override fun createShader(shaderType: ShaderType) =
ShaderHandle(GLES20.glCreateShader(shaderTypeMapping[shaderType]!!))
override fun compileShader(shaderHandle: ShaderHandle, source: String) {
GLES20.glShaderSource(shaderHandle.value, source)
GLES20.glCompileShader(shaderHandle.value)
}
override fun deleteShader(shaderHandle: ShaderHandle) {
GLES20.glDeleteShader(shaderHandle.value)
}
override fun getShaderCompileStatus(shaderHandle: ShaderHandle) =
getShaderProperty(shaderHandle, GLES20.GL_COMPILE_STATUS) == GLES20.GL_TRUE
private fun getShaderProperty(shaderHandle: ShaderHandle, property: Int): Int {
val result = IntBuffer.allocate(1)
GLES20.glGetShaderiv(shaderHandle.value, property, result)
return result[0]
}
override fun getShaderLog(shaderHandle: ShaderHandle): String =
GLES20.glGetShaderInfoLog(shaderHandle.value)
override fun createProgram() =
ProgramHandle(GLES20.glCreateProgram())
override fun attachShader(programHandle: ProgramHandle, shaderHandle: ShaderHandle) {
GLES20.glAttachShader(programHandle.value, shaderHandle.value)
}
override fun linkProgram(programHandle: ProgramHandle) {
GLES20.glLinkProgram(programHandle.value)
}
override fun useProgram(programHandle: ProgramHandle) {
GLES20.glUseProgram(programHandle.value)
}
override fun deleteProgram(programHandle: ProgramHandle) {
GLES20.glDeleteProgram(programHandle.value)
}
override fun getProgramLinkStatus(programHandle: ProgramHandle) =
getProgramProperty(programHandle, GLES20.GL_LINK_STATUS) == GLES20.GL_TRUE
private fun getProgramProperty(programHandle: ProgramHandle, property: Int): Int {
val result = IntBuffer.allocate(1)
GLES20.glGetProgramiv(programHandle.value, property, result)
return result[0]
}
override fun getProgramLog(programHandle: ProgramHandle): String =
GLES20.glGetProgramInfoLog(programHandle.value)
override fun getUniformLocation(handle: ProgramHandle, name: String) =
UniformLocation(GLES20.glGetUniformLocation(handle.value, name))
override fun getAttributeLocation(handle: ProgramHandle, name: String) =
AttributeLocation(GLES20.glGetAttribLocation(handle.value, name))
override fun uniformFloat(location: UniformLocation, float: Float) {
GLES20.glUniform1f(location.value, float)
}
override fun uniformFloats(location: UniformLocation, floats: FloatArray) {
GLES20.glUniform1fv(location.value, floats.size, floats, 0)
}
override fun uniformInt(location: UniformLocation, int: Int) {
GLES20.glUniform1i(location.value, int)
}
override fun uniformInts(location: UniformLocation, ints: IntArray) {
GLES20.glUniform1iv(location.value, ints.size, ints, 0)
}
override fun uniformMatrix16f(location: UniformLocation, _16f: Array<Float>) {
GLES20.glUniformMatrix4fv(location.value, 1, false, _16f.toFloatArray(), 0)
}
override fun uniform4f(location: UniformLocation, _4f: Array<Float>, count: Int) {
GLES20.glUniform4fv(location.value, count, _4f.toFloatArray(), 0)
}
override fun createAttributeFloatArray(location: AttributeLocation, buffer: FloatBuffer, vectorSize: Int) =
createAttributeArray(location, buffer, vectorSize, GLES20.GL_FLOAT, 4)
override fun createAttributeIntArray(location: AttributeLocation, buffer: IntBuffer, vectorSize: Int) =
createAttributeArray(location, buffer, vectorSize, GLES20.GL_INT, 4)
private fun createAttributeArray(location: AttributeLocation, buffer: Buffer, vectorSize: Int, type: Int, typeSize: Int): BufferHandle {
buffer.rewind()
val handles = IntArray(1)
GLES20.glGenBuffers(1, handles, 0)
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, handles[0])
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, buffer.limit() * typeSize, buffer, GLES20.GL_STATIC_DRAW)
GLES20.glVertexAttribPointer(location.value, vectorSize, type, false, 0, 0)
return BufferHandle(handles[0])
}
override fun deleteAttributeArray(handle: BufferHandle) {
GLES20.glDeleteBuffers(1, arrayOf(handle.value).toIntArray(), 0)
}
override fun enableAttributeArray(location: AttributeLocation) {
GLES20.glEnableVertexAttribArray(location.value)
}
override fun disableAttributeArray(location: AttributeLocation) {
GLES20.glDisableVertexAttribArray(location.value)
}
override var textureMinificationFilter: TextureMinificationFilter
by EnumSetAndRememberDelegate(TextureMinificationFilter.NEAREST_MIPMAP_LINEAR, textureMinificationFilterMapping) {
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, it)
}
override var textureMagnificationFilter: TextureMagnificationFilter
by EnumSetAndRememberDelegate(TextureMagnificationFilter.LINEAR, textureMagnificationFilterMapping) {
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, it)
}
override var textureWrapping: Pair<TextureWrapping, TextureWrapping>
by EnumPairSetAndRememberDelegate(TextureWrapping.REPEAT to TextureWrapping.REPEAT, textureWrappingMapping) {
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, it.first)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, it.second)
}
override fun generateTextures(count: Int): Array<TextureHandle> {
val handles = IntArray(count)
GLES20.glGenTextures(count, handles, 0)
return handles.map { TextureHandle(it) }.toTypedArray()
}
override fun deleteTextures(count: Int, handles: Array<TextureHandle>) {
GLES20.glDeleteTextures(count, handles.map { it.value }.toIntArray(), 0)
}
override fun bindTexture2D(handle: TextureHandle) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, handle.value)
}
override fun textureImage2D(inputStream: InputStream, fileName: String, withMipmap: Boolean) {
val bitmap = BitmapFactory.decodeStream(inputStream)
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, bitmap, 0)
if (withMipmap) GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D)
bitmap.recycle()
}
override fun activeTexture(index: Int) {
require(index in 0..31) { "Texture index out of bounds: $index" }
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + index)
}
override fun drawTriangles(verticesCount: Int) {
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, verticesCount)
}
}
| android/src/main/kotlin/glimpse/android/gles/GLES.kt | 2887352145 |
import java.util.*
/*
* 參照某天跟冰封提起的方法嘗試實現的一個解釋器
* 用VSCode寫的...鬼知道能不能用(攤手
*/
// parser str to list, kotlin version
/*
def parse_value(buffer):
if is_quote_by(buffer, '"'):
return String(parse_string(buffer[1:-1]))
s = ''.join(buffer)
if s.startswith("0x"):
return Number(int(s, 16))
if s.startswith("0b") and "." not in s:
return Number(int(s, 2))
if s.startswith("0o") and "." not in s:
return Number(int(s, 8))
try:
return Number(int(s))
except Exception: pass
try:
return Number(float(s))
except Exception: pass
return Symbol(s)
*/
class Reader<T>(val arr: Collection<T>): Iterable<T>, Iterator<T> {
override fun hasNext(): Boolean {
return index < length
}
override fun iterator(): Iterator<T> {
return this
}
val length = arr.size
var index = 0
override fun next(): T {
index += 1
if (index < length) {
return arr.elementAt(index)
} else {
throw IndexOutOfBoundsException()
}
}
fun next(n: Int): ArrayList<T> {
if (index < length) {
val r = ArrayList<T>(n)
var k = 0
for(i in index .. Math.min(index+n, length) - 1) {
r[k++] = arr.elementAt(i)
}
index += n
index = Math.min(index, length)
return r
} else {
throw IndexOutOfBoundsException()
}
}
}
class Parser() {
sealed class Token {
data class String(val value: kotlin.String) : Token()
data class Symbol(val value: kotlin.String) : Token()
data class Number(val value: kotlin.Number) : Token()
object OpenBracket : Token()
object CloseBracket : Token()
}
fun valueParser(buffer: StringBuilder): Token {
if (isQuoteBy(buffer, '"')) {
return stringParser(buffer.substring(1, buffer.length - 1))
}
val s = buffer.toString()
when (true) {
s.startsWith("0x") -> {
return Token.Number(Integer.valueOf(s, 16))
}
s.startsWith("0b") -> {
return Token.Number(Integer.valueOf(s, 2))
}
s.startsWith("0o") -> {
return Token.Number(Integer.valueOf(s, 8))
}
s[0].isDigit() -> {
return Token.Number(Integer.valueOf(s))
}
else -> {
return Token.Symbol(s)
}
}
}
fun stringParser(s: String): Token.String {
}
fun isQuoteBy(buffer: StringBuilder, c: Char): Boolean {
return buffer.length > 1 && buffer[0] == c && buffer[buffer.length - 1] == c
}
val FLAG_DEFAULT = 0
val FLAG_STRING = 1
val FLAG_ESCAPING_STRING = 2
val FLAG_COMMENT = 3
fun preProcess(expr: String): Stack<Token> {
}
fun parse(expr: String): Stack<Token> {
val res = Expr()
val last = Stack<Expr>()
val R = Reader(preProcess(expr))
for(i in R) {
when(i) {
is Token.OpenBracket -> {
val new = Stack<Token>()
last.peek().push(new)
last.push(new)
}
}
}
if type(obj) is str:
if obj in "([{":
new = []
last[-1].append(new)
last.append(new)
elif obj in ")]}":
l = last.pop()
else:
last[-1].append(obj)
else:
last[-1].append(obj)
return res
}
}
| kotlin/src/me/mnahong2112/kf/Parser.kt | 1251882748 |
package abi44_0_0.expo.modules.localization
import android.text.TextUtils
import java.util.*
import kotlin.collections.ArrayList
val USES_IMPERIAL = listOf("US", "LR", "MM")
val iSOCurrencyCodes: ArrayList<String> by lazy {
Currency.getAvailableCurrencies().map { it.currencyCode as String } as ArrayList<String>
}
fun getLocaleNames(locales: ArrayList<Locale>) = locales.map { it.toLanguageTag() } as ArrayList
fun getCountryCode(locale: Locale): String? {
return runCatching {
val country = locale.country
if (TextUtils.isEmpty(country)) null else country
}.getOrNull()
}
fun getSystemProperty(key: String): String {
return runCatching {
val systemProperties = Class.forName("android.os.SystemProperties")
val get = systemProperties.getMethod("get", String::class.java)
get.invoke(systemProperties, key) as String
}.getOrNull() ?: ""
}
fun getCurrencyCode(locale: Locale): String? {
return runCatching {
val currency = Currency.getInstance(locale)
currency?.currencyCode
}.getOrNull()
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/localization/LocalizationUtils.kt | 1714454901 |
package com.vimeo.networking2.params
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Represents the required data for a LinkedIn post.
*
* @param pageId The LinkedIn page identifier that the video will be posted to.
* @param title The title of the post as it will appear on LinkedIn.
* @param description The description of the post as it will appear on LinkedIn.
*/
@JsonClass(generateAdapter = true)
data class PublishToLinkedInPost(
@Json(name = "page_id")
val pageId: Int,
@Json(name = "title")
val title: String,
@Json(name = "description")
val description: String
)
| models/src/main/java/com/vimeo/networking2/params/PublishToLinkedInPost.kt | 531721323 |
package com.xenoage.utils.io
/**
* System independent interface for files.
* For example, there may be implementations for the JVM, Android or JavaScript.
*
* All methods may throw an [IoException].
*/
interface OutputStream {
/**
* Writes the given text.
* Use this method only for text streams.
*/
fun write(text: String)
/**
* Writes the given line of text, terminated by '\n'.
* Use this method only for text streams.
*/
fun writeLine(line: String)
/**
* Writes the specified byte to this output stream. Only the eight low-order
* bits of the given value are used.
*/
fun write(b: Int)
/* TODO: needed ?
/**
* Writes the given bytes to this output stream.
*/
fun write(b: ByteArray)
/**
* Writes [len] bytes from the given byte array starting at
* offset [off] to this output stream.
*/
fun write(b: ByteArray, off: Int, len: Int)
*/
/**
* Closes this input stream and releases any system resources associated
* with the stream.
*/
fun close()
}
| utils-kotlin/src/com/xenoage/utils/io/OutputStream.kt | 2894820140 |
package br.com.bumblebee.api.congressman.repository.model
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.util.*
@Document(collection = "congressman")
data class Congressman(
@Id val id: Int,
val name: String,
val cpf: String,
val gender: String,
val birthday: Date,
val deathDate: Date?,
val schooling: String?,
val socialMedia: List<String>,
val websiteUrl: String?,
val birthState: String?,
val birthCity: String,
val status: List<CongressmanStatus>,
val office: Office
)
data class CongressmanStatus(
@Id val id: Int,
val electionName: String,
val electionCondition: String,
val date: Date,
val legislatureId: Int,
val partyAcronym: String,
val stateAcronym: String,
val status: String,
val photoUrl: String,
val description: String?
)
data class Office(
val floor: String?,
val email: String,
val name: String,
val building: String,
val room: String,
val phone: String
)
| src/main/kotlin/br/com/bumblebee/api/congressman/repository/model/Congressman.kt | 171950391 |
package com.prokkypew.asciipanelview
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.prokkypew.asciipanelview.AsciiPanelView.ColoredChar
import com.prokkypew.asciipanelview.AsciiPanelView.OnCharClickedListener
/**
* An implementation of terminal view for old-school games.
* Initially ported from JPanel AsciiPanel https://github.com/trystan/AsciiPanel to Android View
*
* @author Alexander Roman
*
* @property chars matrix of [ColoredChar] to be drawn on the panel
* @property panelWidth width of panel in chars
* @property panelHeight height of panel in chars
* @property charColor color of chars to be drawn if not specified
* @property bgColor color of char background to be drawn if not specified
* @property cursorX position X of cursor to draw next char at
* @property cursorY position Y of cursor to draw next char at
* @property fontFamily font file name to use for drawing chars
* @property onCharClickedListener interface of [OnCharClickedListener] to be called on panel char click
*/
class AsciiPanelView : View {
companion object {
/**
* Default panel width in chars = 64
*/
const val DEFAULT_PANEL_WIDTH: Int = 64
/**
* Default panel height in chars = 27
*/
const val DEFAULT_PANEL_HEIGHT: Int = 27
/**
* Default char color = [Color.BLACK]
*/
const val DEFAULT_CHAR_COLOR: Int = Color.BLACK
/**
* Default char background color = [Color.WHITE]
*/
const val DEFAULT_BG_COLOR: Int = Color.WHITE
/**
* Default font
*/
const val DEFAULT_FONT: String = "font.ttf"
private const val CLICK_ACTION_THRESHOLD: Int = 200
}
private var tileWidth: Float = 0f
private var tileHeight: Float = 0f
private var textPaint: Paint = Paint()
private var textBgPaint: Paint = Paint()
private var widthCompensation: Float = 0f
private var lastTouchDown: Long = 0
lateinit var chars: Array<Array<ColoredChar>>
var onCharClickedListener: OnCharClickedListener? = null
var panelWidth: Int = DEFAULT_PANEL_WIDTH
var panelHeight: Int = DEFAULT_PANEL_HEIGHT
var charColor: Int = DEFAULT_CHAR_COLOR
var bgColor: Int = DEFAULT_BG_COLOR
var cursorX: Int = 0
var cursorY: Int = 0
var fontFamily: String = DEFAULT_FONT
/**
*@constructor Default View constructors by context
*/
constructor(context: Context) : super(context) {
init()
}
/**
*@constructor Default View constructors by context and attributes
*/
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
readAttributes(attrs)
init()
}
/**
*@constructor Default View constructors by context, attributes and default style
*/
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
readAttributes(attrs)
init()
}
private fun readAttributes(attrs: AttributeSet) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.AsciiPanelView)
try {
panelWidth = ta.getInt(R.styleable.AsciiPanelView_panelWidth, DEFAULT_PANEL_WIDTH)
panelHeight = ta.getInt(R.styleable.AsciiPanelView_panelHeight, DEFAULT_PANEL_HEIGHT)
charColor = ta.getColor(R.styleable.AsciiPanelView_defaultCharColor, DEFAULT_CHAR_COLOR)
bgColor = ta.getColor(R.styleable.AsciiPanelView_defaultBackgroundColor, DEFAULT_BG_COLOR)
if (ta.hasValue(R.styleable.AsciiPanelView_fontFamily))
fontFamily = ta.getString(R.styleable.AsciiPanelView_fontFamily)
} finally {
ta.recycle()
}
}
private fun init() {
chars = Array(panelWidth) { Array(panelHeight) { ColoredChar(' ', charColor, bgColor) } }
val font = Typeface.create(Typeface.createFromAsset(context.assets, fontFamily), Typeface.BOLD)
textPaint.typeface = font
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> lastTouchDown = System.currentTimeMillis()
MotionEvent.ACTION_UP -> if (System.currentTimeMillis() - lastTouchDown < CLICK_ACTION_THRESHOLD) {
val x = event.x.div(tileWidth).toInt()
val y = event.y.div(tileHeight).toInt()
onCharClickedListener?.onCharClicked(x, y, chars[x][y])
}
}
return true
}
override fun onSizeChanged(xNew: Int, yNew: Int, xOld: Int, yOld: Int) {
super.onSizeChanged(xNew, yNew, xOld, yOld)
tileWidth = xNew.toFloat() / panelWidth.toFloat()
tileHeight = (yNew.toFloat()) / panelHeight.toFloat()
textPaint.textSize = tileHeight
val bounds = Rect()
textPaint.getTextBounds("W", 0, 1, bounds)
widthCompensation = (tileWidth - bounds.width()) / 2
}
/**
* @exclude
*/
override fun onDraw(canvas: Canvas) {
for (w in 0 until panelWidth) {
val posX = tileWidth * w
for (h in 0 until panelHeight) {
textBgPaint.color = chars[w][h].bgColor
canvas.drawRect(posX, tileHeight * h, posX + tileWidth, tileHeight * h + tileHeight, textBgPaint)
}
}
for (w in 0 until panelWidth) {
val posX = tileWidth * w
for (h in 0 until panelHeight) {
textPaint.color = chars[w][h].charColor
val posY = tileHeight * (h + 1) - textPaint.descent()
canvas.drawText(chars[w][h].char.toString(), posX + widthCompensation, posY, textPaint)
}
}
}
/**
* Sets the distance from the left new text will be written to.
* @param cursorX the distance from the left new text should be written to
* @return this for convenient chaining of method calls
*/
fun setCursorPosX(cursorX: Int): AsciiPanelView {
if (cursorX < 0 || cursorX >= panelWidth) throw IllegalArgumentException("cursorX $cursorX must be in range [0,$panelWidth).")
this.cursorX = cursorX
return this
}
/**
* Sets the distance from the top new text will be written to.
* @param cursorY the distance from the top new text should be written to
* @return this for convenient chaining of method calls
*/
fun setCursorPosY(cursorY: Int): AsciiPanelView {
if (cursorY < 0 || cursorY >= panelHeight) throw IllegalArgumentException("cursorY $cursorY must be in range [0,$panelHeight).")
this.cursorY = cursorY
return this
}
/**
* Sets the x and y position of where new text will be written to. The origin (0,0) is the upper left corner.
* @param x the distance from the left new text should be written to
* @param y the distance from the top new text should be written to
* @return this for convenient chaining of method calls
*/
fun setCursorPosition(x: Int, y: Int): AsciiPanelView {
setCursorPosX(x)
setCursorPosY(y)
return this
}
/**
* Write a character to the cursor's position.
* This updates the cursor's position.
* @param character the character to write
* @return this for convenient chaining of method calls
*/
fun writeChar(character: Char): AsciiPanelView {
return writeChar(character, cursorX, cursorY, charColor, bgColor)
}
/**
* Write a character to the cursor's position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param character the character to write
* @param charColor the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeChar(character: Char, charColor: Int): AsciiPanelView {
return writeChar(character, cursorX, cursorY, charColor, bgColor)
}
/**
* Write a character to the cursor's position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param character the character to write
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeCharWithColor(character: Char, charColor: Int, bgColor: Int): AsciiPanelView {
return writeChar(character, cursorX, cursorY, charColor, bgColor)
}
/**
* Write a character to the specified position.
* This updates the cursor's position.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @return this for convenient chaining of method calls
*/
fun writeCharWithPos(character: Char, x: Int, y: Int): AsciiPanelView {
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
return writeChar(character, x, y, charColor, bgColor)
}
/**
* Write a character to the specified position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param charColor the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeChar(character: Char, x: Int, y: Int, charColor: Int): AsciiPanelView {
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
return writeChar(character, x, y, charColor, bgColor)
}
/**
* Write a character to the specified position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeChar(character: Char, x: Int, y: Int, charColor: Int?, bgColor: Int?): AsciiPanelView {
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
var gColor = charColor
var bColor = bgColor
if (gColor == null) gColor = this.charColor
if (bColor == null) bColor = this.bgColor
chars[x][y] = ColoredChar(character, gColor, bColor)
cursorX = x + 1
cursorY = y
invalidate()
return this
}
/**
* Write a string to the cursor's position.
* This updates the cursor's position.
* @param string the string to write
* @return this for convenient chaining of method calls
*/
fun writeString(string: String): AsciiPanelView {
if (cursorX + string.length > panelWidth) throw IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length) + " must be less than " + panelWidth + ".")
return writeString(string, cursorX, cursorY, charColor, bgColor)
}
/**
* Write a string to the cursor's position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param string the string to write
* @param charColor the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeString(string: String, charColor: Int): AsciiPanelView {
if (cursorX + string.length > panelWidth) throw IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length) + " must be less than " + panelWidth + ".")
return writeString(string, cursorX, cursorY, charColor, bgColor)
}
/**
* Write a string to the cursor's position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param string the string to write
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeStringWithColor(string: String, charColor: Int, bgColor: Int): AsciiPanelView {
if (cursorX + string.length > panelWidth) throw IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length) + " must be less than " + panelWidth + ".")
return writeString(string, cursorX, cursorY, charColor, bgColor)
}
/**
* Write a string to the specified position.
* This updates the cursor's position.
* @param string the string to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @return this for convenient chaining of method calls
*/
fun writeStringWithPos(string: String, x: Int, y: Int): AsciiPanelView {
if (x + string.length > panelWidth) throw IllegalArgumentException("x + string.length() " + (x + string.length) + " must be less than " + panelWidth + ".")
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
return writeString(string, x, y, charColor, bgColor)
}
/**
* Write a string to the specified position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param string the string to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param charColor the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeString(string: String, x: Int, y: Int, charColor: Int): AsciiPanelView {
if (x + string.length > panelWidth) throw IllegalArgumentException("x + string.length() " + (x + string.length) + " must be less than " + panelWidth + ".")
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
return writeString(string, x, y, charColor, bgColor)
}
/**
* Write a string to the specified position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param string the string to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeString(string: String, x: Int, y: Int, charColor: Int?, bgColor: Int?): AsciiPanelView {
if (x + string.length > panelWidth) throw IllegalArgumentException("x + string.length() " + (x + string.length) + " must be less than " + panelWidth + ".")
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth).")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight).")
var gColor = charColor
var bColor = bgColor
if (gColor == null) gColor = this.charColor
if (bColor == null) bColor = this.bgColor
for (i in 0 until string.length) {
writeChar(string[i], x + i, y, gColor, bColor)
}
return this
}
/**
* Clear the entire screen to whatever the default background color is.
* @return this for convenient chaining of method calls
*/
fun clear(): AsciiPanelView {
return clearRect(' ', 0, 0, panelWidth, panelHeight, charColor, bgColor)
}
/**
* Clear the entire screen with the specified character and whatever the default foreground and background colors are.
* @param character the character to write
* @return this for convenient chaining of method calls
*/
fun clear(character: Char): AsciiPanelView {
return clearRect(character, 0, 0, panelWidth, panelHeight, charColor, bgColor)
}
/**
* Clear the entire screen with the specified character and whatever the specified foreground and background colors are.
* @param character the character to write
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun clear(character: Char, charColor: Int, bgColor: Int): AsciiPanelView {
return clearRect(character, 0, 0, panelWidth, panelHeight, charColor, bgColor)
}
/**
* Clear the section of the screen with the specified character and whatever the default foreground and background colors are.
* The cursor position will not be modified.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param width the height of the section to clear
* @param height the width of the section to clear
* @return this for convenient chaining of method calls
*/
fun clearRect(character: Char, x: Int, y: Int, width: Int, height: Int): AsciiPanelView {
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth).")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight).")
if (width < 1) throw IllegalArgumentException("width $width must be greater than 0.")
if (height < 1) throw IllegalArgumentException("height $height must be greater than 0.")
if (x + width > panelWidth) throw IllegalArgumentException("x + width " + (x + width) + " must be less than " + (panelWidth + 1) + ".")
if (y + height > panelHeight) throw IllegalArgumentException("y + height " + (y + height) + " must be less than " + (panelHeight + 1) + ".")
return clearRect(character, x, y, width, height, charColor, bgColor)
}
/**
* Clear the section of the screen with the specified character and whatever the specified foreground and background colors are.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param width the height of the section to clear
* @param height the width of the section to clear
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun clearRect(character: Char, x: Int, y: Int, width: Int, height: Int, charColor: Int, bgColor: Int): AsciiPanelView {
if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
if (width < 1) throw IllegalArgumentException("width $width must be greater than 0.")
if (height < 1) throw IllegalArgumentException("height $height must be greater than 0.")
if (x + width > panelWidth) throw IllegalArgumentException("x + width " + (x + width) + " must be less than " + (panelWidth + 1) + ".")
if (y + height > panelHeight) throw IllegalArgumentException("y + height " + (y + height) + " must be less than " + (panelHeight + 1) + ".")
val originalCursorX = cursorX
val originalCursorY = cursorY
for (xo in x until x + width) {
for (yo in y until y + height) {
writeChar(character, xo, yo, charColor, bgColor)
}
}
cursorX = originalCursorX
cursorY = originalCursorY
return this
}
/**
* Write a string to the center of the panel at the specified y position.
* This updates the cursor's position.
* @param string the string to write
* @param y the distance from the top to begin writing from
* @return this for convenient chaining of method calls
*/
fun writeCenter(string: String, y: Int): AsciiPanelView {
if (string.length > panelWidth) throw IllegalArgumentException("string.length() " + string.length + " must be less than " + panelWidth + ".")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
val x = (panelWidth - string.length) / 2
return writeString(string, x, y, charColor, bgColor)
}
/**
* Write a string to the center of the panel at the specified y position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param string the string to write
* @param y the distance from the top to begin writing from
* @param charColor the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeCenter(string: String, y: Int, charColor: Int): AsciiPanelView {
if (string.length > panelWidth) throw IllegalArgumentException("string.length() " + string.length + " must be less than " + panelWidth + ".")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)")
val x = (panelWidth - string.length) / 2
return writeString(string, x, y, charColor, bgColor)
}
/**
* Write a string to the center of the panel at the specified y position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param string the string to write
* @param y the distance from the top to begin writing from
* @param charColor the foreground color or null to use the default
* @param bgColor the background color or null to use the default
* @return this for convenient chaining of method calls
*/
fun writeCenter(string: String, y: Int, charColor: Int?, bgColor: Int?): AsciiPanelView {
if (string.length > panelWidth) throw IllegalArgumentException("string.length() " + string.length + " must be less than " + panelWidth + ".")
if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight).")
var gColor = charColor
var bColor = bgColor
val x = (panelWidth - string.length) / 2
if (gColor == null) gColor = this.charColor
if (bColor == null) bColor = this.bgColor
for (i in 0 until string.length) {
writeChar(string[i], x + i, y, gColor, bColor)
}
return this
}
/**
* Interface to be called on panel character click
*/
interface OnCharClickedListener {
/**
* Callback, which is called when panel is clicked
* @param x position of char clicked
* @param y position of char clicked
* @param char object of [ColoredChar] clicked
*/
fun onCharClicked(x: Int?, y: Int?, char: ColoredChar)
}
/**
* Object for chars to print on the panel
* @property char char to print
* @property charColor color of the char
* @property bgColor color of background of the char
*/
class ColoredChar(var char: Char, var charColor: Int, var bgColor: Int)
} | asciipanelview/src/main/java/com/prokkypew/asciipanelview/AsciiPanelView.kt | 3033250462 |
package com.twitter.meil_mitu.twitter4hk.aclog.converter.api
import com.twitter.meil_mitu.twitter4hk.aclog.converter.IAclogStatusConverter
interface ITweetsConverter<TAclogStatus> : IAclogStatusConverter<TAclogStatus> {
} | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/aclog/converter/api/ITweetsConverter.kt | 2063712983 |
/*
* Copyright 2018 Priyank Vasa
* 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.pvryan.easycrypt.randomorg
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
/**
* Interface for Retrofit api calls to api.random.org
*/
internal interface RandomOrgApis {
/**
* Request a new password to api.random.org
*
* @param body of class [RandomOrgRequest] to send with request
*/
@POST("json-rpc/1/invoke")
fun request(@Body body: RandomOrgRequest): Call<RandomOrgResponse>
companion object {
const val BASE_URL = "https://api.random.org/"
}
}
| easycrypt/src/main/java/com/pvryan/easycrypt/randomorg/RandomOrgApis.kt | 2879952936 |
package com.exyui.android.debugbottle.components.crash
import android.util.Log
import com.exyui.android.debugbottle.components.okhttp.HttpBlock
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by yuriel on 9/13/16.
*/
internal data class CrashBlock(
val time: String = "",
val threadName: String = "",
val threadId: String = "",
val threadPriority: String = "",
val threadGroup: String = "",
val message: String = "",
val cause: String = "",
val stacktrace: String = "",
val file: File? = null) {
private val threadSb = StringBuilder()
private val stacktraceSb = StringBuilder()
val threadString: String
get() = threadSb.toString()
val stacktraceString: String
get() = stacktraceSb.toString()
init {
flushString()
}
private fun flushString() {
threadSb + KEY_TIME + KV + time + SEPARATOR
threadSb + KEY_THREAD_NAME + KV + threadName + SEPARATOR
threadSb + KEY_THREAD_ID + KV + threadId + SEPARATOR
threadSb + KEY_THREAD_PRIORITY + KV + threadPriority + SEPARATOR
threadSb + KEY_THREAD_GROUP + KV + threadGroup + SEPARATOR
stacktraceSb + KEY_MESSAGE + KV + message + SEPARATOR
if (cause.isNotEmpty()) {
stacktraceSb + KEY_CAUSE + KV + cause + SEPARATOR
}
stacktraceSb + KEY_STACKTRACE + KV + stacktrace + SEPARATOR
}
private operator fun StringBuilder.plus(any: Any): StringBuilder = this.append(any)
override fun toString(): String {
return threadSb.toString() + stacktraceSb
}
companion object {
internal val TAG = "CrashBlock"
internal val NEW_INSTANCE = "newInstance: "
internal val SEPARATOR = "\r\n"
internal val KV = " = "
internal val KEY_TIME = "time"
internal val KEY_THREAD_NAME = "threadName"
internal val KEY_THREAD_ID = "threadId"
internal val KEY_THREAD_PRIORITY = "threadPriority"
internal val KEY_THREAD_GROUP = "threadGroup"
internal val KEY_MESSAGE = "message"
internal val KEY_CAUSE = "cause"
internal val KEY_STACKTRACE = "stacktrace"
private val TIME_FORMATTER = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.getDefault())
fun newInstance(thread: Thread, ex: Throwable): CrashBlock {
val writer = StringWriter()
val printer = PrintWriter(writer)
ex.printStackTrace(printer)
return CrashBlock(
time = TIME_FORMATTER.format(System.currentTimeMillis()),
threadId = "${thread.id}",
threadName = thread.name,
threadPriority = "${thread.priority}",
threadGroup = thread.threadGroup.name,
message = ex.message?: "",
cause = ex.cause?.message?: "",
stacktrace = writer.toString()
)
}
fun newInstance(file: File): CrashBlock {
var reader: BufferedReader? = null
var time: String = ""
var threadName: String = ""
var threadId: String = ""
var threadPriority: String = ""
var threadGroup: String = ""
var message: String = ""
var cause: String = ""
var stacktrace: String = ""
try {
val input = InputStreamReader(FileInputStream(file), "UTF-8")
reader = BufferedReader(input)
var line: String? = reader.readLine()
fun getStringInfo(): String {
if (null == line || null == reader)
return ""
val split = line!!.split(HttpBlock.KV.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (split.size > 1) {
val sb = StringBuilder(split[1])
sb/*.append(line!!.getValue())*/.append(HttpBlock.SEPARATOR)
line = reader!!.readLine()
// read until SEPARATOR appears
while (line != null) {
if (line != "") {
sb.append(line).append(HttpBlock.SEPARATOR)
} else {
break
}
line = reader!!.readLine()
}
return sb.toString()
} else
return ""
}
while(line != null) {
if (line!!.startsWith(KEY_TIME)) {
time = line!!.getValue()
} else if (line!!.startsWith(KEY_THREAD_NAME)) {
threadName = line!!.getValue()
} else if (line!!.startsWith(KEY_THREAD_ID)) {
threadId = line!!.getValue()
} else if (line!!.startsWith(KEY_THREAD_PRIORITY)) {
threadPriority = line!!.getValue()
} else if (line!!.startsWith(KEY_THREAD_GROUP)) {
threadGroup = line!!.getValue()
} else if (line!!.startsWith(KEY_MESSAGE)) {
message = line!!.getValue()
} else if (line!!.startsWith(KEY_CAUSE)) {
cause = line!!.getValue()
} else if (line!!.startsWith(KEY_STACKTRACE)) {
stacktrace = getStringInfo()
}
line = reader.readLine()
}
reader.close()
reader = null
} catch(e: Exception) {
Log.e(TAG, NEW_INSTANCE, e)
} finally {
try {
if (reader != null) {
reader.close()
}
} catch (e: Exception) {
Log.e(TAG, NEW_INSTANCE, e)
}
}
return CrashBlock(
time = time,
threadName = threadName,
threadId = threadId,
threadPriority = threadPriority,
threadGroup = threadGroup,
message = message,
cause = cause,
stacktrace = stacktrace,
file = file
)
}
private fun String.getValue(): String {
val kv = this.split(KV.toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
if (kv.size > 1) {
return kv[1]
} else {
return ""
}
}
}
} | components/src/main/kotlin/com/exyui/android/debugbottle/components/crash/CrashBlock.kt | 1940456885 |
/*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.os
interface ConsoleManager {
fun enableConsoleEscapeSequences()
fun enterRawMode(): AutoCloseable
}
| app/src/main/kotlin/batect/os/ConsoleManager.kt | 3597407381 |
package org.thoughtcrime.securesms.stories.my
import androidx.fragment.app.Fragment
import org.thoughtcrime.securesms.components.FragmentWrapperActivity
class MyStoriesActivity : FragmentWrapperActivity() {
override fun getFragment(): Fragment {
return MyStoriesFragment()
}
}
| app/src/main/java/org/thoughtcrime/securesms/stories/my/MyStoriesActivity.kt | 3386715004 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.protos
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.google.protobuf.ExtensionRegistryLite
import com.google.protobuf.InvalidProtocolBufferException
import com.google.protobuf.MessageLite
import java.io.InputStream
import java.io.OutputStream
/** Serializer for using DataStore with protos. */
internal class ProtoSerializer<T : MessageLite>(
/** The default proto of this type, obtained via {@code T.getDefaultInstance()} */
override val defaultValue: T,
/**
* Set the extensionRegistryLite to use when deserializing T. If no extension registry is
* necessary, use {@code ExtensionRegistryLite.getEmptyRegistry()}.
*/
private val extensionRegistryLite: ExtensionRegistryLite
) : Serializer<T> {
@Suppress("UNCHECKED_CAST")
override suspend fun readFrom(input: InputStream): T {
try {
return defaultValue.parserForType.parseFrom(input, extensionRegistryLite) as T
} catch (invalidProtocolBufferException: InvalidProtocolBufferException) {
throw CorruptionException(
"Cannot read proto.", invalidProtocolBufferException
)
}
}
override suspend fun writeTo(t: T, output: OutputStream) {
t.writeTo(output)
}
} | datastore/datastore-proto/src/main/java/androidx/datastore/protos/ProtoSerializer.kt | 2702266346 |
package org.jetbrains.ide
import com.intellij.testFramework.DisposeModulesRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.TemporaryDirectory
import io.netty.handler.codec.http.HttpResponseStatus
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.rules.Timeout
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.TimeUnit
internal abstract class BuiltInServerTestCase {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
}
protected val tempDirManager = TemporaryDirectory()
protected val manager = TestManager(projectRule, tempDirManager)
private val ruleChain = RuleChain(
tempDirManager,
Timeout(60, TimeUnit.SECONDS),
manager,
DisposeModulesRule(projectRule))
@Rule fun getChain() = ruleChain
protected open val urlPathPrefix = ""
protected fun doTest(filePath: String? = manager.filePath, additionalCheck: ((connection: HttpURLConnection) -> Unit)? = null) {
val serviceUrl = "http://localhost:${BuiltInServerManager.getInstance().port}$urlPathPrefix"
var url = serviceUrl + (if (filePath == null) "" else ("/$filePath"))
val line = manager.annotation?.line ?: -1
if (line != -1) {
url += ":$line"
}
val column = manager.annotation?.column ?: -1
if (column != -1) {
url += ":$column"
}
val connection = URL(url).openConnection() as HttpURLConnection
val expectedStatus = HttpResponseStatus.valueOf(manager.annotation?.status ?: 200)
assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus)
check(serviceUrl, expectedStatus)
if (additionalCheck != null) {
additionalCheck(connection)
}
}
protected open fun check(serviceUrl: String, expectedStatus: HttpResponseStatus) {
}
} | platform/built-in-server/testSrc/BuiltInServerTestCase.kt | 2795497772 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val NV_non_square_matrices = "NVNonSquareMatrices".nativeClassGLES("NV_non_square_matrices", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension adds support for non-square matrix variables in GLSL shaders.
Requires ${GLES20.core}.
"""
IntConstant(
"Returned by GetActiveAttrib and GetActiveUniform.",
"FLOAT_MAT2x3_NV"..0x8B65,
"FLOAT_MAT2x4_NV"..0x8B66,
"FLOAT_MAT3x2_NV"..0x8B67,
"FLOAT_MAT3x4_NV"..0x8B68,
"FLOAT_MAT4x2_NV"..0x8B69,
"FLOAT_MAT4x3_NV"..0x8B6A
)
void(
"UniformMatrix2x3fvNV",
"",
GLint.IN("location", ""),
AutoSize(2 x 3, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix3x2fvNV",
"",
GLint.IN("location", ""),
AutoSize(3 x 2, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix2x4fvNV",
"",
GLint.IN("location", ""),
AutoSize(2 x 4, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix4x2fvNV",
"",
GLint.IN("location", ""),
AutoSize(4 x 2, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix3x4fvNV",
"",
GLint.IN("location", ""),
AutoSize(3 x 4, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix4x3fvNV",
"",
GLint.IN("location", ""),
AutoSize(4 x 3, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
} | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/NV_non_square_matrices.kt | 1471326252 |
package org.jetbrains.protocolReader
import org.jetbrains.jsonProtocol.JsonObjectBased
import java.lang.reflect.Method
import java.util.*
internal val FIELD_PREFIX = '_'
internal val NAME_VAR_NAME = "_n"
private fun assignField(out: TextOutput, fieldName: String) = out.append(FIELD_PREFIX).append(fieldName).append(" = ")
internal class TypeRef<T>(val typeClass: Class<T>) {
var type: TypeWriter<T>? = null
}
internal class TypeWriter<T>(val typeClass: Class<T>, jsonSuperClass: TypeRef<*>?, private val volatileFields: List<VolatileFieldBinding>, private val methodHandlerMap: LinkedHashMap<Method, MethodHandler>,
/** Loaders that should read values and save them in field array on parse time. */
private val fieldLoaders: List<FieldLoader>, private val hasLazyFields: Boolean) {
/** Subtype aspects of the type or null */
val subtypeAspect = if (jsonSuperClass == null) null else ExistingSubtypeAspect(jsonSuperClass)
fun writeInstantiateCode(scope: ClassScope, out: TextOutput) {
writeInstantiateCode(scope, false, out)
}
fun writeInstantiateCode(scope: ClassScope, deferredReading: Boolean, out: TextOutput) {
val className = scope.getTypeImplReference(this)
if (deferredReading || subtypeAspect == null) {
out.append(className)
}
else {
subtypeAspect.writeInstantiateCode(className, out)
}
}
fun write(fileScope: FileScope) {
val out = fileScope.output
val valueImplClassName = fileScope.getTypeImplShortName(this)
out.append("private class ").append(valueImplClassName).append('(').append(JSON_READER_PARAMETER_DEF).comma().append("preReadName: String?")
subtypeAspect?.writeSuperFieldJava(out)
out.append(") : ").append(typeClass.canonicalName).openBlock()
if (hasLazyFields || JsonObjectBased::class.java.isAssignableFrom(typeClass)) {
out.append("private var ").append(PENDING_INPUT_READER_NAME).append(": ").append(JSON_READER_CLASS_NAME).append("? = reader.subReader()!!").newLine()
}
val classScope = fileScope.newClassScope()
for (field in volatileFields) {
field.writeFieldDeclaration(classScope, out)
out.newLine()
}
for (loader in fieldLoaders) {
if (loader.asImpl) {
out.append("override")
}
else {
out.append("private")
}
out.append(" var ").appendName(loader)
fun addType() {
out.append(": ")
loader.valueReader.appendFinishedValueTypeName(out)
out.append("? = null")
}
if (loader.valueReader is PrimitiveValueReader) {
val defaultValue = loader.defaultValue ?: loader.valueReader.defaultValue
if (defaultValue != null) {
out.append(" = ").append(defaultValue)
}
else {
addType()
}
}
else {
addType()
}
out.newLine()
}
if (fieldLoaders.isNotEmpty()) {
out.newLine()
}
writeConstructorMethod(classScope, out)
out.newLine()
subtypeAspect?.writeParseMethod(classScope, out)
for ((key, value) in methodHandlerMap.entries) {
out.newLine()
value.writeMethodImplementationJava(classScope, key, out)
out.newLine()
}
writeBaseMethods(out)
subtypeAspect?.writeGetSuperMethodJava(out)
writeEqualsMethod(valueImplClassName, out)
out.indentOut().append('}')
}
/**
* Generates Java implementation of standard methods of JSON type class (if needed):
* {@link org.jetbrains.jsonProtocol.JsonObjectBased#getDeferredReader()}
*/
private fun writeBaseMethods(out: TextOutput) {
val method: Method
try {
method = typeClass.getMethod("getDeferredReader")
}
catch (ignored: NoSuchMethodException) {
// Method not found, skip.
return
}
out.newLine()
writeMethodDeclarationJava(out, method)
out.append(" = ").append(PENDING_INPUT_READER_NAME)
}
private fun writeEqualsMethod(valueImplClassName: String, out: TextOutput) {
if (fieldLoaders.isEmpty()) {
return
}
out.newLine().append("override fun equals(other: Any?): Boolean = ")
out.append("other is ").append(valueImplClassName)
// at first we should compare primitive values, then enums, then string, then objects
fun fieldWeight(reader: ValueReader): Int {
var w = 10
if (reader is PrimitiveValueReader) {
w--
if (reader.className != "String") {
w--
}
}
else if (reader is EnumReader) {
// -1 as primitive, -1 as not a string
w -= 2
}
return w
}
for (loader in fieldLoaders.sortedWith(Comparator<FieldLoader> { f1, f2 -> fieldWeight((f1.valueReader)) - fieldWeight((f2.valueReader))})) {
out.append(" && ")
out.appendName(loader).append(" == ").append("other.").appendName(loader)
}
out.newLine()
}
private fun writeConstructorMethod(classScope: ClassScope, out: TextOutput) {
out.append("init").block {
if (fieldLoaders.isEmpty()) {
out.append(READER_NAME).append(".skipValue()")
}
else {
out.append("var ").append(NAME_VAR_NAME).append(" = preReadName")
out.newLine().append("if (").append(NAME_VAR_NAME).append(" == null && reader.hasNext() && reader.beginObject().hasNext())").block {
out.append(NAME_VAR_NAME).append(" = reader.nextName()")
}
out.newLine()
writeReadFields(out, classScope)
// we don't read all data if we have lazy fields, so, we should not check end of stream
//if (!hasLazyFields) {
out.newLine().newLine().append(READER_NAME).append(".endObject()")
//}
}
}
}
private fun writeReadFields(out: TextOutput, classScope: ClassScope) {
val stopIfAllFieldsWereRead = hasLazyFields
val hasOnlyOneFieldLoader = fieldLoaders.size == 1
val isTracedStop = stopIfAllFieldsWereRead && !hasOnlyOneFieldLoader
if (isTracedStop) {
out.newLine().append("var i = 0")
}
out.newLine().append("loop@ while (").append(NAME_VAR_NAME).append(" != null)").block {
(out + "when (" + NAME_VAR_NAME + ")").block {
var isFirst = true
for (fieldLoader in fieldLoaders) {
if (fieldLoader.skipRead) {
continue
}
if (!isFirst) {
out.newLine()
}
out.append('"')
if (fieldLoader.jsonName.first() == '$') {
out.append('\\')
}
out.append(fieldLoader.jsonName).append('"').append(" -> ")
if (stopIfAllFieldsWereRead && !isTracedStop) {
out.openBlock()
}
val primitiveValueName = if (fieldLoader.valueReader is ObjectValueReader) fieldLoader.valueReader.primitiveValueName else null
if (primitiveValueName != null) {
out.append("if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT)").openBlock()
}
out.appendName(fieldLoader).append(" = ")
fieldLoader.valueReader.writeReadCode(classScope, false, out)
if (primitiveValueName != null) {
out.newLine().append("else").openBlock()
assignField(out, "${primitiveValueName}Type")
out.append("reader.peek()").newLine()
assignField(out, primitiveValueName)
out + "reader.nextString(true)"
}
if (stopIfAllFieldsWereRead && !isTracedStop) {
out.newLine().append(READER_NAME).append(".skipValues()").newLine().append("break@loop").closeBlock()
}
if (isFirst) {
isFirst = false
}
}
out.newLine().append("else ->")
if (isTracedStop) {
out.block {
out.append("reader.skipValue()")
out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()"
out.newLine() + "continue@loop"
}
}
else {
out.space().append("reader.skipValue()")
}
}
out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()"
if (isTracedStop) {
out.newLine().newLine().append("if (i++ == ").append(fieldLoaders.size - 1).append(")").block {
(out + READER_NAME + ".skipValues()").newLine() + "break"
}
}
}
}
} | platform/script-debugger/protocol/protocol-reader/src/TypeWriter.kt | 2360246474 |
package com.baeldung.kotlin.jpa
import org.hibernate.cfg.Configuration
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase
import org.hibernate.testing.transaction.TransactionUtil.doInHibernate
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.IOException
import java.util.*
class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
private val properties: Properties
@Throws(IOException::class)
get() {
val properties = Properties()
properties.load(javaClass.classLoader.getResourceAsStream("hibernate.properties"))
return properties
}
override fun getAnnotatedClasses(): Array<Class<*>> {
return arrayOf(Person::class.java, PhoneNumber::class.java)
}
override fun configure(configuration: Configuration) {
super.configure(configuration)
configuration.properties = properties
}
@Test
fun givenPersonWithFullData_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John", "[email protected]", Arrays.asList(PhoneNumber(0, "202-555-0171"), PhoneNumber(0, "202-555-0102")))
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
@Test
fun givenPerson_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John")
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
@Test
fun givenPersonWithNullFields_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John", null, null)
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
} | projects/tutorials-master/tutorials-master/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt | 3565602094 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.lib.impl
import com.intellij.debugger.streams.resolve.AllToResultResolver
import com.intellij.debugger.streams.resolve.IdentityResolver
import com.intellij.debugger.streams.resolve.OptionalOrderResolver
import com.intellij.debugger.streams.trace.CallTraceInterpreter
import com.intellij.debugger.streams.trace.impl.handler.unified.MatchHandler
import com.intellij.debugger.streams.trace.impl.handler.unified.OptionalTerminationHandler
import com.intellij.debugger.streams.trace.impl.handler.unified.ToCollectionHandler
import com.intellij.debugger.streams.trace.impl.interpret.CollectIdentityTraceInterpreter
import com.intellij.debugger.streams.trace.impl.interpret.OptionalTraceInterpreter
/**
* @author Vitaliy.Bibaev
*/
class MatchingOperation(name: String, interpreter: CallTraceInterpreter)
: TerminalOperationBase(name, { call, _, dsl -> MatchHandler(call, dsl) }, interpreter, AllToResultResolver())
class OptionalResultOperation(name: String)
: TerminalOperationBase(name, { call, expr, dsl -> OptionalTerminationHandler(call, expr, dsl) },
OptionalTraceInterpreter(), OptionalOrderResolver())
class ToCollectionOperation(name: String)
: TerminalOperationBase(name, { call, _, dsl -> ToCollectionHandler(call, dsl) },
CollectIdentityTraceInterpreter(), IdentityResolver()) | src/main/java/com/intellij/debugger/streams/lib/impl/TerminalOperations.kt | 585132820 |
package i_introduction._3_Default_Arguments
import util.*
fun todoTask3(): Nothing = TODO(
"""
Task 3.
Several overloads of 'JavaCode3.foo()' can be replaced with one function in Kotlin.
Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile.
You have to add parameters and replace 'todoTask3()' with a real body.
Uncomment the commented code and make it compile.
""",
documentation = doc2(),
references = { name: String -> JavaCode3().foo(name); foo(name) })
fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String =
(if (toUpperCase) name.toUpperCase() else name) + number
fun task3(): String {
return (foo("a") +
foo("b", number = 1) +
foo("c", toUpperCase = true) +
foo(name = "d", number = 2, toUpperCase = true))
}
| src/i_introduction/_3_Default_Arguments/DefaultAndNamedParams.kt | 4289433470 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val EXT_multiview_draw_buffers = "EXTMultiviewDrawBuffers".nativeClassGLES("EXT_multiview_draw_buffers", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows selecting among draw buffers as the rendering target. This may be among multiple primary buffers pertaining to platform-specific
stereoscopic or multiview displays or among offscreen framebuffer object color attachments.
To remove any artificial limitations imposed on the number of possible buffers, draw buffers are identified not as individual enums, but as pairs of
values consisting of an enum representing buffer locations such as COLOR_ATTACHMENT_EXT or MULTIVIEW_EXT, and an integer representing an identifying
index of buffers of this location. These (location, index) pairs are used to specify draw buffer targets using a new DrawBuffersIndexedEXT call.
Rendering to buffers of location MULTIVIEW_EXT associated with the context allows rendering to multiview buffers created by EGL using
EGL_EXT_multiview_window for stereoscopic displays.
Rendering to COLOR_ATTACHMENT_EXT buffers allows implementations to increase the number of potential color attachments indefinitely to renderbuffers
and textures.
This extension allows the traditional quad buffer stereoscopic rendering method that has proven effective by indicating a left or right draw buffer and
rendering to each accordingly, but is also dynamic enough to handle an arbitrary number of color buffer targets all using the same shader. This grants
the user maximum flexibility as well as a familiar interface.
"""
IntConstant(
"Accepted by the {@code location} parameter of DrawBuffersIndexedEXT.",
"COLOR_ATTACHMENT_EXT"..0x90F0,
"MULTIVIEW_EXT"..0x90F1
)
IntConstant(
"Accepted by the {@code target} parameter of GetIntegeri_EXT.",
"DRAW_BUFFER_EXT"..0x0C01,
"READ_BUFFER_EXT"..0x0C02
)
IntConstant(
"Accepted by the {@code target} parameter of GetInteger.",
"MAX_MULTIVIEW_BUFFERS_EXT"..0x90F2
)
void(
"ReadBufferIndexedEXT",
"",
GLenum.IN("src", ""),
GLint.IN("index", "")
)
void(
"DrawBuffersIndexedEXT",
"",
AutoSize("location", "indices")..GLint.IN("n", ""),
const..GLenum_p.IN("location", ""),
const..GLint_p.IN("indices", "")
)
void(
"GetIntegeri_vEXT",
"",
GLenum.IN("target", ""),
GLuint.IN("index", ""),
ReturnParam..Check(1)..GLint_p.OUT("data", "")
)
} | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/EXT_multiview_draw_buffers.kt | 1318359335 |
package info.metadude.android.eventfahrplan.network.repositories
import info.metadude.android.eventfahrplan.commons.logging.Logging
import info.metadude.android.eventfahrplan.network.fetching.FetchFahrplan
import info.metadude.android.eventfahrplan.network.fetching.FetchScheduleResult
import info.metadude.android.eventfahrplan.network.models.Meta
import info.metadude.android.eventfahrplan.network.models.Session
import info.metadude.android.eventfahrplan.network.serialization.FahrplanParser
import okhttp3.OkHttpClient
class ScheduleNetworkRepository(
logging: Logging
) {
private val fetcher = FetchFahrplan(logging)
private val parser = FahrplanParser(logging)
fun fetchSchedule(okHttpClient: OkHttpClient,
url: String,
eTag: String,
onFetchScheduleFinished: (fetchScheduleResult: FetchScheduleResult) -> Unit) {
fetcher.setListener(onFetchScheduleFinished::invoke)
fetcher.fetch(okHttpClient, url, eTag)
}
fun parseSchedule(scheduleXml: String,
eTag: String,
onUpdateSessions: (sessions: List<Session>) -> Unit,
onUpdateMeta: (meta: Meta) -> Unit,
onParsingDone: (result: Boolean, version: String) -> Unit) {
parser.setListener(object : FahrplanParser.OnParseCompleteListener {
override fun onUpdateSessions(sessions: List<Session>) = onUpdateSessions.invoke(sessions)
override fun onUpdateMeta(meta: Meta) = onUpdateMeta.invoke(meta)
override fun onParseDone(result: Boolean, version: String) = onParsingDone.invoke(result, version)
})
parser.parse(scheduleXml, eTag)
}
}
| network/src/main/java/info/metadude/android/eventfahrplan/network/repositories/ScheduleNetworkRepository.kt | 3477740747 |
package fr.jaydeer.dice.dto
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonSubTypes.Type
import com.fasterxml.jackson.annotation.JsonTypeInfo
import fr.jaydeer.common.api.validation.NoneId
import fr.jaydeer.common.api.validation.groups.Creation
import fr.jaydeer.common.dto.EntityDto
import fr.jaydeer.dice.entity.DiceEntity
import javax.validation.constraints.NotNull
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type",
visible = false, defaultImpl = CustomDice::class)
@JsonSubTypes(
Type(value = NSideDice::class, name = DiceType.Id.N_SIDE),
Type(value = CustomDice::class, name = DiceType.Id.CUSTOM)
)
sealed class Dice
data class NSideDice(val n: Int,
val start: Int = 1,
val step: Int = 1) : Dice()
data class CustomDice(@get:NoneId(value = DiceEntity::class, groups = arrayOf(Creation::class))
override val id: String?,
@NotNull(groups = arrayOf(Creation::class))
val faces: Map<String, Int>?) : EntityDto, Dice() | src/main/kotlin/fr/jaydeer/dice/dto/Dice.kt | 2542167047 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.inspection
import com.intellij.codeInspection.reference.EntryPoint
import com.intellij.codeInspection.reference.RefElement
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.psi.PsiElement
import org.jdom.Element
class PlatformAnnotationEntryPoint : EntryPoint() {
override fun getDisplayName() = "Minecraft Entry Point"
override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = false
override fun isEntryPoint(psiElement: PsiElement) = false
override fun isSelected() = false
override fun setSelected(selected: Boolean) {}
override fun getIgnoreAnnotations() =
arrayOf("org.spongepowered.api.event.Listener", "org.bukkit.event.EventHandler")
@Throws(InvalidDataException::class)
override fun readExternal(element: Element) {
}
@Throws(WriteExternalException::class)
override fun writeExternal(element: Element) {
}
}
| src/main/kotlin/inspection/PlatformAnnotationEntryPoint.kt | 241874106 |
package ru.fantlab.android.data.dao.model
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize
data class ClassificatorModel(
@SerializedName("id") val id: Int,
@SerializedName("name") val name: String,
@SerializedName("description") val descr: String?,
@SerializedName("childs") val childs: ArrayList<ClassificatorModel>?
) : Parcelable | app/src/main/kotlin/ru/fantlab/android/data/dao/model/ClassificatorModel.kt | 2048570960 |
package com.commonsense.android.kotlin.base.exceptions
import org.junit.*
import org.junit.jupiter.api.Test
/**
*
*/
internal class StackTraceExceptionTest {
@Ignore
@Test
fun getLocalizedMessage() {
}
@Ignore
@Test
fun getStackTrace() {
}
} | base/src/test/kotlin/com/commonsense/android/kotlin/base/exceptions/StackTraceExceptionTest.kt | 2604309843 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.user.esb
import com.google.common.eventbus.AllowConcurrentEvents
import com.google.common.eventbus.Subscribe
import com.hp.gagawa.java.elements.A
import com.mycollab.common.domain.MailRecipientField
import com.mycollab.common.i18n.MailI18nEnum
import com.mycollab.configuration.ApplicationConfiguration
import com.mycollab.configuration.IDeploymentMode
import com.mycollab.core.utils.DateTimeUtils
import com.mycollab.db.arguments.*
import com.mycollab.html.LinkUtils
import com.mycollab.i18n.LocalizationHelper
import com.mycollab.module.billing.RegisterStatusConstants
import com.mycollab.module.billing.UserStatusConstants
import com.mycollab.module.esb.GenericCommand
import com.mycollab.module.mail.service.ExtMailService
import com.mycollab.module.mail.service.IContentGenerator
import com.mycollab.module.user.AccountLinkGenerator
import com.mycollab.module.user.domain.SimpleUser
import com.mycollab.module.user.domain.criteria.UserSearchCriteria
import com.mycollab.module.user.service.BillingAccountService
import com.mycollab.module.user.service.UserService
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.*
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
class NewUserJoinCommand(private val billingAccountService: BillingAccountService,
private val extMailService: ExtMailService,
private val contentGenerator: IContentGenerator,
private val userService: UserService,
private val deploymentMode: IDeploymentMode,
private val applicationConfiguration: ApplicationConfiguration) : GenericCommand() {
companion object {
val LOG = LoggerFactory.getLogger(NewUserJoinCommand::class.java)
class Formatter {
fun formatMemberLink(siteUrl: String, newMember: SimpleUser): String =
A(AccountLinkGenerator.generatePreviewFullUserLink(siteUrl, newMember.username)).appendText(newMember.displayName).write()
fun formatRoleName(siteUrl: String, newMember: SimpleUser): String =
if (newMember.isAccountOwner == true) "Account Owner"
else A(AccountLinkGenerator.generatePreviewFullRoleLink(siteUrl, newMember.roleId)).appendText(newMember.roleName).write()
}
}
@AllowConcurrentEvents
@Subscribe
fun execute(event: NewUserJoinEvent) {
val username = event.username
val sAccountId = event.sAccountId
val searchCriteria = UserSearchCriteria()
searchCriteria.saccountid = NumberSearchField(sAccountId)
searchCriteria.registerStatuses = SetSearchField(RegisterStatusConstants.ACTIVE)
searchCriteria.addExtraField(OneValueSearchField(SearchField.AND, "s_user_account.isAccountOwner = ", 1))
val accountOwners = userService.findPageableListByCriteria(BasicSearchRequest(searchCriteria))
val newUser = userService.findUserInAccount(username, sAccountId)
if (newUser != null) {
val recipients = accountOwners
.map { it as SimpleUser }
.filter { it.status == UserStatusConstants.EMAIL_VERIFIED }
.map { MailRecipientField(it.username, it.displayName) }
val account = billingAccountService.getAccountById(sAccountId)
if (account != null) {
contentGenerator.putVariable("siteUrl", deploymentMode.getSiteUrl(account.subdomain))
contentGenerator.putVariable("newUser", newUser)
contentGenerator.putVariable("formatter", Formatter())
contentGenerator.putVariable("copyRight", LocalizationHelper.getMessage(Locale.US, MailI18nEnum.Copyright,
DateTimeUtils.getCurrentYear()))
contentGenerator.putVariable("logoPath", LinkUtils.accountLogoPath(account.id, account.logopath))
extMailService.sendHTMLMail(applicationConfiguration.notifyEmail, applicationConfiguration.siteName, recipients,
"${newUser.displayName} has just joined on MyCollab workspace",
contentGenerator.parseFile("mailNewUserJoinAccountNotifier.ftl", Locale.US))
} else {
LOG.error("Can not find account $sAccountId")
}
} else {
LOG.error("Can not find the user $username in account $sAccountId")
}
}
} | mycollab-esb/src/main/java/com/mycollab/module/user/esb/NewUserJoinCommand.kt | 1903621031 |
package de.pbauerochse.worklogviewer.datasource.api.domain
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
class PeriodValue @JsonCreator constructor(
@JsonProperty("minutes") val minutes: Long,
@JsonProperty("presentation") val presentation: String
)
| application/src/main/java/de/pbauerochse/worklogviewer/datasource/api/domain/PeriodValue.kt | 1292295155 |
package org.jetbrains.haskell.debugger.repl
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.openapi.project.Project
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import org.jetbrains.haskell.debugger.prochandlers.HaskellDebugProcessHandler
import com.intellij.execution.process.ProcessTerminatedListener
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.ui.ConsoleView
import com.intellij.openapi.application.ApplicationManager
public object DebugConsoleFactory {
public fun createDebugConsole(project: Project,
processHandler: HaskellDebugProcessHandler): ConsoleView {
val console = ConsoleViewImpl(project, false)
ProcessTerminatedListener.attach(processHandler)
console.attachToProcess(processHandler)
return console
}
} | plugin/src/org/jetbrains/haskell/debugger/repl/DebugConsoleFactory.kt | 3626404460 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.wall.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param comments - Comments number
* @param date - Date when the note has been created in Unixtime
* @param id - Note ID
* @param ownerId - Note owner's ID
* @param readComments - Read comments number
* @param title - Note title
* @param viewUrl - URL of the page with note preview
* @param text - Note text
* @param privacyView
* @param privacyComment
* @param canComment
* @param textWiki - Note wiki text
*/
data class WallAttachedNote(
@SerializedName("comments")
val comments: Int,
@SerializedName("date")
val date: Int,
@SerializedName("id")
val id: Int,
@SerializedName("owner_id")
val ownerId: UserId,
@SerializedName("read_comments")
val readComments: Int,
@SerializedName("title")
val title: String,
@SerializedName("view_url")
val viewUrl: String,
@SerializedName("text")
val text: String? = null,
@SerializedName("privacy_view")
val privacyView: List<String>? = null,
@SerializedName("privacy_comment")
val privacyComment: List<String>? = null,
@SerializedName("can_comment")
val canComment: Int? = null,
@SerializedName("text_wiki")
val textWiki: String? = null
)
| api/src/main/java/com/vk/sdk/api/wall/dto/WallAttachedNote.kt | 175803542 |
package com.eden.orchid.forms
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.converters.StringConverter
import com.eden.orchid.api.options.OptionExtractor
import com.eden.orchid.forms.model.Form
import com.eden.orchid.forms.model.FormsModel
import com.eden.orchid.utilities.SuppressedWarnings
import com.eden.orchid.utilities.resolve
import javax.inject.Provider
import org.json.JSONObject
import java.lang.reflect.Field
import javax.inject.Inject
class FormOptionExtractor
@Inject
constructor(
private val contextProvider: Provider<OrchidContext>,
private val converter: StringConverter
) : OptionExtractor<Form>(1000) {
override fun acceptsClass(clazz: Class<*>): Boolean {
return clazz == Form::class.java
}
@Suppress(SuppressedWarnings.UNCHECKED_KOTLIN)
override fun getOption(field: Field, sourceObject: Any, key: String): Form? {
val formsModel: FormsModel = contextProvider.get().resolve()
if (sourceObject is Form) {
return sourceObject
} else if (sourceObject is JSONObject) {
return Form(contextProvider.get(), "", sourceObject.toMap())
}
else if (sourceObject is Map<*, *>) {
return Form(contextProvider.get(), "", sourceObject as? Map<String, Any> ?: emptyMap())
}
else {
val value = converter.convert(String::class.java, sourceObject)
if (value.first) {
return formsModel.getForm(value.second)
}
}
return null
}
override fun getDefaultValue(field: Field): Form? {
return null
}
}
| plugins/OrchidForms/src/main/kotlin/com/eden/orchid/forms/FormOptionExtractor.kt | 4036588756 |
package org.jetbrains.kotlinx.jupyter.common
private val enumNameRegex = Regex("_(.)")
@OptIn(ExperimentalStdlibApi::class)
fun getNameForUser(name: String): String {
return enumNameRegex.replace(name.lowercase()) { match ->
match.groupValues[1].uppercase()
}
}
| build-plugin/common-dependencies/src/org/jetbrains/kotlinx/jupyter/common/enumUtil.kt | 3747430936 |
package com.intfocus.template.constant
/**
* ****************************************************
* author jameswong
* created on: 17/11/06 下午5:43
* e-mail: [email protected]
* name:
* desc:
* ****************************************************
*/
object AppList {
const val RS = "ruishang"
const val SYP = "shengyinplus"
const val YH = "yonghui"
const val YHTEST = "yonghuitest"
const val YHDEV = "yonghuidev"
}
| app/src/main/java/com/intfocus/template/constant/AppList.kt | 1599815777 |
package de.gesellix.docker.compose.adapters
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonReader
import com.squareup.moshi.ToJson
import de.gesellix.docker.compose.types.ServiceNetwork
class StringToServiceNetworksAdapter {
@ToJson
fun toJson(@ServiceNetworksType networks: Map<String, ServiceNetwork>): List<String> {
throw UnsupportedOperationException()
}
@FromJson
@ServiceNetworksType
fun fromJson(reader: JsonReader): Map<String, ServiceNetwork?> {
val result = hashMapOf<String, ServiceNetwork?>()
when (reader.peek()) {
JsonReader.Token.BEGIN_OBJECT -> {
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (reader.peek()) {
JsonReader.Token.NULL -> result[name] = reader.nextNull()
JsonReader.Token.STRING -> throw UnsupportedOperationException("didn't expect a String value for network $name")
// result[name] = reader.nextString()
JsonReader.Token.BEGIN_OBJECT -> {
val serviceNetwork = ServiceNetwork()
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"ipv4_address" -> serviceNetwork.ipv4Address = reader.nextString()
"ipv6_address" -> serviceNetwork.ipv6Address = reader.nextString()
"aliases" -> {
val aliases = arrayListOf<String>()
reader.beginArray()
while (reader.hasNext()) {
aliases.add(reader.nextString())
}
reader.endArray()
serviceNetwork.aliases = aliases
}
else -> {
// ...
}
}
}
reader.endObject()
result[name] = serviceNetwork
}
else -> {
// ...
}
}
}
reader.endObject()
}
JsonReader.Token.BEGIN_ARRAY -> {
reader.beginArray()
while (reader.hasNext()) {
val name = reader.nextString()
// def value = reader.nextNull()
result[name] = null
}
reader.endArray()
}
else -> {
// ...
}
}
return result
}
}
| src/main/kotlin/de/gesellix/docker/compose/adapters/StringToServiceNetworksAdapter.kt | 2112468578 |
/*
* Copyright (C) 2016-2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.tests.parser
import com.intellij.openapi.extensions.PluginId
import org.hamcrest.CoreMatchers.`is`
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import uk.co.reecedunn.intellij.plugin.core.psi.toPsiTreeString
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.core.vfs.ResourceVirtualFileSystem
import uk.co.reecedunn.intellij.plugin.core.vfs.decode
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
@Suppress("RedundantVisibilityModifier", "Reformat")
@DisplayName("XQuery Update Facility 3.0 - Parser")
class UpdateFacilityParserTest : ParserTestCase() {
override val pluginId: PluginId = PluginId.getId("UpdateFacilityParserTest")
private val res = ResourceVirtualFileSystem(this::class.java.classLoader)
fun parseResource(resource: String): XQueryModule = res.toPsiFile(resource, project)
fun loadResource(resource: String): String? = res.findFileByPath(resource)!!.decode()
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (26) FunctionDecl")
internal inner class FunctionDecl {
@Test
@DisplayName("updating annotation; external")
fun testFunctionDecl_Updating() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("updating annotation; function body")
fun testFunctionDecl_Updating_EnclosedExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_EnclosedExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_EnclosedExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("updating annotation; missing function keyword")
fun testFunctionDecl_Updating_MissingFunctionKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (141) RevalidationDecl")
internal inner class RevalidationDecl {
@Test
@DisplayName("revalidation declaration")
fun testRevalidationDecl() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("revalidation declaration; compact whitespace")
fun testRevalidationDecl_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing revalidation mode")
fun testRevalidationDecl_MissingRevalidationMode() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationMode.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationMode.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing revalidation keyword")
fun testRevalidationDecl_MissingRevalidationKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing semicolon")
fun testRevalidationDecl_MissingSemicolon() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingSemicolon.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingSemicolon.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("prolog body statements before")
fun testRevalidationDecl_PrologBodyStatementsBefore() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsBefore.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsBefore.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("prolog body statements after")
fun testRevalidationDecl_PrologBodyStatementsAfter() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsAfter.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsAfter.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (142) InsertExprTargetChoice")
internal inner class InsertExprTargetChoice {
@Test
@DisplayName("into")
fun testInsertExprTargetChoice_Into() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Node.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Node.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first")
fun testInsertExprTargetChoice_First() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_First.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_First.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("last")
fun testInsertExprTargetChoice_Last() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Last.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Last.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first/last; missing 'as' keyword")
fun testInsertExprTargetChoice_FirstLast_MissingAsKeyword() {
val expected =
loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingAsKeyword.txt")
val actual =
parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingAsKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first/last; missing 'first'/'last' keyword")
fun testInsertExprTargetChoice_FirstLast_MissingFirstLastKeyword() {
val expected =
loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingFirstLastKeyword.txt")
val actual =
parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingFirstLastKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first/last; missing 'into' keyword")
fun testInsertExprTargetChoice_FirstLast_MissingIntoKeyword() {
val expected =
loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingIntoKeyword.txt")
val actual =
parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingIntoKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("before")
fun testInsertExprTargetChoice_Before() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Before.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Before.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("after")
fun testInsertExprTargetChoice_After() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_After.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_After.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (143) InsertExpr")
internal inner class InsertExpr {
@Test
@DisplayName("node")
fun testInsertExpr_Node() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Node.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Node.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("node; compact whitespace")
fun testInsertExpr_Node_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Node_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Node_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("nodes")
fun testInsertExpr_Nodes() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("nodes; compact whitespace")
fun testInsertExpr_Nodes_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing source SourceExpr")
fun testInsertExpr_MissingSourceExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_MissingSourceExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_MissingSourceExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing InsertExprTargetChoice")
fun testInsertExpr_MissingInsertExprTargetChoice() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_MissingInsertExprTargetChoice.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_MissingInsertExprTargetChoice.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testInsertExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (144) DeleteExpr")
internal inner class DeleteExpr {
@Test
@DisplayName("node")
fun testDeleteExpr_Node() {
val expected = loadResource("tests/parser/xquery-update-1.0/DeleteExpr_Node.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/DeleteExpr_Node.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("nodes")
fun testDeleteExpr_Nodes() {
val expected = loadResource("tests/parser/xquery-update-1.0/DeleteExpr_Nodes.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/DeleteExpr_Nodes.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testDeleteExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/DeleteExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/DeleteExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (145) ReplaceExpr")
internal inner class ReplaceExpr {
@Test
@DisplayName("replace expression")
fun testReplaceExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testReplaceExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'with' keyword")
fun testReplaceExpr_MissingWithKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingWithKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingWithKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing ReplaceExpr")
fun testReplaceExpr_MissingReplaceExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingReplaceExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingReplaceExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("value of")
fun testReplaceExpr_ValueOf() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("value of; missing 'node' keyword")
fun testReplaceExpr_ValueOf_MissingNodeKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingNodeKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingNodeKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("value of; missing 'of' keyword")
fun testReplaceExpr_ValueOf_MissingOfKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingOfKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingOfKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (145) ReplaceExpr")
internal inner class RenameExpr {
@Test
@DisplayName("rename expression")
fun testRenameExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testRenameExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'as' keyword")
fun testRenameExpr_MissingAsKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr_MissingAsKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr_MissingAsKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing NewNameExpr")
fun testRenameExpr_MissingNewNameExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr_MissingNewNameExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr_MissingNewNameExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (150) TransformExpr ; XQuery Update Facility 3.0 EBNF (208) CopyModifyExpr")
internal inner class TransformExpr {
@Test
@DisplayName("copy modify expression")
fun testTransformExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("copy modify expression; compact whitespace")
fun testTransformExpr_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("copy modify expression; recover using '=' instead of ':='")
fun testTransformExpr_Equal() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_Equal.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_Equal.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing VarName")
fun testTransformExpr_MissingVarName() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarName.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarName.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing ':='")
fun testTransformExpr_MissingVarAssignOperator() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignOperator.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignOperator.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing variable assignment Expr")
fun testTransformExpr_MissingVarAssignExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'modify' keyword")
fun testTransformExpr_MissingModifyKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing modify Expr")
fun testTransformExpr_MissingModifyExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'return' keyword")
fun testTransformExpr_MissingReturnKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing return Expr")
fun testTransformExpr_MissingReturnExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("multiple VarName")
fun testTransformExpr_MultipleVarName() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("multiple VarName; compact whitespace")
fun testTransformExpr_MultipleVarName_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("multiple VarName; missing '$' variable indicator")
fun testTransformExpr_MultipleVarName_MissingVarIndicator() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_MissingVarIndicator.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_MissingVarIndicator.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("VarName as XQuery 3.0 EQName")
fun testTransformExpr_EQName() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_EQName.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_EQName.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.0 EBNF (27) CompatibilityAnnotation")
internal inner class CompatibilityAnnotation {
@Test
@DisplayName("function declaration")
fun testCompatibilityAnnotation_FunctionDecl() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("function declaration; missing 'function' keyword")
fun testCompatibilityAnnotation_FunctionDecl_MissingFunctionKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("variable declaration")
fun testCompatibilityAnnotation_VarDecl() {
val expected = loadResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("variable declaration; missing 'variable' keyword")
fun testCompatibilityAnnotation_VarDecl_MissingVariableKeyword() {
val expected = loadResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl_MissingVariableKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl_MissingVariableKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.0 EBNF (97) TransformWithExpr")
internal inner class TransformWithExpr30 {
@Test
@DisplayName("transform with expression")
fun testTransformWithExpr() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("transform with expression; compact whitespace")
fun testTransformWithExpr_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'with' keyword")
fun testTransformWithExpr_MissingWithKeyword() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingWithKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingWithKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing opening brace")
fun testTransformWithExpr_MissingOpeningBrace() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingOpeningBrace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingOpeningBrace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing Expr")
fun testTransformWithExpr_MissingExpr() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing closing brace")
fun testTransformWithExpr_MissingClosingBrace() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingClosingBrace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingClosingBrace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.0 EBNF (207) UpdatingFunctionCall")
internal inner class UpdatingFunctionCall {
@Test
@DisplayName("updating function call")
fun testUpdatingFunctionCall() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("updating function call; compact whitespace")
fun testUpdatingFunctionCall_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'updating' keyword")
fun testUpdatingFunctionCall_MissingUpdatingKeyword() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingUpdatingKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingUpdatingKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing opening parenthesis")
fun testUpdatingFunctionCall_MissingOpeningParenthesis() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingOpeningParenthesis.txt")
val actual =
parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingOpeningParenthesis.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing PrimaryExpr")
fun testUpdatingFunctionCall_MissingPrimaryExpr() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingPrimaryExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingPrimaryExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing closing parenthesis")
fun testUpdatingFunctionCall_MissingClosingParenthesis() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingClosingParenthesis.txt")
val actual =
parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingClosingParenthesis.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("arguments: single")
fun testUpdatingFunctionCall_Arguments_Single() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Single.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Single.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("arguments: multiple")
fun testUpdatingFunctionCall_Arguments_Multiple() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("arguments: multiple; compact whitespace")
fun testUpdatingFunctionCall_Arguments_Multiple_CompactWhitespace() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple_CompactWhitespace.txt")
val actual =
parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.1 EBNF (97) TransformWithExpr")
internal inner class TransformWithExpr31 {
@Test
@DisplayName("arrow expression")
fun testTransformWithExpr_ArrowExpr() {
val expected = loadResource("tests/parser/xquery-update-3.1/TransformWithExpr_ArrowExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.1/TransformWithExpr_ArrowExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
}
| src/lang-xquery/test/uk/co/reecedunn/intellij/plugin/xquery/tests/parser/UpdateFacilityParserTest.kt | 3911379406 |
/*
* Copyright (C) 2019 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.completion.filters
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import uk.co.reecedunn.intellij.plugin.core.completion.CompletionFilter
import uk.co.reecedunn.intellij.plugin.core.sequences.ancestors
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathAtomicOrUnionType
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathSimpleTypeName
object XPathAtomicOrUnionTypeFilter : CompletionFilter {
override fun accepts(element: PsiElement, context: ProcessingContext): Boolean {
return element.ancestors().find {
when (it) {
is XPathAtomicOrUnionType -> true // SequenceType / ItemType
is XPathSimpleTypeName -> true // SingleType
else -> false
}
} != null
}
}
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/completion/filters/XPathAtomicOrUnionTypeFilter.kt | 38624710 |
package uy.klutter.json.jackson
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.singleton
object KodeinJacksonWithKotlin {
/**
* Add an ObjectMapper singleton factory to Kodein registry that is enabled for Kotlin classes
*/
val module = Kodein.Module {
bind<ObjectMapper>() with singleton {
jacksonObjectMapper()
.registerModule(JavaTimeModule())
.registerModule(Jdk8Module())
.registerModule(ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
}
}
/**
* Add an ObjectMapper singleton factory to Kodein registry that auto finds and registers all Jackson modules found on
* the classpath using Java service provider interface. This is slower than direct registration of modules, but only
* done once. Also, by adding modules directly you are ensured your dependencies are correct for the application at
* compile-time, which is safer.
*/
val moduleWithAutoFindJacksonModules = Kodein.Module {
bind<ObjectMapper>() with singleton { jacksonObjectMapper().findAndRegisterModules() }
}
}
| json-jackson-kodein/src/main/kotlin/uy/klutter/json/jackson/KodeinModule.kt | 1462209230 |
/*
* Copyright (C) 2016, 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast.xpath
import uk.co.reecedunn.intellij.plugin.xpm.optree.item.XpmArrayExpression
/**
* An XPath 3.1 and XQuery 3.1 `ArrayConstructor` node in the XQuery AST.
*/
interface XPathArrayConstructor : XPathPrimaryExpr, XpmArrayExpression
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathArrayConstructor.kt | 157608741 |
/*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.github.andrewoma.kwery.fetcher.readme
import com.github.andrewoma.kwery.fetcher.*
// Given the following domain model
data class Actor(val id: Int, val firstName: String, val lastName: String)
data class Language(val id: Int, val name: String)
data class Film(val id: Int, val language: Language, val actors: Set<Actor>,
val title: String, val releaseYear: Int)
@Suppress("UNUSED_PARAMETER")
class Dao<ID, T> {
fun findByIds(id: Collection<ID>): Map<ID, T> = mapOf()
fun findByFilmIds(id: Collection<ID>): Map<ID, Collection<T>> = mapOf()
fun findFilmsReleasedAfter(year: Int): List<Film> = listOf()
}
fun readme() {
val languageDao = Dao<Int, Language>()
val filmDao = Dao<Int, Film>()
val actorDao = Dao<Int, Actor>()
// Define types with functions describing how to fetch a batch by ids
val language = Type(Language::id, { languageDao.findByIds(it) })
val actor = Type(Actor::id, { actorDao.findByIds(it) })
// For types that reference other types describe how to apply fetched values
val film = Type(Film::id, { filmDao.findByIds(it) }, listOf(
// 1 to 1
Property(Film::language, language, { it.language.id }, { f, l -> f.copy(language = l) }),
// 1 to many requires a function to describe how to fetch the related objects
CollectionProperty(Film::actors, actor, { it.id },
{ f, a -> f.copy(actors = a.toSet()) },
{ actorDao.findByFilmIds(it) })
))
val fetcher = GraphFetcher(setOf(language, actor, film))
// Extension function to fetch the graph for any List using fetcher defined above
fun <T> List<T>.fetch(vararg nodes: Node) = fetcher.fetch(this, Node.create("", nodes.toSet()))
// We can now efficiently fetch various graphs for any list of films
// The following fetches the films with actors and languages in 3 queries
val filmsWithAll = filmDao.findFilmsReleasedAfter(2010).fetch(Node.all)
// The graph specification can also be built using properties
val filmsWithActors = filmDao.findFilmsReleasedAfter(2010).fetch(Film::actors.node())
println("$filmsWithAll $filmsWithActors")
}
fun main(args: Array<String>) {
readme()
} | fetcher/src/test/kotlin/com/github/andrewoma/kwery/fetcher/readme/Readme.kt | 3218662733 |
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.samples.config
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.web.servlet.invoke
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.provisioning.InMemoryUserDetailsManager
/**
* @author Eleftheria Stein
*/
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/css/**", permitAll)
authorize("/user/**", hasAuthority("ROLE_USER"))
}
formLogin {
loginPage = "/log-in"
}
}
}
@Bean
public override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
return InMemoryUserDetailsManager(userDetails)
}
}
| samples/boot/kotlin/src/main/kotlin/org/springframework/security/samples/config/SecurityConfig.kt | 1843431867 |
package me.serce.solidity.lang.core
import com.intellij.psi.tree.IElementType
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.FileViewProvider
import me.serce.solidity.lang.SolidityFileType
import me.serce.solidity.lang.SolidityLanguage
class SolidityFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, SolidityLanguage) {
override fun getFileType(): FileType = SolidityFileType
override fun toString(): String = "Solidity File"
}
class SolidityElementType(val name: String) : IElementType(name, SolidityLanguage)
| src/main/kotlin/me/serce/solidity/lang/core/psi.kt | 3179246896 |
package org.walleth.enhancedlist
interface EnhancedListInterface<T> {
suspend fun undeleteAll()
suspend fun deleteAllSoftDeleted()
suspend fun getAll(): List<T>
fun compare(t1: T, t2: T): Boolean
suspend fun upsert(item: T)
suspend fun filter(item: T) : Boolean
} | app/src/main/java/org/walleth/enhancedlist/EnhancedListInterface.kt | 2889443515 |
package com.vmenon.mpo.auth.framework.di.dagger
import android.app.Application
import com.vmenon.mpo.auth.data.AuthState
import com.vmenon.mpo.auth.domain.AuthService
import com.vmenon.mpo.auth.domain.biometrics.BiometricsManager
import com.vmenon.mpo.auth.framework.AuthServiceImpl
import com.vmenon.mpo.auth.framework.Authenticator
import com.vmenon.mpo.auth.framework.openid.OpenIdAuthenticator
import com.vmenon.mpo.system.domain.Logger
import dagger.Module
import dagger.Provides
@Module
object AuthModule {
@Provides
@AuthScope
fun provideAuthService(
authState: AuthState,
authenticator: Authenticator,
biometricsManager: BiometricsManager
): AuthService =
AuthServiceImpl(authState, authenticator, biometricsManager)
// TODO: Probably makes more sense to move this into OpenIdAuthModule and have AuthComponent
// depend on OpenIdAuthComponent
@Provides
@AuthScope
fun provideAuthenticator(
application: Application,
authState: AuthState,
logger: Logger
): Authenticator =
OpenIdAuthenticator(application, authState, logger)
} | auth_framework/src/main/java/com/vmenon/mpo/auth/framework/di/dagger/AuthModule.kt | 3076363780 |
package me.liuqingwen.android.projectvideoplayer
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest
{
@Test fun addition_isCorrect()
{
assertEquals(4, 2 + 2)
}
}
| ProjectVideoPlayer/app/src/test/java/me/liuqingwen/android/projectvideoplayer/ExampleUnitTest.kt | 15864530 |
package info.hzvtc.hipixiv.pojo
class EmptyResponse
| app/src/main/java/info/hzvtc/hipixiv/pojo/EmptyResponse.kt | 752662536 |
package dev.jriley.hackernews
import org.junit.Assert.*
import org.junit.Test
class NumberParseTest {
@Test
fun parseValueSumTheParts() {
val value = 1234L
assertEquals(10, parseNumber(value))
assertTrue(equalsOne(value))
}
@Test
fun nextInvalidNumber() {
val value = 9876L
assertEquals(30, parseNumber(value))
assertFalse(equalsOne(value))
}
@Test
fun nextValidNumber() {
val value = 442L
assertEquals(10, parseNumber(value))
assertTrue(equalsOne(value))
}
@Test
fun longMaxValue() {
assertEquals(88, parseNumber(Long.MAX_VALUE))
assertFalse(equalsOne(Long.MAX_VALUE))
}
@Test
fun intMaxValue() {
val value = Int.MAX_VALUE.toLong()
assertEquals(46, parseNumber(value))
assertFalse(equalsOne(value))
}
private fun equalsOne(value: Long): Boolean = parseNumber(parseNumber(value)) == 1L
private fun parseNumber(value: Long): Long {
var x = value
var y = 0L
while (x > 0) {
y += x % 10
x /= 10
}
return y
}
} | mobile/src/test/java/dev/jriley/hackernews/NumberParseTest.kt | 3988374230 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.test.java
import org.jetbrains.uast.test.common.RenderLogTestBase
import java.io.File
abstract class AbstractJavaRenderLogTest : AbstractJavaUastTest(), RenderLogTestBase {
override fun getTestFile(testName: String, ext: String) =
File(File(TEST_JAVA_MODEL_DIR, testName).canonicalPath.substringBeforeLast('.') + '.' + ext)
} | uast/uast-tests/test/org/jetbrains/uast/test/java/AbstractJavaRenderLogTest.kt | 293690209 |
package expo.modules.camera.tasks
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.util.Base64
import androidx.exifinterface.media.ExifInterface
import expo.modules.camera.CameraViewHelper.getExifData
import expo.modules.camera.CameraViewHelper.addExifData
import expo.modules.camera.utils.FileSystemUtils
import expo.modules.core.Promise
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
private const val DIRECTORY_NOT_FOUND_MSG = "Documents directory of the app could not be found."
private const val UNKNOWN_IO_EXCEPTION_MSG = "An unknown I/O exception has occurred."
private const val UNKNOWN_EXCEPTION_MSG = "An unknown exception has occurred."
private const val ERROR_TAG = "E_TAKING_PICTURE_FAILED"
private const val DIRECTORY_NAME = "Camera"
private const val EXTENSION = ".jpg"
private const val SKIP_PROCESSING_KEY = "skipProcessing"
private const val FAST_MODE_KEY = "fastMode"
private const val QUALITY_KEY = "quality"
private const val BASE64_KEY = "base64"
private const val HEIGHT_KEY = "height"
private const val WIDTH_KEY = "width"
private const val EXIF_KEY = "exif"
private const val DATA_KEY = "data"
private const val URI_KEY = "uri"
private const val ID_KEY = "id"
private const val DEFAULT_QUALITY = 1
class ResolveTakenPictureAsyncTask(
private var promise: Promise,
private var options: Map<String, Any>,
private val directory: File,
private var pictureSavedDelegate: PictureSavedDelegate
) : AsyncTask<Void?, Void?, Bundle?>() {
private var imageData: ByteArray? = null
private var bitmap: Bitmap? = null
constructor(imageData: ByteArray?, promise: Promise, options: Map<String, Any>, directory: File, delegate: PictureSavedDelegate) : this(
promise, options, directory, delegate
) {
this.imageData = imageData
}
constructor(bitmap: Bitmap?, promise: Promise, options: Map<String, Any>, directory: File, delegate: PictureSavedDelegate) : this(
promise, options, directory, delegate
) {
this.bitmap = bitmap
}
private val quality: Int
get() = options[QUALITY_KEY]?.let {
val requestedQuality = (it as Number).toDouble()
(requestedQuality * 100).toInt()
} ?: DEFAULT_QUALITY * 100
override fun doInBackground(vararg params: Void?): Bundle? {
// handle SkipProcessing
if (imageData != null && isOptionEnabled(SKIP_PROCESSING_KEY)) {
return handleSkipProcessing()
}
if (bitmap == null) {
bitmap = imageData?.let { BitmapFactory.decodeByteArray(imageData, 0, it.size) }
}
try {
ByteArrayInputStream(imageData).use { inputStream ->
val response = Bundle()
val exifInterface = ExifInterface(inputStream)
// Get orientation of the image from mImageData via inputStream
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
// Rotate the bitmap to the proper orientation if needed
if (orientation != ExifInterface.ORIENTATION_UNDEFINED) {
bitmap = bitmap?.let {
rotateBitmap(it, getImageRotation(orientation))
}
}
// Write Exif data to the response if requested
if (isOptionEnabled(EXIF_KEY)) {
val exifData = getExifData(exifInterface)
response.putBundle(EXIF_KEY, exifData)
}
// Upon rotating, write the image's dimensions to the response
response.apply {
putInt(WIDTH_KEY, bitmap!!.width)
putInt(HEIGHT_KEY, bitmap!!.height)
}
// Cache compressed image in imageStream
ByteArrayOutputStream().use { imageStream ->
bitmap!!.compress(Bitmap.CompressFormat.JPEG, quality, imageStream)
// Write compressed image to file in cache directory
val filePath = writeStreamToFile(imageStream)
// Save Exif data to the image if requested
if (isOptionEnabled(EXIF_KEY)) {
val exifFromFile = ExifInterface(filePath!!)
addExifData(exifFromFile, exifInterface)
}
val imageFile = File(filePath)
val fileUri = Uri.fromFile(imageFile).toString()
response.putString(URI_KEY, fileUri)
// Write base64-encoded image to the response if requested
if (isOptionEnabled(BASE64_KEY)) {
response.putString(BASE64_KEY, Base64.encodeToString(imageStream.toByteArray(), Base64.NO_WRAP))
}
}
return response
}
} catch (e: Exception) {
when (e) {
is Resources.NotFoundException -> promise.reject(ERROR_TAG, DIRECTORY_NOT_FOUND_MSG, e)
is IOException -> promise.reject(ERROR_TAG, UNKNOWN_IO_EXCEPTION_MSG, e)
else -> promise.reject(ERROR_TAG, UNKNOWN_EXCEPTION_MSG, e)
}
e.printStackTrace()
}
// An exception had to occur, promise has already been rejected. Do not try to resolve it again.
return null
}
private fun handleSkipProcessing(): Bundle? {
try {
// save byte array (it's already a JPEG)
ByteArrayOutputStream().use { imageStream ->
imageStream.write(imageData)
// write compressed image to file in cache directory
val filePath = writeStreamToFile(imageStream)
val imageFile = File(filePath)
// handle image uri
val fileUri = Uri.fromFile(imageFile).toString()
// read exif information
val exifInterface = ExifInterface(filePath!!)
return Bundle().apply {
putString(URI_KEY, fileUri)
putInt(WIDTH_KEY, exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, -1))
putInt(HEIGHT_KEY, exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, -1))
// handle exif request
if (isOptionEnabled(EXIF_KEY)) {
val exifData = getExifData(exifInterface)
putBundle(EXIF_KEY, exifData)
}
// handle base64
if (isOptionEnabled(BASE64_KEY)) {
putString(BASE64_KEY, Base64.encodeToString(imageData, Base64.NO_WRAP))
}
}
}
} catch (e: Exception) {
if (e is IOException) {
promise.reject(ERROR_TAG, UNKNOWN_IO_EXCEPTION_MSG, e)
} else {
promise.reject(ERROR_TAG, UNKNOWN_EXCEPTION_MSG, e)
}
e.printStackTrace()
}
// error occurred
return null
}
override fun onPostExecute(response: Bundle?) {
super.onPostExecute(response)
// If the response is not null everything went well and we can resolve the promise.
if (response != null) {
if (isOptionEnabled(FAST_MODE_KEY)) {
val wrapper = Bundle()
wrapper.putInt(ID_KEY, (options[ID_KEY] as Double).toInt())
wrapper.putBundle(DATA_KEY, response)
pictureSavedDelegate.onPictureSaved(wrapper)
} else {
promise.resolve(response)
}
}
}
// Write stream to file in cache directory
@Throws(Exception::class)
private fun writeStreamToFile(inputStream: ByteArrayOutputStream): String? {
try {
val outputPath = FileSystemUtils.generateOutputPath(directory, DIRECTORY_NAME, EXTENSION)
FileOutputStream(outputPath).use { outputStream ->
inputStream.writeTo(outputStream)
}
return outputPath
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
private fun rotateBitmap(source: Bitmap, angle: Int): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle.toFloat())
return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
}
// Get rotation degrees from Exif orientation enum
private fun getImageRotation(orientation: Int) = when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
private fun isOptionEnabled(key: String) = options[key] != null && (options[key] as Boolean)
}
| packages/expo-camera/android/src/main/java/expo/modules/camera/tasks/ResolveTakenPictureAsyncTask.kt | 3018843588 |
package info.nightscout.androidaps.diaconn.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import io.reactivex.rxjava3.core.Single
@Dao
abstract class DiaconnHistoryRecordDao {
@Query("SELECT * from $TABLE_DIACONN_HISTORY WHERE timestamp >= :timestamp AND code = :type")
abstract fun allFromByType(timestamp: Long, type: Byte): Single<List<DiaconnHistoryRecord>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun createOrUpdate(diaconnHistoryRecord: DiaconnHistoryRecord)
@Query( "SELECT * from $TABLE_DIACONN_HISTORY WHERE pumpUid = :pumpUid ORDER BY timestamp DESC LIMIT 1" )
abstract fun getLastRecord(pumpUid: String): DiaconnHistoryRecord?
}
| diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecordDao.kt | 4070949324 |
/*
* Copyright © 2020 Paul Ambrose ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus.agent
import brave.grpc.GrpcTracing
import com.github.pambrose.common.delegate.AtomicDelegates.atomicBoolean
import com.github.pambrose.common.dsl.GrpcDsl.channel
import com.github.pambrose.common.util.simpleClassName
import com.github.pambrose.common.utils.TlsContext
import com.github.pambrose.common.utils.TlsContext.Companion.PLAINTEXT_CONTEXT
import com.github.pambrose.common.utils.TlsUtils.buildClientTlsContext
import com.google.protobuf.Empty
import io.grpc.ClientInterceptors
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.prometheus.Agent
import io.prometheus.common.BaseOptions.Companion.HTTPS_PREFIX
import io.prometheus.common.BaseOptions.Companion.HTTP_PREFIX
import io.prometheus.common.GrpcObjects
import io.prometheus.common.GrpcObjects.newAgentInfo
import io.prometheus.common.GrpcObjects.newRegisterAgentRequest
import io.prometheus.common.GrpcObjects.newScrapeResponseChunk
import io.prometheus.common.GrpcObjects.newScrapeResponseSummary
import io.prometheus.common.GrpcObjects.toScrapeResponse
import io.prometheus.common.GrpcObjects.toScrapeResponseHeader
import io.prometheus.common.ScrapeResults
import io.prometheus.grpc.ChunkedScrapeResponse
import io.prometheus.grpc.ProxyServiceGrpcKt
import io.prometheus.grpc.ScrapeRequest
import io.prometheus.grpc.ScrapeResponse
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import mu.KLogging
import java.io.ByteArrayInputStream
import java.util.concurrent.CountDownLatch
import java.util.zip.CRC32
import kotlin.properties.Delegates.notNull
internal class AgentGrpcService(
internal val agent: Agent,
private val options: AgentOptions,
private val inProcessServerName: String
) {
private var grpcStarted by atomicBoolean(false)
private var stub: ProxyServiceGrpcKt.ProxyServiceCoroutineStub by notNull()
private val tracing by lazy { agent.zipkinReporterService.newTracing("grpc_client") }
private val grpcTracing by lazy { GrpcTracing.create(tracing) }
var channel: ManagedChannel by notNull()
val hostName: String
val port: Int
private val tlsContext: TlsContext
init {
val schemeStripped =
options.proxyHostname
.run {
when {
startsWith(HTTP_PREFIX) -> removePrefix(HTTP_PREFIX)
startsWith(HTTPS_PREFIX) -> removePrefix(HTTPS_PREFIX)
else -> this
}
}
if (":" in schemeStripped) {
val vals = schemeStripped.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
hostName = vals[0]
port = Integer.valueOf(vals[1])
} else {
hostName = schemeStripped
port = 50051
}
tlsContext =
agent.options.run {
if (certChainFilePath.isNotEmpty() ||
privateKeyFilePath.isNotEmpty() ||
trustCertCollectionFilePath.isNotEmpty()
)
buildClientTlsContext(
certChainFilePath = certChainFilePath,
privateKeyFilePath = privateKeyFilePath,
trustCertCollectionFilePath = trustCertCollectionFilePath
)
else
PLAINTEXT_CONTEXT
}
resetGrpcStubs()
}
@Synchronized
fun shutDown() {
if (agent.isZipkinEnabled)
tracing.close()
if (grpcStarted)
channel.shutdownNow()
}
@Synchronized
fun resetGrpcStubs() {
logger.info { "Creating gRPC stubs" }
if (grpcStarted)
shutDown()
else
grpcStarted = true
channel =
channel(
hostName = hostName,
port = port,
enableRetry = true,
tlsContext = tlsContext,
overrideAuthority = agent.options.overrideAuthority,
inProcessServerName = inProcessServerName
) {
if (agent.isZipkinEnabled)
intercept(grpcTracing.newClientInterceptor())
}
val interceptors = listOf(AgentClientInterceptor(agent))
stub = ProxyServiceGrpcKt.ProxyServiceCoroutineStub(ClientInterceptors.intercept(channel, interceptors))
}
// If successful, this will create an agentContext on the Proxy and an interceptor will add an agent_id to the headers`
suspend fun connectAgent() =
try {
logger.info { "Connecting to proxy at ${agent.proxyHost} using ${tlsContext.desc()}..." }
stub.connectAgent(Empty.getDefaultInstance())
logger.info { "Connected to proxy at ${agent.proxyHost} using ${tlsContext.desc()}" }
agent.metrics { connectCount.labels(agent.launchId, "success").inc() }
true
} catch (e: StatusRuntimeException) {
agent.metrics { connectCount.labels(agent.launchId, "failure").inc() }
logger.info { "Cannot connect to proxy at ${agent.proxyHost} using ${tlsContext.desc()} - ${e.simpleClassName}: ${e.message}" }
false
}
suspend fun registerAgent(initialConnectionLatch: CountDownLatch) {
val request =
newRegisterAgentRequest(agent.agentId, agent.launchId, agent.agentName, hostName, agent.options.consolidated)
stub.registerAgent(request)
.also { response ->
agent.markMsgSent()
if (!response.valid)
throw RequestFailureException("registerAgent() - ${response.reason}")
}
initialConnectionLatch.countDown()
}
fun pathMapSize() =
runBlocking {
stub.pathMapSize(GrpcObjects.newPathMapSizeRequest(agent.agentId))
.run {
agent.markMsgSent()
pathCount
}
}
suspend fun registerPathOnProxy(path: String) =
stub.registerPath(GrpcObjects.newRegisterPathRequest(agent.agentId, path))
.apply {
agent.markMsgSent()
if (!valid)
throw RequestFailureException("registerPathOnProxy() - $reason")
}
suspend fun unregisterPathOnProxy(path: String) =
stub.unregisterPath(GrpcObjects.newUnregisterPathRequest(agent.agentId, path))
.apply {
agent.markMsgSent()
if (!valid)
throw RequestFailureException("unregisterPathOnProxy() - $reason")
}
suspend fun sendHeartBeat() {
agent.agentId
.also { agentId ->
if (agentId.isNotEmpty())
try {
stub.sendHeartBeat(GrpcObjects.newHeartBeatRequest(agentId))
.apply {
agent.markMsgSent()
if (!valid) {
logger.error { "AgentId $agentId not found on proxy" }
throw StatusRuntimeException(Status.NOT_FOUND)
}
}
} catch (e: StatusRuntimeException) {
logger.error { "sendHeartBeat() failed ${e.status}" }
}
}
}
suspend fun readRequestsFromProxy(agentHttpService: AgentHttpService, connectionContext: AgentConnectionContext) {
connectionContext
.use {
val agentInfo = newAgentInfo(agent.agentId)
stub.readRequestsFromProxy(agentInfo)
.collect { request: ScrapeRequest ->
// The actual fetch happens at the other end of the channel, not here.
logger.debug { "readRequestsFromProxy():\n$request" }
connectionContext.scrapeRequestsChannel.send { agentHttpService.fetchScrapeUrl(request) }
agent.scrapeRequestBacklogSize.incrementAndGet()
}
}
}
private suspend fun processScrapeResults(
agent: Agent,
scrapeResultsChannel: Channel<ScrapeResults>,
nonChunkedChannel: Channel<ScrapeResponse>,
chunkedChannel: Channel<ChunkedScrapeResponse>
) =
try {
for (scrapeResults: ScrapeResults in scrapeResultsChannel) {
val scrapeId = scrapeResults.scrapeId
if (!scrapeResults.zipped) {
logger.debug { "Writing non-chunked msg scrapeId: $scrapeId length: ${scrapeResults.contentAsText.length}" }
nonChunkedChannel.send(scrapeResults.toScrapeResponse())
agent.metrics { scrapeResultCount.labels(agent.launchId, "non-gzipped").inc() }
} else {
val zipped = scrapeResults.contentAsZipped
val chunkContentSize = options.chunkContentSizeKbs
logger.debug { "Comparing ${zipped.size} and $chunkContentSize" }
if (zipped.size < chunkContentSize) {
logger.debug { "Writing zipped non-chunked msg scrapeId: $scrapeId length: ${zipped.size}" }
nonChunkedChannel.send(scrapeResults.toScrapeResponse())
agent.metrics { scrapeResultCount.labels(agent.launchId, "gzipped").inc() }
} else {
scrapeResults.toScrapeResponseHeader()
.also {
logger.debug { "Writing header length: ${zipped.size} for scrapeId: $scrapeId " }
chunkedChannel.send(it)
}
var totalByteCount = 0
var totalChunkCount = 0
val checksum = CRC32()
val bais = ByteArrayInputStream(zipped)
val buffer = ByteArray(chunkContentSize)
var readByteCount: Int
while (bais.read(buffer).also { bytesRead -> readByteCount = bytesRead } > 0) {
totalChunkCount++
totalByteCount += readByteCount
checksum.update(buffer, 0, buffer.size)
newScrapeResponseChunk(scrapeId, totalChunkCount, readByteCount, checksum, buffer)
.also {
logger.debug { "Writing chunk $totalChunkCount for scrapeId: $scrapeId" }
chunkedChannel.send(it)
}
}
newScrapeResponseSummary(scrapeId, totalChunkCount, totalByteCount, checksum)
.also {
logger.debug { "Writing summary totalChunkCount: $totalChunkCount for scrapeID: $scrapeId" }
chunkedChannel.send(it)
agent.metrics { scrapeResultCount.labels(agent.launchId, "chunked").inc() }
}
}
}
agent.markMsgSent()
agent.scrapeRequestBacklogSize.decrementAndGet()
}
} finally {
nonChunkedChannel.close()
chunkedChannel.close()
}
suspend fun writeResponsesToProxyUntilDisconnected(agent: Agent, connectionContext: AgentConnectionContext) {
fun exceptionHandler() =
CoroutineExceptionHandler { _, e ->
if (agent.isRunning)
Status.fromThrowable(e)
.apply {
logger.error { "Error in writeResponsesToProxyUntilDisconnected(): $code $description" }
}
}
coroutineScope {
val nonChunkedChannel = Channel<ScrapeResponse>(Channel.UNLIMITED)
val chunkedChannel = Channel<ChunkedScrapeResponse>(Channel.UNLIMITED)
launch(Dispatchers.Default + exceptionHandler()) {
processScrapeResults(agent, connectionContext.scrapeResultsChannel, nonChunkedChannel, chunkedChannel)
}
connectionContext
.use {
coroutineScope {
launch(Dispatchers.Default + exceptionHandler()) {
stub.writeResponsesToProxy(nonChunkedChannel.consumeAsFlow())
}
launch(Dispatchers.Default + exceptionHandler()) {
stub.writeChunkedResponsesToProxy(chunkedChannel.consumeAsFlow())
}
}
logger.info { "Disconnected from proxy at ${agent.proxyHost}" }
}
}
}
companion object : KLogging()
} | src/main/kotlin/io/prometheus/agent/AgentGrpcService.kt | 2406205106 |
/*
* Copyright 2013 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.squareup.wire.protos.kotlin.unknownfields.EnumVersionTwo
import com.squareup.wire.protos.kotlin.unknownfields.NestedVersionOne
import com.squareup.wire.protos.kotlin.unknownfields.NestedVersionTwo
import com.squareup.wire.protos.kotlin.unknownfields.VersionOne
import com.squareup.wire.protos.kotlin.unknownfields.VersionTwo
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertNull
class UnknownFieldsTest {
private val v1Adapter = VersionOne.ADAPTER
private val v2Adapter = VersionTwo.ADAPTER
@Test
fun testUnknownFields() {
val v1_obj = NestedVersionOne(i = 111)
val v2_obj = NestedVersionTwo(
i = 111,
v2_i = 12345,
v2_s = "222",
v2_f32 = 67890,
v2_f64 = 98765L,
v2_rs = listOf("1", "2")
)
val v2 = VersionTwo(
i = 111,
v2_i = 12345,
v2_s = "222",
v2_f32 = 67890,
v2_f64 = 98765L,
v2_rs = listOf("1", "2"),
obj = v2_obj
)
assertEquals(111, v2.i)
assertEquals(v2.obj!!.copy(), v2.obj)
// Check v.2 fields
assertEquals(12345, v2.v2_i)
assertEquals("222", v2.v2_s)
assertEquals(67890, v2.v2_f32)
assertEquals(98765L, v2.v2_f64)
assertEquals(listOf("1", "2"), v2.v2_rs)
// Serialized
val v2Bytes = v2Adapter.encode(v2)
// Parse
val v1 = v1Adapter.decode(v2Bytes)
// v.1 fields are visible, v.2 fields are in unknownFieldSet
assertEquals(111, v1.i)
assertEquals(v1_obj, v1.obj!!.copy(unknownFields = ByteString.EMPTY))
// Serialized output should still contain the v.2 fields
val v1Bytes = v1Adapter.encode(v1)
// Unknown fields participate in equals() and hashCode()
val v1Simple = VersionOne(i = 111, obj = v1_obj)
assertNotEquals(v1Simple, v1)
assertNotEquals(v1Simple.hashCode(), v1.hashCode())
assertArrayNotEquals(v1Adapter.encode(v1Simple), v1Adapter.encode(v1))
// Unknown fields can be removed for equals() and hashCode();
val v1Known = v1.copy(
obj = v1.obj.copy(unknownFields = ByteString.EMPTY),
unknownFields = ByteString.EMPTY
)
assertEquals(v1Simple, v1Known)
assertEquals(v1Simple.hashCode(), v1Known.hashCode())
assertArrayEquals(v1Adapter.encode(v1Simple), v1Adapter.encode(v1Known))
// Re-parse
val v2B = v2Adapter.decode(v1Bytes)
assertEquals(111, v2B.i)
assertEquals(12345, v2B.v2_i)
assertEquals("222", v2B.v2_s)
assertEquals(67890, v2B.v2_f32)
assertEquals(98765L, v2B.v2_f64)
assertEquals(listOf("1", "2"), v2B.v2_rs)
assertEquals(v2_obj, v2B.obj)
// "Modify" v1 via a merged builder, serialize, and re-parse
val v1Modified = v1.copy(i = 777, obj = v1_obj.copy(i = 777))
assertEquals(777, v1Modified.i)
assertEquals(v1_obj.copy(i = 777), v1Modified.obj)
val v1ModifiedBytes = v1Adapter.encode(v1Modified)
val v2C = v2Adapter.decode(v1ModifiedBytes)
assertEquals(777, v2C.i)
assertEquals(12345, v2C.v2_i)
assertEquals("222", v2C.v2_s)
assertEquals(67890, v2C.v2_f32)
assertEquals(98765L, v2C.v2_f64)
assertEquals(NestedVersionTwo(i = 777), v2C.obj)
assertEquals(listOf("1", "2"), v2C.v2_rs)
}
@Test fun unknownEnumFields() {
val v2 = VersionTwo(en = EnumVersionTwo.PUSS_IN_BOOTS_V2, i = 100)
val v2Serialized = VersionTwo.ADAPTER.encode(v2)
val v1 = VersionOne.ADAPTER.decode(v2Serialized)
assertEquals(100, v1.i)
assertNull(v1.en)
// 40 = 8 << 3 | 0 (tag: 8, field encoding: VARINT(0))
// 04 = PUSS_IN_BOOTS(4)
assertEquals("4004".decodeHex(), v1.unknownFields)
}
}
| wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/UnknownFieldsTest.kt | 6813457 |
/*
* Copyright 2020 Square 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.
*/
@file:JvmName("JsonUtils")
package com.squareup.wire.json
import com.squareup.moshi.JsonReader
import okio.Buffer
import org.assertj.core.api.Assertions.assertThat
fun assertJsonEquals(expected: String, value: String) {
assertThat(JsonReader.of(Buffer().writeUtf8(value)).readJsonValue())
.isEqualTo(JsonReader.of(Buffer().writeUtf8(expected)).readJsonValue())
}
| wire-library/wire-test-utils/src/main/java/com/squareup/wire/json/Json.kt | 2749639851 |
package net.treelzebub.zinepress.db.zines
import android.database.Cursor
import net.treelzebub.zinepress.db.IQuery
import net.treelzebub.zinepress.db.zines.ZineContentProvider
import net.treelzebub.zinepress.util.listAndClose
/**
* Created by Tre Murillo on 1/8/16
*/
class ZineQuery(override val parent: DbZines) : IQuery<IZine> {
override fun list(): List<DbZine> {
return cursor().listAndClose { DbZine(it) }
}
override fun cursor(): Cursor {
return parent.context.contentResolver
.query(parent.uri(),
null, null, null,
"${ZineCols.DATE} DESC")
}
override fun selection(): Pair<String, Array<String>> {
throw UnsupportedOperationException()
}
}
| app/src/main/java/net/treelzebub/zinepress/db/zines/ZineQuery.kt | 3569704621 |
package com.github.inventorywatcher.model
import com.fasterxml.jackson.annotation.JsonInclude
import io.vertx.codegen.annotations.DataObject
import io.vertx.core.json.Json
import io.vertx.core.json.JsonObject
import java.util.*
/**
* Created by hunyadym on 2016. 02. 17..
*/
@DataObject
@JsonInclude(JsonInclude.Include.NON_NULL)
data class Inventory constructor(var name: String?, var items: List<Item>?) : Validatable, JsonConvertable {
companion object Message {
val NAME_MUST_NOT_BE_NULL = "Name must not be null!"
}
constructor() : this(null, null)
constructor(inventory: Inventory) : this(inventory.name, inventory.items)
constructor(json: JsonObject) : this(Json.decodeValue(json.encode(), Inventory::class.java))
constructor(json: String) : this(Json.decodeValue(json, Inventory::class.java))
override fun validate(): List<String> {
val errors = ArrayList<String>()
if (items == null) {
errors.add(Inventory.NAME_MUST_NOT_BE_NULL)
}
return errors
}
override fun toJson(): JsonObject {
return JsonObject(this.toJsonString())
}
} | src/main/kotlin/com/github/inventorywatcher/model/Inventory.kt | 2922724356 |
package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class Links(
var self: String? = null,
var html: String? = null,
var photos: String? = null,
var likes: String? = null,
var portfolio: String? = null,
var download: String? = null,
@SerializedName("download_location") var downloadLocation: String? = null
) : Parcelable | androidunsplash/src/main/java/com/keenencharles/unsplash/models/Links.kt | 1150293109 |
package biz.eventually.atpl.utils
/**
* Created by Thibault de Lambilly on 19/06/2017.
*/
import android.content.Context
import android.preference.PreferenceManager
import biz.eventually.atpl.AtplApplication
import biz.eventually.atpl.R
object Prefields {
val PREF_TIMER_NBR: String = AtplApplication.get().getString(R.string.pref_timer_nbr)
val PREF_TIMER_ENABLE : String = AtplApplication.get().getString(R.string.pref_timer_enable)
val PREF_TOKEN : String = AtplApplication.get().getString(R.string.pref_token)
val PREF_LAST_DATA : String = AtplApplication.get().getString(R.string.pref_last_data)
}
fun prefsGetString(context: Context, key: String, defValue: String? = null) : String? {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getString(key, defValue)
}
fun prefsPutString(context: Context, key: String, value: String) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putString(key, value)
editor.apply()
}
fun prefsPutInt(context: Context, key: String, value: Int) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putInt(key, value)
editor.apply()
}
inline fun <reified T> prefsGetValue(key: String, defValue: T): T {
val pref = PreferenceManager.getDefaultSharedPreferences(AtplApplication.get())
return when(T::class) {
Int::class -> pref.getInt(key, defValue as Int) as T
String::class -> pref.getString(key, defValue as String) as T
Boolean::class -> pref.getBoolean(key, defValue as Boolean) as T
Long::class -> pref.getLong(key, defValue as Long) as T
else -> defValue
}
}
fun prefsPutBool(context: Context, key: String, defValue: Boolean): Boolean {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getBoolean(key, defValue)
}
fun getInt(context: Context, key: String, defValue: Int): Int {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getInt(key, defValue)
}
fun putInt(context: Context, key: String, value: Int) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putInt(key, value)
editor.apply()
}
fun getLong(context: Context, key: String, defValue: Long): Long {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getLong(key, defValue)
}
fun putLong(context: Context, key: String, value: Long) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putLong(key, value)
editor.apply()
}
fun exists(context: Context, key: String): Boolean {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.contains(key)
}
fun remove(context: Context, key: String) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.remove(key)
editor.apply()
} | app/src/main/java/biz/eventually/atpl/utils/PrefUtils.kt | 3313185013 |
package de.korovin.countries.persistence
import de.korovin.countries.models.Country
import org.springframework.context.annotation.Primary
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
/**
* Created by aw3s0 on 10/10/2017.
* CRUD repository for countries
* which accesses them by their short name
*/
@Repository
@Primary
@Transactional
interface CountryRepository : CrudRepository<Country, Long>
| server/src/main/kotlin/de/korovin/countries/persistence/CountryRepository.kt | 193543475 |
package jumpaku.othello.game
@ExperimentalUnsignedTypes
fun countBits(bits: ULong) = sequenceOf(0, 8, 16, 24, 32, 40, 48, 56)
.map { bitsCountTable[((bits shr it) and 0xffuL).toInt()] }.sum()
private val bitsCountTable = intArrayOf(
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
) | api/src/main/kotlin/jumpaku/othello/game/CountBits.kt | 929375579 |
/*
* 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.calcite.buildtools.fmpp
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.Configuration
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.kotlin.dsl.withGroovyBuilder
@CacheableTask
open class FmppTask @Inject constructor(
objectFactory: ObjectFactory
) : DefaultTask() {
@Classpath
val fmppClasspath = objectFactory.property<Configuration>()
.convention(project.configurations.named(FmppPlugin.FMPP_CLASSPATH_CONFIGURATION_NAME))
@InputFile
@PathSensitive(PathSensitivity.NONE)
val config = objectFactory.fileProperty()
@InputDirectory
@PathSensitive(PathSensitivity.RELATIVE)
val templates = objectFactory.directoryProperty()
@OutputDirectory
val output = objectFactory.directoryProperty()
.convention(project.layout.buildDirectory.dir("fmpp/$name"))
/**
* Path might contain spaces and TDD special characters, so it needs to be quoted.
* See http://fmpp.sourceforge.net/tdd.html
*/
private fun String.tddString() =
"\"${toString().replace("\\", "\\\\").replace("\"", "\\\"")}\""
@TaskAction
fun run() {
project.delete(output.asFileTree)
ant.withGroovyBuilder {
"taskdef"(
"name" to "fmpp",
"classname" to "fmpp.tools.AntTask",
"classpath" to fmppClasspath.get().asPath
)
"fmpp"(
"configuration" to config.get(),
"sourceRoot" to templates.get().asFile,
"outputRoot" to output.get().asFile,
"data" to "tdd(" + config.get().toString().tddString() + "), " +
"default: tdd(" + "${templates.get().asFile}/../default_config.fmpp".tddString() + ")"
)
}
}
}
| buildSrc/subprojects/fmpp/src/main/kotlin/org/apache/calcite/buildtools/fmpp/FmppTask.kt | 2316987829 |
package com.fsck.k9.notification
import com.fsck.k9.Account
internal object NotificationIds {
const val PUSH_NOTIFICATION_ID = 1
private const val NUMBER_OF_GENERAL_NOTIFICATIONS = 1
private const val OFFSET_SEND_FAILED_NOTIFICATION = 0
private const val OFFSET_CERTIFICATE_ERROR_INCOMING = 1
private const val OFFSET_CERTIFICATE_ERROR_OUTGOING = 2
private const val OFFSET_AUTHENTICATION_ERROR_INCOMING = 3
private const val OFFSET_AUTHENTICATION_ERROR_OUTGOING = 4
private const val OFFSET_FETCHING_MAIL = 5
private const val OFFSET_NEW_MAIL_SUMMARY = 6
private const val OFFSET_NEW_MAIL_SINGLE = 7
private const val NUMBER_OF_MISC_ACCOUNT_NOTIFICATIONS = 7
private const val NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS = MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS
private const val NUMBER_OF_NOTIFICATIONS_PER_ACCOUNT =
NUMBER_OF_MISC_ACCOUNT_NOTIFICATIONS + NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS
fun getNewMailSummaryNotificationId(account: Account): Int {
return getBaseNotificationId(account) + OFFSET_NEW_MAIL_SUMMARY
}
fun getSingleMessageNotificationId(account: Account, index: Int): Int {
require(index in 0 until NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS) { "Invalid index: $index" }
return getBaseNotificationId(account) + OFFSET_NEW_MAIL_SINGLE + index
}
fun getAllMessageNotificationIds(account: Account): List<Int> {
val singleMessageNotificationIdRange = (0 until NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS).map { index ->
getBaseNotificationId(account) + OFFSET_NEW_MAIL_SINGLE + index
}
return singleMessageNotificationIdRange.toList() + getNewMailSummaryNotificationId(account)
}
fun getFetchingMailNotificationId(account: Account): Int {
return getBaseNotificationId(account) + OFFSET_FETCHING_MAIL
}
fun getSendFailedNotificationId(account: Account): Int {
return getBaseNotificationId(account) + OFFSET_SEND_FAILED_NOTIFICATION
}
fun getCertificateErrorNotificationId(account: Account, incoming: Boolean): Int {
val offset = if (incoming) OFFSET_CERTIFICATE_ERROR_INCOMING else OFFSET_CERTIFICATE_ERROR_OUTGOING
return getBaseNotificationId(account) + offset
}
fun getAuthenticationErrorNotificationId(account: Account, incoming: Boolean): Int {
val offset = if (incoming) OFFSET_AUTHENTICATION_ERROR_INCOMING else OFFSET_AUTHENTICATION_ERROR_OUTGOING
return getBaseNotificationId(account) + offset
}
private fun getBaseNotificationId(account: Account): Int {
return 1 /* skip notification ID 0 */ + NUMBER_OF_GENERAL_NOTIFICATIONS +
account.accountNumber * NUMBER_OF_NOTIFICATIONS_PER_ACCOUNT
}
}
| app/core/src/main/java/com/fsck/k9/notification/NotificationIds.kt | 1371617510 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems") // KTIJ-19938
package com.intellij.lang.documentation.impl
import com.intellij.lang.documentation.*
import com.intellij.model.Pointer
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.readAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.AsyncSupplier
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
internal fun DocumentationTarget.documentationRequest(): DocumentationRequest {
ApplicationManager.getApplication().assertReadAccessAllowed()
return DocumentationRequest(createPointer(), presentation)
}
@ApiStatus.Internal
fun CoroutineScope.computeDocumentationAsync(targetPointer: Pointer<out DocumentationTarget>): Deferred<DocumentationResultData?> {
return async(Dispatchers.Default) {
computeDocumentation(targetPointer)
}
}
internal suspend fun computeDocumentation(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return withContext(Dispatchers.Default) {
val documentationResult: DocumentationResult? = readAction {
targetPointer.dereference()?.computeDocumentation()
}
@Suppress("REDUNDANT_ELSE_IN_WHEN")
when (documentationResult) {
is DocumentationResultData -> documentationResult
is AsyncDocumentation -> documentationResult.supplier.invoke() as DocumentationResultData?
null -> null
else -> error("Unexpected result: $documentationResult") // this fixes Kotlin incremental compilation
}
}
}
@ApiStatus.Internal
suspend fun handleLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult {
return withContext(Dispatchers.Default) {
tryResolveLink(targetPointer, url)
?: tryContentUpdater(targetPointer, url)
?: InternalLinkResult.CannotResolve
}
}
private suspend fun tryResolveLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return when (val resolveResult = resolveLink(targetPointer::dereference, url)) {
InternalResolveLinkResult.InvalidTarget -> InternalLinkResult.InvalidTarget
InternalResolveLinkResult.CannotResolve -> null
is InternalResolveLinkResult.Value -> InternalLinkResult.Request(resolveResult.value)
}
}
internal sealed class InternalResolveLinkResult<out X> {
object InvalidTarget : InternalResolveLinkResult<Nothing>()
object CannotResolve : InternalResolveLinkResult<Nothing>()
class Value<X>(val value: X) : InternalResolveLinkResult<X>()
}
internal suspend fun resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
): InternalResolveLinkResult<DocumentationRequest> {
return resolveLink(targetSupplier, url, DocumentationTarget::documentationRequest)
}
/**
* @param ram read action mapper - a function which would be applied to resolved [DocumentationTarget] while holding the read action
*/
internal suspend fun <X> resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val readActionResult = readAction {
resolveLinkInReadAction(targetSupplier, url, ram)
}
return when (readActionResult) {
is ResolveLinkInReadActionResult.Sync -> readActionResult.syncResult
is ResolveLinkInReadActionResult.Async -> asyncTarget(readActionResult.supplier, ram)
}
}
private suspend fun <X> asyncTarget(
supplier: AsyncSupplier<LinkResolveResult.Async?>,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val asyncLinkResolveResult: LinkResolveResult.Async? = supplier.invoke()
if (asyncLinkResolveResult == null) {
return InternalResolveLinkResult.CannotResolve
}
when (asyncLinkResolveResult) {
is AsyncResolvedTarget -> {
val pointer = asyncLinkResolveResult.pointer
return readAction {
val target: DocumentationTarget? = pointer.dereference()
if (target == null) {
InternalResolveLinkResult.InvalidTarget
}
else {
InternalResolveLinkResult.Value(ram(target))
}
}
}
else -> error("Unexpected result: $asyncLinkResolveResult")
}
}
private sealed class ResolveLinkInReadActionResult<out X> {
class Sync<X>(val syncResult: InternalResolveLinkResult<X>) : ResolveLinkInReadActionResult<X>()
class Async(val supplier: AsyncSupplier<LinkResolveResult.Async?>) : ResolveLinkInReadActionResult<Nothing>()
}
private fun <X> resolveLinkInReadAction(
targetSupplier: () -> DocumentationTarget?,
url: String,
m: (DocumentationTarget) -> X,
): ResolveLinkInReadActionResult<X> {
val documentationTarget = targetSupplier()
?: return ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.InvalidTarget)
@Suppress("REDUNDANT_ELSE_IN_WHEN")
return when (val linkResolveResult: LinkResolveResult? = resolveLink(documentationTarget, url)) {
null -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.CannotResolve)
is ResolvedTarget -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.Value(m(linkResolveResult.target)))
is AsyncLinkResolveResult -> ResolveLinkInReadActionResult.Async(linkResolveResult.supplier)
else -> error("Unexpected result: $linkResolveResult") // this fixes Kotlin incremental compilation
}
}
private fun resolveLink(target: DocumentationTarget, url: String): LinkResolveResult? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.resolveLink(target, url) ?: continue
}
return null
}
private suspend fun tryContentUpdater(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return readAction {
contentUpdaterInReadAction(targetPointer, url)
}
}
private fun contentUpdaterInReadAction(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
val target = targetPointer.dereference()
?: return InternalLinkResult.InvalidTarget
val updater = contentUpdater(target, url)
?: return null
return InternalLinkResult.Updater(updater)
}
private fun contentUpdater(target: DocumentationTarget, url: String): ContentUpdater? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.contentUpdater(target, url) ?: continue
}
return null
}
@TestOnly
fun computeDocumentationBlocking(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return runBlocking {
withTimeout(1000 * 60) {
computeDocumentation(targetPointer)
}
}
}
| platform/lang-impl/src/com/intellij/lang/documentation/impl/impl.kt | 2207880633 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.motion.visual
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString
class VisualToggleCharacterModeAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_READONLY
override fun execute(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments,
): Boolean {
val listOption = (
injector.optionService
.getOptionValue(OptionScope.LOCAL(editor), OptionConstants.selectmodeName) as VimString
).value
return if (listOption.contains("cmd")) {
injector.visualMotionGroup.enterSelectMode(editor, VimStateMachine.SubMode.VISUAL_CHARACTER)
} else injector.visualMotionGroup
.toggleVisual(editor, cmd.count, cmd.rawCount, VimStateMachine.SubMode.VISUAL_CHARACTER)
}
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/visual/VisualToggleCharacterModeAction.kt | 3915765139 |
package com.johnny.gank.adapter
/*
* Copyright (C) 2016 Johnny Shieh 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.
*/
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.johnny.gank.R
import com.johnny.gank.model.ui.GankNormalItem
import kotlinx.android.synthetic.main.pager_item_picture.view.*
/**
* description
*
* @author Johnny Shieh ([email protected])
* @version 1.0
*/
class PicturePagerAdapter : PagerAdapter() {
companion object {
const val ADD_FRONT = -1L
const val ADD_END = 1L
const val ADD_NONE = 0L
}
private val items = mutableListOf<GankNormalItem>()
fun initList(list: List<GankNormalItem>) {
items.addAll(list)
}
fun appendList(page: Int, list: List<GankNormalItem>): Long {
if (0 == count) return ADD_NONE
if (page == items[0].page - 1) {
items.addAll(0, list)
return ADD_FRONT
} else if (page == items.last().page + 1) {
items.addAll(items.size, list)
return ADD_END
}
return ADD_NONE
}
fun getItem(position: Int): GankNormalItem? {
if (position !in 0 until count) return null
return items[position]
}
override fun getCount(): Int {
return items.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = LayoutInflater.from(container.context).inflate(R.layout.pager_item_picture, container, false)
val item = items[position]
Glide.with(container.context)
.load(item.gank.url)
.apply(RequestOptions()
.dontAnimate()
.centerCrop()
).into(view.pic)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
if (`object` is View) container.removeView(`object`)
}
override fun getItemPosition(`object`: Any): Int {
return POSITION_NONE
}
}
| app/src/main/kotlin/com/johnny/gank/adapter/PicturePagerAdapter.kt | 894186843 |
package org.schabi.newpipe.local.subscription
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.xwray.groupie.Group
import io.reactivex.rxjava3.schedulers.Schedulers
import org.schabi.newpipe.local.feed.FeedDatabaseManager
import org.schabi.newpipe.local.subscription.item.ChannelItem
import org.schabi.newpipe.local.subscription.item.FeedGroupCardItem
import org.schabi.newpipe.util.DEFAULT_THROTTLE_TIMEOUT
import java.util.concurrent.TimeUnit
class SubscriptionViewModel(application: Application) : AndroidViewModel(application) {
private var feedDatabaseManager: FeedDatabaseManager = FeedDatabaseManager(application)
private var subscriptionManager = SubscriptionManager(application)
private val mutableStateLiveData = MutableLiveData<SubscriptionState>()
private val mutableFeedGroupsLiveData = MutableLiveData<List<Group>>()
val stateLiveData: LiveData<SubscriptionState> = mutableStateLiveData
val feedGroupsLiveData: LiveData<List<Group>> = mutableFeedGroupsLiveData
private var feedGroupItemsDisposable = feedDatabaseManager.groups()
.throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS)
.map { it.map(::FeedGroupCardItem) }
.subscribeOn(Schedulers.io())
.subscribe(
{ mutableFeedGroupsLiveData.postValue(it) },
{ mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) }
)
private var stateItemsDisposable = subscriptionManager.subscriptions()
.throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS)
.map { it.map { entity -> ChannelItem(entity.toChannelInfoItem(), entity.uid, ChannelItem.ItemVersion.MINI) } }
.subscribeOn(Schedulers.io())
.subscribe(
{ mutableStateLiveData.postValue(SubscriptionState.LoadedState(it)) },
{ mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) }
)
override fun onCleared() {
super.onCleared()
stateItemsDisposable.dispose()
feedGroupItemsDisposable.dispose()
}
sealed class SubscriptionState {
data class LoadedState(val subscriptions: List<Group>) : SubscriptionState()
data class ErrorState(val error: Throwable? = null) : SubscriptionState()
}
}
| app/src/main/java/org/schabi/newpipe/local/subscription/SubscriptionViewModel.kt | 3405893276 |
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.R.string
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.store.StatsStore.InsightType
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.NavigationTarget.SetBloggingReminders
import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemActionCard
import org.wordpress.android.ui.stats.refresh.utils.ActionCardHandler
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import javax.inject.Inject
import javax.inject.Named
class ActionCardReminderUseCase @Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher,
private val actionCardHandler: ActionCardHandler,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) : StatelessUseCase<Boolean>(InsightType.ACTION_REMINDER, mainDispatcher, backgroundDispatcher, listOf()) {
override suspend fun loadCachedData() = true
override suspend fun fetchRemoteData(forced: Boolean): State<Boolean> = State.Data(true)
override fun buildLoadingItem(): List<BlockListItem> = listOf()
override fun buildUiModel(domainModel: Boolean): List<BlockListItem> {
return listOf(
ListItemActionCard(
titleResource = string.stats_action_card_blogging_reminders_title,
text = string.stats_action_card_blogging_reminders_message,
positiveButtonText = string.stats_action_card_blogging_reminders_button_label,
positiveAction = ListItemInteraction.create(this::onSetReminders),
negativeButtonText = string.stats_management_dismiss_insights_news_card,
negativeAction = ListItemInteraction.create(this::onDismiss)
)
)
}
private fun onSetReminders() {
analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_ACTION_BLOGGING_REMINDERS_CONFIRMED)
navigateTo(SetBloggingReminders)
actionCardHandler.dismiss(InsightType.ACTION_REMINDER)
}
private fun onDismiss() {
analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_ACTION_BLOGGING_REMINDERS_DISMISSED)
actionCardHandler.dismiss(InsightType.ACTION_REMINDER)
}
}
| WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/ActionCardReminderUseCase.kt | 3023218575 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package org.jetbrains.builtInWebServer
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.net.InetAddresses
import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.Strings
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.*
import com.intellij.util.io.DigestUtil.randomToken
import com.intellij.util.net.NetUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.cookie.DefaultCookie
import io.netty.handler.codec.http.cookie.ServerCookieDecoder
import io.netty.handler.codec.http.cookie.ServerCookieEncoder
import org.jetbrains.ide.BuiltInServerBundle
import org.jetbrains.ide.BuiltInServerManagerImpl
import org.jetbrains.ide.HttpRequestHandler
import org.jetbrains.ide.orInSafeMode
import org.jetbrains.io.send
import java.awt.datatransfer.StringSelection
import java.io.IOException
import java.net.InetAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
internal val LOG = logger<BuiltInWebServer>()
private val notificationManager by lazy {
SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP, NotificationType.INFORMATION)
}
private val WEB_SERVER_PATH_HANDLER_EP_NAME = ExtensionPointName.create<WebServerPathHandler>("org.jetbrains.webServerPathHandler")
class BuiltInWebServer : HttpRequestHandler() {
override fun isAccessible(request: HttpRequest): Boolean {
return BuiltInServerOptions.getInstance().builtInServerAvailableExternally ||
request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true)
}
override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
var hostName = getHostName(request) ?: return false
val projectName: String?
val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']'
if (isIpv6) {
hostName = hostName.substring(1, hostName.length - 1)
}
if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) {
if (urlDecoder.path().length < 2) {
return false
}
projectName = null
}
else {
if (hostName.endsWith(".localhost")) {
projectName = hostName.substring(0, hostName.lastIndexOf('.'))
}
else {
projectName = hostName
}
}
return doProcess(urlDecoder, request, context, projectName)
}
}
internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false)
const val TOKEN_PARAM_NAME = "_ijt"
const val TOKEN_HEADER_NAME = "x-ijt"
private val STANDARD_COOKIE by lazy {
val productName = ApplicationNamesInfo.getInstance().lowercaseProductName
val configPath = PathManager.getConfigPath()
val file = Path.of(configPath, USER_WEB_TOKEN)
var token: String? = null
if (file.exists()) {
try {
token = UUID.fromString(file.readText()).toString()
}
catch (e: Exception) {
LOG.warn(e)
}
}
if (token == null) {
token = UUID.randomUUID().toString()
file.write(token!!)
Files.getFileAttributeView(file, PosixFileAttributeView::class.java)
?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE))
}
// explicit setting domain cookie on localhost doesn't work for chrome
// http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https
val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!)
cookie.isHttpOnly = true
cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10))
cookie.setPath("/")
cookie
}
// expire after access because we reuse tokens
private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>()
fun acquireToken(): String {
var token = tokens.asMap().keys.firstOrNull()
if (token == null) {
token = randomToken()
tokens.put(token, java.lang.Boolean.TRUE)
}
return token
}
private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean {
val decodedPath = urlDecoder.path()
var offset: Int
var isEmptyPath: Boolean
val isCustomHost = projectNameAsHost != null
var projectName: String
if (isCustomHost) {
projectName = projectNameAsHost!!
// host mapped to us
offset = 0
isEmptyPath = decodedPath.isEmpty()
}
else {
offset = decodedPath.indexOf('/', 1)
projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset)
isEmptyPath = offset == -1
}
val referer = request.headers().get(HttpHeaderNames.REFERER)
val projectNameFromReferer =
if (!isCustomHost && referer != null) {
try {
val uri = URI.create(referer)
val refererPath = uri.path
if (refererPath != null && refererPath.startsWith('/')) {
val secondSlashOffset = refererPath.indexOf('/', 1)
if (secondSlashOffset > 1) refererPath.substring(1, secondSlashOffset)
else null
}
else null
}
catch (t: Throwable) {
null
}
}
else null
var candidateByDirectoryName: Project? = null
var isCandidateFromReferer = false
val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean {
if (project.isDisposed) {
return false
}
val name = project.name
if (isCustomHost) {
// domain name is case-insensitive
if (projectName.equals(name, ignoreCase = true)) {
if (!SystemInfo.isFileSystemCaseSensitive) {
// may be passed path is not correct
projectName = name
}
return true
}
}
else {
// WEB-17839 Internal web server reports 404 when serving files from project with slashes in name
if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) {
val isEmptyPathCandidate = decodedPath.length == (name.length + 1)
if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') {
projectName = name
offset = name.length + 1
isEmptyPath = isEmptyPathCandidate
return true
}
}
}
if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) {
candidateByDirectoryName = project
}
if (candidateByDirectoryName == null &&
projectNameFromReferer != null &&
(projectNameFromReferer == name || compareNameAndProjectBasePath(projectNameFromReferer, project))) {
candidateByDirectoryName = project
isCandidateFromReferer = true
}
return false
}) ?: candidateByDirectoryName
if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) {
notificationManager.notify("", BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), project) { }
return false
}
if (isCandidateFromReferer) {
projectName = projectNameFromReferer!!
offset = 0
isEmptyPath = false
}
if (isEmptyPath) {
// we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work
redirectToDirectory(request, context.channel(), projectName, null)
return true
}
val path = toIdeaPath(decodedPath, offset)
if (path == null) {
HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request)
return true
}
for (pathHandler in WEB_SERVER_PATH_HANDLER_EP_NAME.extensionList) {
LOG.runAndLogException {
if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) {
return true
}
}
}
return false
}
fun HttpRequest.isSignedRequest(): Boolean {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return true
}
// we must check referrer - if html cached, browser will send request without query
val token = headers().get(TOKEN_HEADER_NAME)
?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull()
?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() }
// we don't invalidate token - allow making subsequent requests using it (it is required for our javadoc DocumentationComponent)
return token != null && tokens.getIfPresent(token) != null
}
private const val FAVICON_PATH = "favicon.ico"
fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return EmptyHttpHeaders.INSTANCE
}
request.headers().get(HttpHeaderNames.COOKIE)?.let {
for (cookie in ServerCookieDecoder.STRICT.decode(it)) {
if (cookie.name() == STANDARD_COOKIE.name()) {
if (cookie.value() == STANDARD_COOKIE.value()) {
return EmptyHttpHeaders.INSTANCE
}
break
}
}
}
if (isSignedRequest) {
return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict")
}
val urlDecoder = QueryStringDecoder(request.uri())
if (!urlDecoder.path().endsWith("/$FAVICON_PATH") && !urlDecoder.path().endsWith("/$FAVICON_PATH/")) {
val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}"
SwingUtilities.invokeAndWait {
ProjectUtil.focusProjectWindow(null, true)
if (MessageDialogBuilder
// escape - see https://youtrack.jetbrains.com/issue/IDEA-287428
.yesNo("", Strings.escapeXmlEntities(BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50))))
.icon(Messages.getWarningIcon())
.yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard"))
.guessWindowAndAsk()) {
CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken()))
}
}
}
HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return null
}
private fun toIdeaPath(decodedPath: String, offset: Int): String? {
// must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize
val path = decodedPath.substring(offset)
if (!path.startsWith('/')) {
return null
}
return FileUtil.toCanonicalPath(path, '/').substring(1)
}
fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean {
val basePath = project.basePath
return basePath != null && endsWithName(basePath, projectName)
}
fun findIndexFile(basedir: VirtualFile): VirtualFile? {
val children = basedir.children
if (children.isNullOrEmpty()) {
return null
}
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: VirtualFile? = null
val preferredName = indexNamePrefix + "html"
for (child in children) {
if (!child.isDirectory) {
val name = child.name
//noinspection IfStatementWithIdenticalBranches
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
fun findIndexFile(basedir: Path): Path? {
val children = basedir.directoryStreamIfExists({
val name = it.fileName.toString()
name.startsWith("index.") || name.startsWith("default.")
}) { it.toList() } ?: return null
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: Path? = null
val preferredName = "${indexNamePrefix}html"
for (child in children) {
if (!child.isDirectory()) {
val name = child.fileName.toString()
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
// is host loopback/any or network interface address (i.e. not custom domain)
// must be not used to check is host on local machine
internal fun isOwnHostName(host: String): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
try {
val address = InetAddress.getByName(host)
if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) {
return true
}
val localHostName = InetAddress.getLocalHost().hostName
// WEB-8889
// develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name)
return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true))
}
catch (ignored: IOException) {
return false
}
}
| platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt | 4094949285 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.ActivateToolWindowAction
import com.intellij.ide.actions.ToolWindowMoveAction
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.ScalableIcon
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID
import com.intellij.openapi.wm.impl.SquareStripeButton.Companion.createMoveGroup
import com.intellij.openapi.wm.safeToolWindowPaneId
import com.intellij.toolWindow.ToolWindowEventSource
import com.intellij.ui.MouseDragHelper
import com.intellij.ui.PopupHandler
import com.intellij.ui.ToggleActionButton
import com.intellij.ui.UIBundle
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import java.awt.Component
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Rectangle
import java.awt.event.MouseEvent
import java.util.function.Supplier
internal class SquareStripeButton(val toolWindow: ToolWindowImpl) :
ActionButton(SquareAnActionButton(toolWindow), createPresentation(toolWindow), ActionPlaces.TOOLWINDOW_TOOLBAR_BAR, Dimension(40, 40)) {
companion object {
fun createMoveGroup(toolWindow: ToolWindowImpl): DefaultActionGroup {
val result = DefaultActionGroup.createPopupGroup(Supplier { UIBundle.message("tool.window.new.stripe.move.to.action.group.name") })
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.LeftTop))
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.BottomLeft))
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.RightTop))
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.BottomRight))
return result
}
}
init {
setLook(SquareStripeButtonLook(this))
addMouseListener(object : PopupHandler() {
override fun invokePopup(component: Component, x: Int, y: Int) {
val popupMenu = ActionManager.getInstance()
.createActionPopupMenu(ActionPlaces.TOOLWINDOW_POPUP, createPopupGroup(toolWindow))
popupMenu.component.show(component, x, y)
}
})
MouseDragHelper.setComponentDraggable(this, true)
}
override fun updateUI() {
super.updateUI()
myPresentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(myPresentation)
myPresentation.isEnabledAndVisible = true
}
fun updatePresentation() {
updateToolTipText()
myPresentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(myPresentation)
}
fun isHovered() = myRollover
fun isFocused() = toolWindow.isActive
fun resetDrop() = resetMouseState()
fun paintDraggingButton(g: Graphics) {
val areaSize = size.also {
JBInsets.removeFrom(it, insets)
JBInsets.removeFrom(it, SquareStripeButtonLook.ICON_PADDING)
}
val rect = Rectangle(areaSize)
buttonLook.paintLookBackground(g, rect, JBUI.CurrentTheme.ActionButton.pressedBackground())
icon.let {
val x = (areaSize.width - it.iconWidth) / 2
val y = (areaSize.height - it.iconHeight) / 2
buttonLook.paintIcon(g, this, it, x, y)
}
buttonLook.paintLookBorder(g, rect, JBUI.CurrentTheme.ActionButton.pressedBorder())
}
override fun updateToolTipText() {
@Suppress("DialogTitleCapitalization")
HelpTooltip()
.setTitle(toolWindow.stripeTitle)
.setLocation(getAlignment(toolWindow.anchor, toolWindow.isSplitMode))
.setShortcut(ActionManager.getInstance().getKeyboardShortcut(ActivateToolWindowAction.getActionIdForToolWindow(toolWindow.id)))
.setInitialDelay(0)
.setHideDelay(0)
.installOn(this)
HelpTooltip.setMasterPopupOpenCondition(this) { !(parent as AbstractDroppableStripe).isDroppingButton() }
}
override fun checkSkipPressForEvent(e: MouseEvent) = e.button != MouseEvent.BUTTON1
}
private fun getAlignment(anchor: ToolWindowAnchor, splitMode: Boolean): HelpTooltip.Alignment {
return when (anchor) {
ToolWindowAnchor.RIGHT -> HelpTooltip.Alignment.LEFT
ToolWindowAnchor.TOP -> HelpTooltip.Alignment.LEFT
ToolWindowAnchor.LEFT -> HelpTooltip.Alignment.RIGHT
ToolWindowAnchor.BOTTOM -> if (splitMode) HelpTooltip.Alignment.LEFT else HelpTooltip.Alignment.RIGHT
else -> HelpTooltip.Alignment.RIGHT
}
}
private fun createPresentation(toolWindow: ToolWindowImpl): Presentation {
val presentation = Presentation(toolWindow.stripeTitle)
presentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(presentation)
presentation.isEnabledAndVisible = true
return presentation
}
private fun scaleIcon(presentation: Presentation) {
if (presentation.icon is ScalableIcon && presentation.icon.iconWidth != 20) {
presentation.icon = IconLoader.loadCustomVersionOrScale(presentation.icon as ScalableIcon, 20f)
}
}
private fun createPopupGroup(toolWindow: ToolWindowImpl): DefaultActionGroup {
val group = DefaultActionGroup()
group.add(HideAction(toolWindow))
group.addSeparator()
group.add(createMoveGroup(toolWindow))
return group
}
private class MoveToAction(private val toolWindow: ToolWindowImpl,
private val targetAnchor: ToolWindowMoveAction.Anchor) : AnAction(targetAnchor.toString()), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val toolWindowManager = toolWindow.toolWindowManager
val info = toolWindowManager.getLayout().getInfo(toolWindow.id)
toolWindowManager.setSideToolAndAnchor(id = toolWindow.id,
paneId = info?.safeToolWindowPaneId ?: WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID,
anchor = targetAnchor.anchor,
order = -1,
isSplit = targetAnchor.isSplit)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = targetAnchor.anchor != toolWindow.anchor || toolWindow.isSplitMode != targetAnchor.isSplit
}
}
private class HideAction(private val toolWindow: ToolWindowImpl)
: AnAction(UIBundle.message("tool.window.new.stripe.hide.action.name")), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
toolWindow.toolWindowManager.hideToolWindow(id = toolWindow.id,
hideSide = false,
moveFocus = true,
removeFromStripe = true,
source = ToolWindowEventSource.SquareStripeButton)
}
}
private class SquareAnActionButton(private val window: ToolWindowImpl) : ToggleActionButton(window.stripeTitle, null), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
e.presentation.icon = window.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(e.presentation)
return window.isVisible
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (e.project!!.isDisposed) {
return
}
val manager = window.toolWindowManager
if (state) {
manager.activated(window, ToolWindowEventSource.SquareStripeButton)
}
else {
manager.hideToolWindow(id = window.id,
hideSide = false,
moveFocus = true,
removeFromStripe = false,
source = ToolWindowEventSource.SquareStripeButton)
}
}
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/SquareStripeButton.kt | 3983015799 |
package org.snakeskin.component
/**
* Marker interface for a Talon SRX
*/
interface ITalonSrxDevice : IMotorControllerSmartComponent | SnakeSkin-CTRE/src/main/kotlin/org/snakeskin/component/ITalonSrxDevice.kt | 819869312 |
package i_introduction._10_Object_Expressions
import util.TODO
import util.doc10
import java.util.*
fun todoTask10(): Nothing = TODO(
"""
Task 10.
Read about object expressions that play the same role in Kotlin as anonymous classes in Java.
Add an object expression that provides a comparator to sort a list in a descending order using 'java.util.Collections' class.
In Kotlin you use Kotlin library extensions instead of java.util.Collections,
but this example is still a good demonstration of mixing Kotlin and Java code.
""",
documentation = doc10()
)
fun task10(): List<Int> {
val arrayList = arrayListOf(1, 5, 2)
Collections.sort(arrayList, object: Comparator<Int>{
//Check out the original solution. It is cleverer than this! =)
override fun compare(n1: Int,
n2: Int): Int {
if(n1 > n2) return -1
if(n1 < n2) return 1
return 0
}
})
return arrayList
}
| src/i_introduction/_10_Object_Expressions/n10ObjectExpressions.kt | 2221044401 |
class Foo {
companion object {
@JvmStatic
val ID = "123"
}
} | kotlin/Mastering-Kotlin-master/Chapter07/src/Foo.kt | 1919264386 |
package io.ipoli.android.common.view
import android.support.annotation.ColorRes
import io.ipoli.android.R
/**
* Created by Venelin Valkov <[email protected]>
* on 9/26/17.
*/
enum class AndroidColor(
@ColorRes val color100: Int,
@ColorRes val color200: Int,
@ColorRes val color300: Int,
@ColorRes val color400: Int,
@ColorRes val color500: Int,
@ColorRes val color600: Int,
@ColorRes val color700: Int,
@ColorRes val color800: Int,
@ColorRes val color900: Int
) {
RED(
R.color.md_red_100,
R.color.md_red_200,
R.color.md_red_300,
R.color.md_red_400,
R.color.md_red_500,
R.color.md_red_600,
R.color.md_red_700,
R.color.md_red_800,
R.color.md_red_900
),
GREEN(
R.color.md_green_100,
R.color.md_green_200,
R.color.md_green_300,
R.color.md_green_400,
R.color.md_green_500,
R.color.md_green_600,
R.color.md_green_700,
R.color.md_green_800,
R.color.md_green_900
),
BLUE(
R.color.md_blue_100,
R.color.md_blue_200,
R.color.md_blue_300,
R.color.md_blue_400,
R.color.md_blue_500,
R.color.md_blue_600,
R.color.md_blue_700,
R.color.md_blue_800,
R.color.md_blue_900
),
PURPLE(
R.color.md_purple_100,
R.color.md_purple_200,
R.color.md_purple_300,
R.color.md_purple_400,
R.color.md_purple_500,
R.color.md_purple_600,
R.color.md_purple_700,
R.color.md_purple_800,
R.color.md_purple_900
),
BROWN(
R.color.md_brown_100,
R.color.md_brown_200,
R.color.md_brown_300,
R.color.md_brown_400,
R.color.md_brown_500,
R.color.md_brown_600,
R.color.md_brown_700,
R.color.md_brown_800,
R.color.md_brown_900
),
ORANGE(
R.color.md_orange_100,
R.color.md_orange_200,
R.color.md_orange_300,
R.color.md_orange_400,
R.color.md_orange_500,
R.color.md_orange_600,
R.color.md_orange_700,
R.color.md_orange_800,
R.color.md_orange_900
),
PINK(
R.color.md_pink_100,
R.color.md_pink_200,
R.color.md_pink_300,
R.color.md_pink_400,
R.color.md_pink_500,
R.color.md_pink_600,
R.color.md_pink_700,
R.color.md_pink_800,
R.color.md_pink_900
),
TEAL(
R.color.md_teal_100,
R.color.md_teal_200,
R.color.md_teal_300,
R.color.md_teal_400,
R.color.md_teal_500,
R.color.md_teal_600,
R.color.md_teal_700,
R.color.md_teal_800,
R.color.md_teal_900
),
DEEP_ORANGE(
R.color.md_deep_orange_100,
R.color.md_deep_orange_200,
R.color.md_deep_orange_300,
R.color.md_deep_orange_400,
R.color.md_deep_orange_500,
R.color.md_deep_orange_600,
R.color.md_deep_orange_700,
R.color.md_deep_orange_800,
R.color.md_deep_orange_900
),
INDIGO(
R.color.md_indigo_100,
R.color.md_indigo_200,
R.color.md_indigo_300,
R.color.md_indigo_400,
R.color.md_indigo_500,
R.color.md_indigo_600,
R.color.md_indigo_700,
R.color.md_indigo_800,
R.color.md_indigo_900
),
BLUE_GREY(
R.color.md_blue_grey_100,
R.color.md_blue_grey_200,
R.color.md_blue_grey_300,
R.color.md_blue_grey_400,
R.color.md_blue_grey_500,
R.color.md_blue_grey_600,
R.color.md_blue_grey_700,
R.color.md_blue_grey_800,
R.color.md_blue_grey_900
),
LIME(
R.color.md_lime_100,
R.color.md_lime_200,
R.color.md_lime_300,
R.color.md_lime_400,
R.color.md_lime_600,
R.color.md_lime_700,
R.color.md_lime_800,
R.color.md_lime_800,
R.color.md_lime_900
);
} | app/src/main/java/io/ipoli/android/common/view/AndroidColor.kt | 3762009392 |
package com.meiji.daily.util
import android.content.Context
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.meiji.daily.BuildConfig
import com.meiji.daily.SdkManager
import com.meiji.daily.data.remote.IApi
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Meiji on 2017/12/28.
*/
@Singleton
class RetrofitHelper
@Inject
constructor(private val mContext: Context) {
/**
* 缓存机制
* 在响应请求之后在 data/data/<包名>/cache 下建立一个response 文件夹,保持缓存数据。
* 这样我们就可以在请求的时候,如果判断到没有网络,自动读取缓存的数据。
* 同样这也可以实现,在我们没有网络的情况下,重新打开App可以浏览的之前显示过的内容。
* 也就是:判断网络,有网络,则从网络获取,并保存到缓存中,无网络,则从缓存中获取。
* https://werb.github.io/2016/07/29/%E4%BD%BF%E7%94%A8Retrofit2+OkHttp3%E5%AE%9E%E7%8E%B0%E7%BC%93%E5%AD%98%E5%A4%84%E7%90%86/
</包名> */
private val cacheControlInterceptor = Interceptor { chain ->
var request = chain.request()
if (!NetWorkUtil.isNetworkConnected(mContext)) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build()
}
val originalResponse = chain.proceed(request)
if (NetWorkUtil.isNetworkConnected(mContext)) {
// 有网络时 设置缓存为默认值
val cacheControl = request.cacheControl().toString()
originalResponse.newBuilder()
.header("Cache-Control", cacheControl)
.removeHeader("Pragma") // 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.build()
} else {
// 无网络时 设置超时为1周
val maxStale = 60 * 60 * 24 * 7
originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.removeHeader("Pragma")
.build()
}
}
// 指定缓存路径,缓存大小 50Mb
// Cookie 持久化
// Log 拦截器
val retrofit: Retrofit
get() {
val cache = Cache(File(mContext.cacheDir, "HttpCache"),
(1024 * 1024 * 50).toLong())
val cookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(mContext))
var builder: OkHttpClient.Builder = OkHttpClient.Builder()
.cookieJar(cookieJar)
.cache(cache)
.addInterceptor(cacheControlInterceptor)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
if (BuildConfig.DEBUG) {
builder = SdkManager.initInterceptor(builder)
}
return Retrofit.Builder()
.baseUrl(IApi.API_BASE)
.client(builder.build())
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
}
| app/src/main/java/com/meiji/daily/util/RetrofitHelper.kt | 2948461150 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.