text
stringlengths 9
427k
|
|---|
package com.mobigod.statussaver.ui.splash
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.mobigod.statussaver.R
import com.mobigod.statussaver.data.local.PreferenceManager
import com.mobigod.statussaver.ui.saver.activity.StatusSaverActivity
import dagger.android.AndroidInjection
import javax.inject.Inject
class SplashActivity : AppCompatActivity() {
@Inject lateinit var preferenceManager: PreferenceManager
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
AndroidInjection.inject(this)
setContentView(R.layout.activity_splash)
Handler().postDelayed({
if (!preferenceManager.isFirstTime){
Intent(this, StatusDecisionActivity::class.java).also {
startActivity(it)
finish()
}
}
}, 2000)
}
}
|
package com.example.weather.data.di
import android.content.Context
import com.example.weather.data.remote.config.CacheControlInterceptor
import com.example.weather.data.remote.config.RetrofitConfig
import com.example.weather.data.remote.config.wrapresponse.WrapResponseAdapterFactory
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.Cache
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.CallAdapter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {
@Provides
internal fun provideRetrofit(
client: OkHttpClient,
factory: GsonConverterFactory,
wrapResponseFactory: CallAdapter.Factory
): Retrofit =
Retrofit.Builder()
.baseUrl("https://api.openweathermap.org")
.client(client)
.addConverterFactory(factory)
.addCallAdapterFactory(wrapResponseFactory)
.build()
@Provides
internal fun provideOkHttpClient(
certPinner: CertificatePinner,
cache: Cache,
cacheControlInterceptor: CacheControlInterceptor,
httpLoggingInterceptor: HttpLoggingInterceptor
): OkHttpClient {
return OkHttpClient.Builder()
.certificatePinner(certPinner)
.cache(cache)
.addInterceptor(cacheControlInterceptor)
.addInterceptor(httpLoggingInterceptor)
.build()
}
@Provides
internal fun provideAdapterFactory() : CallAdapter.Factory = WrapResponseAdapterFactory()
@Provides
internal fun provideCache(@ApplicationContext context: Context) =
RetrofitConfig.cache(context)
@Provides
internal fun provideCacheControlInterceptor(@ApplicationContext context: Context) =
RetrofitConfig.cacheControlInterceptor(context)
@Provides
internal fun provideHttpLoggingInterceptor() =
RetrofitConfig.httpLoggingInterceptor
@Provides
internal fun provideCertificatePinner() =
CertificatePinner.Builder()
.add("api.openweathermap.org", "sha256/axmGTWYycVN5oCjh3GJrxWVndLSZjypDO6evrHMwbXg=")
.add("api.openweathermap.org", "sha256/4a6cPehI7OG6cuDZka5NDZ7FR8a60d3auda+sKfg4Ng=")
.add("api.openweathermap.org", "sha256/x4QzPSC810K5/cMjb05Qm4k3Bw5zBn4lTdO/nEW/Td4=")
.build()
@Provides
@Singleton
fun provideGsonConverterFactory(): GsonConverterFactory {
return GsonConverterFactory.create(Gson())
}
}
|
package com.amaro.feature.list.plugin.mapper
import com.amaro.feature.list.domain.model.Item
import com.amaro.feature.list.domain.model.Owner
import com.amaro.libraries.core.domain.mapper.ListMapper
import com.amaro.libraries.networking.domain.model.ItemDTO
import com.amaro.libraries.networking.domain.model.OwnerDTO
class ItemDTOListMapper : ListMapper<ItemDTO, Item> {
override fun map(input: List<ItemDTO>): List<Item> {
return input.map {
Item(
it.id,
it.name,
toOwner(it.owner),
it.fullName,
it.starCount,
it.forksCount
)
}
}
private fun toOwner(ownerDTO: OwnerDTO): Owner {
return Owner(
ownerDTO.id,
ownerDTO.login,
ownerDTO.avatarUrl
)
}
}
|
package ru.flexo.glideapps.myquestions.myquestionsautorefresh
import org.openqa.selenium.By
import org.openqa.selenium.OutputType
import org.openqa.selenium.support.ui.ExpectedConditions
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.io.File
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
fun String.getLinks(): String? {
return Regex("https:\\/\\/glide.+").find(this)?.value
}
@Service
class MainService @Autowired constructor(
private val mail: EmailReceiver,
private val selenium: SeleniumProvider,
private val authenticationPage: AuthenticationPage,
private val myProjectPage: MyProjectPage,
private val projectsPage: ProjectsPage
) : NewMessageListener {
init {
var retry = true
while (retry)
try {
run2()
} catch (e: Exception) {
println("FATAL ERROR: retry")
}
}
private var actualDate = Date()
private var signInLink = ""
private fun startWaitSignInEmail() {
actualDate = Date()
signInLink = ""
}
private fun run2() {
mail.addNewMessageListener(this)
authenticationPage.open()
authenticationPage.loadingScreen.waitUntilHide()
while (true) {
if (myProjectPage.reloadButton.isDisplayed()) {
myProjectPage.reloadDb()
} else if(authenticationPage.googleSignInButton.isDisplayed()) {
// AUTHORIZE
authenticationPage.emailInput.click().sendKeys("flexoqa@yandex.ru")
startWaitSignInEmail()
authenticationPage.submit.click()
authenticationPage.tryAgainButton.waitUntilDisplayed()
mail.start()
authenticationPage.goto(signInLink)
projectsPage.myProjectCategory.click()
projectsPage.myProjectCard.click()
myProjectPage.loadingScreen.waitUntilHide()
while (myProjectPage.okTips.isDisplayed(1000)) {
myProjectPage.okTips.click()
}
myProjectPage.reloadDb()
} else {
myProjectPage.screenshot()
println("Something wrong, see screenshot")
}
Thread.sleep(300000)
}
}
private fun run() {
mail.addNewMessageListener(this)
selenium.execute(false) { driver, wait, selenium ->
val targetProject = By.xpath("//h3[contains(text(), 'My Questions')]")
val reloadButton = By.cssSelector("div.mini-action-reload")
val reloadSpin = By.cssSelector("div.mini-action-reload.spin")
val okTips = By.cssSelector("div.ts-ok-button")
val loading = By.cssSelector("div.oss-loading-overlay")
driver.navigate().to("https://go.glideapps.com/o/rKs3tuIy0nS5EYsoBhGH")
// Thread.sleep(5000)
selenium.waitLoading()
while (true) {
if (driver.findElements(reloadButton).isNotEmpty()){
// RELOAD
driver.findElement(reloadButton).click()
Thread.sleep(1000)
if (driver.findElements(reloadSpin).isNotEmpty()) {
println ("Reload Successful!!!")
} else {
println ("Something wrong! Cant reload!")
}
} else if (driver.findElements(By.xpath("//button[contains(text(), 'Sign up with Google')]")).isNotEmpty()) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".email-region > input")))
// AUTHORIZE
val emailInput = driver.findElementByCssSelector(".email-region > input")
val submit = driver.findElementByCssSelector("button.email-button")
startWaitSignInEmail()
emailInput.click()
emailInput.sendKeys("flexoqa@yandex.ru")
submit.click()
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(text(),'Try again')]")))
mail.start()
driver.navigate().to(signInLink)
selenium.waitLoading()
// NAVIGATE TO BUTTON
wait.until(ExpectedConditions.visibilityOfElementLocated(targetProject))
driver.findElement(targetProject).click()
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("My Questions")))
driver.findElementByName("My Questions").click()
// SPEND TIPS IF DISPLAYED
while (driver.findElements(okTips).isNotEmpty()) {
driver.findElement(okTips).click()
}
// RELOAD
val dataStep = By.cssSelector("div.data-step")
wait.until(ExpectedConditions.visibilityOfElementLocated(dataStep))
driver.findElement(reloadButton).click()
Thread.sleep(1000)
if (driver.findElements(reloadSpin).isNotEmpty()) {
println ("Reload Successful!!!")
} else {
println ("Something wrong! Cant reload!")
}
}
else {
val sc = driver.getScreenshotAs(OutputType.FILE)
val f = File("screens\\screen_error_${SimpleDateFormat("HHmmssddMMyyyy").format(Date())}.png")
f.createNewFile()
f.writeBytes(sc.readBytes())
println("Something wrong, see screenshot")
}
Thread.sleep(10000)
}
}
}
override fun onNewMessage(messages: List<GlideSignInMassage>) {
val mess = messages.lastOrNull { it.receivingDate >= actualDate }
mess?.let {
println("Found actual link from ${it.receivingDate}")
signInLink = it.link.getLinks()!! //TODO retry
mail.stop()
}
}
}
|
package com.codesroots.mac.cards.models
data class mazad(
val Result: List<Result>
)
|
package com.example.roomloginapp.ui.fragments
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.roomloginapp.R
class DashboardPage : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_dashboard_page, container, false)
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}
|
package com.gabrielribeiro.suacorrida.database
import androidx.lifecycle.LiveData
import androidx.room.*
import com.gabrielribeiro.suacorrida.model.Run
@Dao
interface RunDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRun(run : Run)
@Delete
suspend fun deleteRun(run: Run)
@Query("SELECT * FROM run_table ORDER BY timestamp DESC ")
fun getAllRunsSortedByDate() : LiveData<List<Run>>
@Query("SELECT * FROM run_table ORDER BY avgSpeedInKMH DESC ")
fun getAllRunsSortedByAvgSpeed() : LiveData<List<Run>>
@Query("SELECT * FROM run_table ORDER BY distanceInMeters DESC ")
fun getAllRunsSortedByDistanceInMeters() : LiveData<List<Run>>
@Query("SELECT * FROM run_table ORDER BY timeInMillis DESC ")
fun getAllRunsSortedByTimeInMillis() : LiveData<List<Run>>
@Query("SELECT * FROM run_table ORDER BY caloriesBurned DESC ")
fun getAllRunsSortedByCaloriesBurned() : LiveData<List<Run>>
@Query("SELECT SUM (timeInMillis) FROM run_table")
fun getTotalTimeMilliseconds() : LiveData<Long>
@Query("SELECT SUM (caloriesBurned) FROM run_table")
fun getTotalCaloriesBurned() : LiveData<Long>
@Query("SELECT SUM (distanceInMeters) FROM run_table")
fun getTotalDistanceInMeters() : LiveData<Long>
@Query("SELECT AVG (avgSpeedInKMH) FROM run_table")
fun getTotalAvgSpeed() : LiveData<Float>
}
|
package com.gw.zph.application
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.widget.Toast
import com.amap.api.location.AMapLocation
import com.cmic.sso.sdk.auth.AuthnHelper
import com.facebook.stetho.Stetho
import com.getkeepsafe.relinker.ReLinker
import com.gw.safty.common.UncaughtExceptionCatcher
import com.gw.zph.BuildConfig
import com.gw.zph.base.db.DbHelper
import com.gw.zph.core.network.RetrofitClient
import com.iflytek.cloud.SpeechConstant
import com.iflytek.cloud.SpeechUtility
import com.jeremyliao.liveeventbus.LiveEventBus
import com.qmuiteam.qmui.arch.QMUISwipeBackActivityManager
import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKVLogLevel
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import kiun.com.bvroutine.ActivityApplication
import kiun.com.bvroutine.handlers.ListHandler
import timber.log.Timber
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*
import kotlin.properties.Delegates
@SuppressLint("Registered")
class MyApplication : ActivityApplication(), Application.ActivityLifecycleCallbacks {
private var mFinalCount: Int = 0
private val activityList = LinkedList<Activity>()
private var mamapl: AMapLocation? = null
private var mAuthnHelper: AuthnHelper? = null
override fun onCreate() {
super.onCreate()
Instance = this
registerActivityLifecycleCallbacks(this)
Stetho.initializeWithDefaults(this)
RetrofitClient.setup(this)
setupTimber()
setupMmkv()
initSpeech()
initDb()
initUM()
initEventBus()
initQMUI()
initChinaMoble();
if (BuildConfig.DEBUG){
Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionCatcher())
}
}
private fun initChinaMoble(){
mAuthnHelper=AuthnHelper.getInstance(this)
}
private fun initEventBus() {
ListHandler.configNormal("系统发生错误,请下拉重试", "未找到相应信息", "正在为您查找数据")
//配置liveEventBus
LiveEventBus.get()
.config()
.supportBroadcast(this)
.lifecycleObserverAlwaysActive(true)
.autoClear(false)
}
private fun initQMUI(){
QMUISwipeBackActivityManager.init(this)
}
private fun initDb() {
//复制assets目录下的数据库文件到应用数据库中
// try {
// copyDataBase("dbtest.db")
// insertExternalDatabase(DbHelper.BASIC_PROBLEM_DB_NAME)
// } catch (e: Exception) {
// }
DbHelper.getInstance().initAddr(this) //初始化外部数据库
DbHelper.getInstance().init(this) //数据库初始化
}
private fun initUM(){
//设置LOG开关,默认为false
/**
* 初始化common库
* 参数1:上下文,不能为空
* 参数2:设备类型,UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子,默认为手机
* 参数3:Push推送业务的secret
*/
//设置LOG开关,默认为false
UMConfigure.setLogEnabled(true)
// PushHelper.init(this);
// UMConfigure.preInit()
UMConfigure.init(this, "613712695f3497702f2360ab", BuildConfig.BUILD_TYPE, UMConfigure.DEVICE_TYPE_PHONE, "")
// UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null)
// 选用LEGACY_AUTO页面采集模式
MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_AUTO)
}
companion object {
var Instance: MyApplication by Delegates.notNull()
const val LocationTest = true
}
private fun setupMmkv(){
val dir = filesDir.absolutePath + "/mmkv"
MMKV.initialize(dir) { ReLinker.loadLibrary(this@MyApplication, it) }
MMKV.setLogLevel(MMKVLogLevel.LevelInfo)
}
private fun setupTimber(){
if (BuildConfig.DEBUG){
Timber.plant(Timber.DebugTree())
}else {
Timber.plant()
}
}
/**
* 科大讯飞语音初始化
* */
private fun initSpeech(){
val param = StringBuffer()
param.append("appid=5f0d13df")
param.append(",")
// 设置使用v5+
param.append(SpeechConstant.ENGINE_MODE + "=" + SpeechConstant.MODE_MSC)
SpeechUtility.createUtility(this@MyApplication, param.toString())
}
fun finishAllActivities() {
activityList.forEach {
it.finish()
}
activityList.clear()
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
savedInstanceState?.let {
}
activityList.add(activity)
}
override fun onActivityStarted(activity: Activity) {
mFinalCount++
}
override fun onActivityDestroyed(activity: Activity) {
activityList.remove(activity)
}
override fun onActivityStopped(activity: Activity) {
mFinalCount--
if (mFinalCount <= 0) {
Toast.makeText(activity, "应用已进入后台运行", Toast.LENGTH_SHORT).show()
}
}
override fun onActivityResumed(activity: Activity) {
Timber.tag("打开").e("${activity.javaClass.canonicalName}")
}
override fun onActivityPaused(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
@Synchronized
fun getMamapl(): AMapLocation? {
return mamapl
}
@Synchronized
fun setMamapl(mamapl: AMapLocation?) {
this.mamapl = mamapl
}
@Throws(IOException::class)
private fun copyDataBase(dbname: String) {
// Open your local db as the input stream
val myInput = this.assets.open(dbname)
// Path to the just created empty db
val outFileName = getDatabasePath(DbHelper.DB_NAME_ADD)
if (!outFileName.exists()) {
outFileName.parentFile?.mkdirs()
// Open the empty db as the output stream
val myOutput: OutputStream = FileOutputStream(outFileName)
// transfer bytes from the inputfile to the outputfile
val buffer = ByteArray(1024)
var length: Int
while (myInput.read(buffer).also { length = it } > 0) {
myOutput.write(buffer, 0, length)
}
// Close the streams
myOutput.flush()
myOutput.close()
myInput.close()
}
}
private fun insertExternalDatabase(assetsFileName: String): Boolean {
var success = true
var `is`: InputStream? = null
var fos: FileOutputStream? = null
try {
val destDbFile = getDatabasePath(assetsFileName)
if (!destDbFile.exists()) {
destDbFile.parentFile?.mkdirs()
`is` = assets.open(assetsFileName)
fos = FileOutputStream(destDbFile)
val buffer = ByteArray(1024)
var length: Int
while (`is`.read(buffer).also { length = it } > 0) {
fos.write(buffer, 0, length)
}
success = true
}
} catch (e: java.lang.Exception) {
success = false
e.printStackTrace()
} finally {
try {
`is`?.close()
if (fos != null) {
fos.flush()
fos.close()
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}
return success
}
}
|
package com.name.name.musicappmvp.ui.main
import com.name.name.musicappmvp.data.model.Song
import com.name.name.musicappmvp.data.repository.LocalSongRepository
import com.name.name.musicappmvp.data.source.OnGotListCallback
import java.lang.Exception
class MainLocalMusicPresenter(
private val view: MainLocalMusicContract.View,
private val localSongRepository: LocalSongRepository
) :
MainLocalMusicContract.Presenter {
override fun getAllLocalSong() {
localSongRepository.getLocalSongs(object : OnGotListCallback {
override fun onSuccess(list: List<Song>) {
view.displayLocalSong(list)
}
override fun onFailure(exception: Exception) {
//showException()
}
})
}
override fun playChosenSong() {
view.setPauseButton()
}
override fun stopSongPlaying() {
view.setPlayButton()
}
}
|
package com.app.tf.livnlive
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import android.app.Activity
import android.R.attr.y
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Color
import android.support.constraint.ConstraintLayout
import android.support.constraint.ConstraintSet
import android.support.v7.app.AlertDialog
import android.widget.ImageView
import android.widget.Switch
import dmax.dialog.SpotsDialog
class SignupActivity : AppCompatActivity() {
private var mEmailField: EditText? = null
private var mPasswordField: EditText? = null
private var mConfirmPasswordField: EditText? = null
private var mAuth: FirebaseAuth? = null
var activityView: SpotsDialog? = null
var accepted:Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
adjustScreenSize()
mAuth = FirebaseAuth.getInstance()
mEmailField = findViewById<EditText>(R.id.email)
mPasswordField = findViewById<EditText>(R.id.password)
mConfirmPasswordField = findViewById<EditText>(R.id.ConfirmPwd)
activityView = SpotsDialog(this, R.style.Custom);
val mCLayout = findViewById(R.id.signup) as ConstraintLayout
val tncswitch = findViewById<Switch>(R.id.TncSwitch)
tncswitch.setOnClickListener{
if (accepted == true ){
accepted = false
}else{
accepted = true
}
}
Utility.setupUI(mCLayout,this)
}
fun createNewUser(view: View) {
if (!validateForm()) {
return
}
val email = mEmailField!!.text.toString()
val password = mPasswordField!!.text.toString()
activityView!!.show();
mAuth!!.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
activityView!!.hide();
if (task.isSuccessful) {
// Sign in: success
// update UI for current User
val user = mAuth!!.currentUser
FirebaseAuth.getInstance().signOut();
//updateUI(user)
// val prof = Intent(this, ProfileActivity::class.java)
// // Start the profile activity.
// startActivity(prof);
val builder = AlertDialog.Builder(this)
// Set the alert dialog title
builder.setTitle("")
// Display a message on alert dialog
builder.setMessage("Your account is created. Please login to continue")
// Set a positive button and its click listener on alert dialog
builder.setPositiveButton("Ok"){dialog, which ->
// Do something when user press the positive button
val login = Intent(this, MainActivity::class.java)
// Start the new activity.
startActivity(login)
finish()
}
val dialog: AlertDialog = builder.create()
// Display the alert dialog on app interface
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK)
} else {
// Sign in: fail
//Log.e(TAG, "signIn: Fail!", task.exception)
//updateUI(null)
val builder = AlertDialog.Builder(this)
// Set the alert dialog title
builder.setTitle("")
// Display a message on alert dialog
//builder.setMessage("The inputs are incorrect. Please try again!")
builder.setMessage(task.exception!!.message)
// Set a positive button and its click listener on alert dialog
builder.setPositiveButton("Ok"){dialog, which ->
// Do something when user press the positive button
}
val dialog: AlertDialog = builder.create()
// Display the alert dialog on app interface
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK)
}
}
}
fun openTnc(view: View) {
val tnc = Intent(this, TnCActivity::class.java)
startActivity(tnc);
}
private fun validateForm(): Boolean {
var valid = true
val email = mEmailField?.getText().toString()
if (TextUtils.isEmpty(email)) {
mEmailField?.setError("Required.")
valid = false
} else {
mEmailField?.setError(null)
}
val password = mPasswordField?.getText().toString()
if (TextUtils.isEmpty(password)) {
mPasswordField?.setError("Required.")
valid = false
} else {
mPasswordField?.setError(null)
}
val confirm = mConfirmPasswordField?.getText().toString()
if (TextUtils.isEmpty(password)) {
mConfirmPasswordField?.setError("Required.")
valid = false
} else {
mConfirmPasswordField?.setError(null)
}
if (password != confirm){
valid = false
mConfirmPasswordField?.setError("Did not match.")
}
if (accepted == false){
valid = false
val builder = AlertDialog.Builder(this)
// Set the alert dialog title
builder.setTitle("")
// Display a message on alert dialog
builder.setMessage("Please accept terms and condition.")
// Set a positive button and its click listener on alert dialog
builder.setPositiveButton("Ok"){dialog, which ->
}
val dialog: AlertDialog = builder.create()
// Display the alert dialog on app interface
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK)
}
return valid
}
fun goToLoginPage(view: View) {
val login = Intent(this, MainActivity::class.java)
// Start the new activity.
startActivity(login)
finish()
}
fun adjustScreenSize(){
val screenSize = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK
if ((screenSize == Configuration.SCREENLAYOUT_SIZE_SMALL ) || (screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL )){
var img = findViewById<ImageView>(R.id.signupimageView)
val lt = img.layoutParams
val layoutParams = ConstraintLayout.LayoutParams(lt.width*3/4, lt.height*3/4);
img.setLayoutParams(layoutParams);
val signup = findViewById(R.id.signup) as ConstraintLayout
val set = ConstraintSet()
set.clone(signup)
set.connect(img.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.connect(img.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0);
set.connect(img.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 20);
set.setHorizontalBias(img.getId(), 0.5F);
set.applyTo(signup)
}
}
}
|
package com.example.kar_o_bar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
class CarHostActivity : AppCompatActivity(), CarListFragment.ItemSelected {
private lateinit var carDescription : TextView
private lateinit var carDetails : ArrayList<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
carDescription = findViewById(R.id.carDescription)
carDetails = ArrayList()
carDetails.add(
"""Bayerische Motoren Werke AG, commonly referred to as BMW is a German multinational corporation which produces luxury vehicles and motorcycles. The company was founded in 1916 as a manufacturer of aircraft engines, which it produced from 1917 until 1918 and again from 1933 to 1945.
Automobiles are marketed under the brands BMW, Mini and Rolls-Royce, and motorcycles are marketed under the brand BMW Motorrad. """
)
carDetails.add(
"""Mercedes-Benz commonly referred to as Mercedes, is both a German automotive brand and, from late 2019 onwards, a subsidiary – as Mercedes-Benz AG – of Daimler AG.[1] Mercedes-Benz is known for producing luxury vehicles and commercial vehicles.
"""
)
carDetails.add("""Alfa Romeo Automobiles S.p.A. is an Italian premium car manufacturer and a subsidiary of Stellantis. The company was founded on June 24, 1910, in Milan, Italy. "Alfa" is an acronym of its founding name, "Anonima Lombarda Fabbrica Automobili." "Anonima" means "anonymous", which was a legal form of company at the time, as it was founded by anonymous investors.""")
carDetails.add("""Volkswagen, shortened to VW, is a German motor vehicle manufacturer founded in 1937 by the German Labour Front, known for the iconic Beetle and headquartered in Wolfsburg. It is the flagship brand of the Volkswagen Group, the largest car maker by worldwide sales in 2016 and 2017.[2] The group's biggest market is in China, which delivers 40% of its sales and profits.""")
carDetails.add("""Audi AG is a German automobile manufacturer that designs, engineers, produces, markets and distributes luxury vehicles. Audi is a subsidiary of Volkswagen Group and has its roots at Ingolstadt, Bavaria, Germany. Audi vehicles are produced in nine production facilities worldwide.""")
if (findViewById<View>(R.id.layout_default) != null) {
val manager = this.supportFragmentManager
manager.beginTransaction()
.hide(manager.findFragmentById(R.id.detailFrag)!!)
.show(manager.findFragmentById(R.id.listFrag)!!)
.commit()
}
if (findViewById<View>(R.id.layout_land) != null) {
val manager = this.supportFragmentManager
manager.beginTransaction()
.show(manager.findFragmentById(R.id.detailFrag)!!)
.show(manager.findFragmentById(R.id.listFrag)!!)
.addToBackStack(null)
.commit()
}
}
override fun onItemSelected(index: Int) {
if (findViewById<View>(R.id.layout_default) != null) {
val manager = this.supportFragmentManager
manager.beginTransaction()
.show(manager.findFragmentById(R.id.detailFrag)!!)
.hide(manager.findFragmentById(R.id.listFrag)!!)
.addToBackStack(null)
.commit()
}
carDescription.text = carDetails[index]
}
}
|
package com.helmi_18104036.klintung.data
import com.helmi_18104036.klintung.model.DataModel
object DataPenginapan{
private val title = arrayOf(
"Green Valley Resort",
"Hotel Teratai Putih",
"Atrium Resort Hotel",
"Queen Garden Hotel",
"RedDoorz Plus near UNSOED Purwokerto",
"Hotel Legen 2 Baturaden",
"laqosta farm",
"Purwosari guest house",
"Menggala Cottage",
"Hotel Puriwisata Baturraden"
)
private val image = arrayOf(
"https://media-cdn.tripadvisor.com/media/photo-s/09/ca/33/65/photo0jpg.jpg",
"https://cf.bstatic.com/images/hotel/max1024x768/240/240362729.jpg",
"https://cf.bstatic.com/images/hotel/max1024x768/257/257933657.jpg",
"https://media-cdn.tripadvisor.com/media/photo-s/0d/a9/6c/77/kolam-renang.jpg",
"https://cf.bstatic.com/images/hotel/max1024x768/231/231134215.jpg",
"https://origin.pegipegi.com/jalan/images/pictL/Y9/Y961689/Y961689003.jpg",
"https://cf.bstatic.com/images/hotel/max1024x768/260/260751965.jpg",
"https://cf.bstatic.com/images/hotel/max1024x768/261/261903447.jpg",
"https://static.tiket.photos/image/upload/t_htl-dskt/v1589851758/tix-hotel/images-web/2020/05/19/79897c8a-1df9-429c-ada7-b31985d111af-1589851757296-d41d8cd98f00b204e9800998ecf8427e.png",
"https://pix10.agoda.net/hotelImages/649/6492170/6492170_19012310280071597157.jpg"
)
private val description = arrayOf(
"Green Valley Resort adalah pilihan yang populer di kalangan wisatawan di Purwokerto, baik untuk menjelajahinya atau hanya sekedar transit. Hotel ini memiliki segala yang dibutuhkan untuk menginap dengan nyaman. Tempat parkir mobil, antar-jemput bandara, fasilitas rapat, restoran, layanan binatu (laundry) ada dalam daftar hal-hal yang para tamu dapat nikmati. Semua kamar dirancang dan didekorasi untuk membuat tamu merasa seperti di rumah dan beberapa kamar dilengkapi dengan televisi layar datar, AC, meja tulis, bar mini, balkon/teras. Hibur diri Anda dengan fasilitas rekreasi di hotel, termasuk kolam renang luar ruangan, taman. Suasana yang ramah dan pelayanan yang istimewa bisa Anda harapkan selama menginap di Green Valley Resort.",
"Terletak di Baturaden, 22 km dari Gunung Slamet, Hotel Teratai Putih memiliki lounge bersama, taman, dan teras. Akomodasi ini menyediakan resepsionis 24 jam dan layanan kamar untuk Anda.",
"Atrium Resort Hotel adalah pilihan yang populer di kalangan wisatawan di Purwokerto, baik untuk menjelajahinya atau hanya sekedar transit. Menawarkan berbagai fasilitas dan layanan, hotel menyediakan semua yang Anda butuhkan untuk bermalam dengan nyaman. Staf yang siap melayani akan menyambut dan memandu Anda di Atrium Resort Hotel. Bersantailah di kamar Anda yang nyaman dan beberapa kamar dilengkapi dengan fasilitas seperti televisi layar datar, akses internet WiFi (gratis), AC, layanan bangun pagi, meja tulis. Untuk meningkatkan kualitas pengalaman menginap para tamu, hotel ini menawarkan fasilitas rekreasi seperti kolam renang luar ruangan, taman. Dengan layanan handal dan staf profesional, Atrium Resort Hotel memenuhi kebutuhan Anda.",
"Terletak strategis di area Baturaden, Queen Garden Hotel menjanjikan kunjungan yang santai dan mengagumkan. Baik pebisnis maupun wisatawan, keduanya dapat menikmati fasilitas dan layanan dari properti ini. Layanan kamar 24 jam, WiFi gratis di semua kamar, Wi-fi di tempat umum, tempat parkir mobil, layanan kamar ada dalam daftar hal-hal yang dapat dinikmati oleh para tamu. Dirancang untuk memberikan kenyamanan, beberapa kamar memiliki televisi layar datar, akses internet WiFi (gratis), AC, layanan bangun pagi, meja tulis untuk memastikan kenyamanan istirahat malam Anda. Pulihkan diri Anda setelah berkeliling seharian dalam kenyamanan kamar Anda atau manfaatkan fasilitas seperti kolam renang luar ruangan, taman bermain anak, kolam renang anak, lapangan tenis, taman. Dengan layanan handal dan staf profesional, Queen Garden Hotel memenuhi kebutuhan Anda.",
"RedDoorz Plus near UNSOED Purwokerto terletak di Purwokerto, 18 km dari Owabong. Guest house ini menawarkan akomodasi dengan Wi-Fi gratis dan parkir pribadi gratis. Kamar-kamar di guest house ini dilengkapi dengan TV layar datar.",
"Hotel Legen 2 Baturaden berbintang 1 ini menawarkan kenyamanan kepada Anda baik untuk keperluan bisnis maupun berwisata di Purwokerto. Menawarkan berbagai fasilitas dan layanan, hotel menyediakan semua yang Anda butuhkan untuk bermalam dengan nyaman. Layanan kamar 24 jam, WiFi gratis di semua kamar, resepsionis 24 jam, check-in/check-out cepat, Wi-fi di tempat umum hanyalah beberapa dari berbagai fasilitas yang ditawarkan. Setiap kamar didesain dengan elegan dan dilengkapi dengan fasilitas yang berguna. Suasana tenang di hotel ini meluas hingga fasilitas rekreasinya yang meliputi taman. Dengan layanan handal dan staf profesional, Hotel Legen 2 Baturaden memenuhi kebutuhan Anda.",
"Laqosta farm terletak di Rempawah, dan menawarkan akomodasi dengan bar dan Wi-Fi gratis. Akomodasi ini menyajikan sarapan prasmanan setiap hari. Anda dapat bersantai di taman akomodasi. Holiday park ini berjarak 6 km dari Baturaden dan Purwokerto.",
"Purwosari guest house di Banyumas menawarkan akomodasi dengan teras dan pemandangan taman. Setiap unit menawarkan dapur lengkap, TV layar datar, ruang bersama, kamar mandi pribadi, dan mesin cuci.",
"Menggala Cottage terletak di Wangon dan memiliki restoran, lounge bersama, taman, dan teras. Akomodasi ini menawarkan resepsionis 24 jam dan layanan kamar. Kamar-kamar di hotel ini memiliki meja kerja, TV, dan kamar mandi pribadi.",
"Selain restoran, bed & breakfast ini juga menawarkan resepsionis 24 jam dan WiFi gratis di area umum."
)
private val lat = arrayOf(
"-7.3375753",
"7.3248299",
"-7.4521482",
"-7.3123891",
"-7.3805715",
"-2.4762576",
"-7.3693205",
"-7.3650426",
"-7.3160675",
"-7.3235681"
)
private val lang = arrayOf(
"109.2291336",
"109.2261168",
"109.2794371",
"109.2358833",
"109.2489156",
"108.9646441",
"109.2315791",
"110.3128586",
"109.2369295",
"109.2260361"
)
val listData:ArrayList<DataModel> get(){
var list = arrayListOf<DataModel>()
for (position in title.indices){
val data = DataModel(title[position],image[position],description[position],lat[position],
lang[position])
list.add(data)
}
return list
}
}
|
@file:Suppress("UNUSED_VARIABLE")
package esw.ocs.scripts.examples.paradox
import csw.params.events.Event
import csw.params.events.EventKey
import csw.params.events.ObserveEvent
import csw.params.events.SystemEvent
import esw.ocs.dsl.core.script
import esw.ocs.dsl.epics.EventVariable
import esw.ocs.dsl.epics.ParamVariable
import esw.ocs.dsl.highlevel.models.ObsId
import esw.ocs.dsl.params.intKey
import kotlin.time.Duration.Companion.seconds
script {
onSetup("publish-event") {
//#system-event
val parameters = intKey("stepNumber").set(1)
//#publish
val systemEvent: SystemEvent = SystemEvent("ESW.IRIS_darkNight", "stepInfo", parameters)
//#publish
//#system-event
//#observe-event
val observeEvent: ObserveEvent = observationStart(ObsId("2020A-001-123"))
//#observe-event
//#publish
publishEvent(systemEvent)
//#publish
//#subscribe
//#get-event
val tempEventKey = "IRIS.env.temperature.temp"
val stateEventKey = "IRIS.env.temperature.state"
//#get-event
onEvent(tempEventKey, stateEventKey) { event ->
// logic to execute on every event
println(event.eventKey())
}
//#subscribe
//#subscribe-async
onEvent(tempEventKey, stateEventKey, duration = 2.seconds) { event ->
// logic to execute on every event
println(event.eventKey())
}
//#subscribe-async
fun getTemperature(): Int = TODO()
//#publish-async
publishEvent(10.seconds) {
val temperatureKey = intKey("temperature").set(getTemperature())
SystemEvent("ESW.IRIS_darkNight", "temperature", temperatureKey)
}
//#publish-async
//#get-event
val event = getEvent(tempEventKey) // for single event key
val events: Set<Event> = getEvent(tempEventKey, stateEventKey) // for single event key
//#get-event
//#event-key
// full event key string
val tempKey: EventKey = EventKey("ESW.temperature.temp")
// prefix and event name strings
val tempKey1: EventKey = EventKey("ESW.temperature", "temp")
//#event-key
//#event-var
val eventVariable: EventVariable = EventVariable("ESW.temperature.temp")
//#event-var
//#param-var
val locKey = intKey("current-location")
val paramVariable: ParamVariable<Int> = ParamVariable(0, "IRIS.ifs.motor.position", locKey)
//#param-var
}
}
|
package leakcanary
import leakcanary.internal.InternalLeakCanary
object LeakCanary {
data class Config(
val dumpHeap: Boolean = true,
val excludedRefs: ExcludedRefs = AndroidExcludedRefs.createAppDefaults().build(),
val reachabilityInspectorClasses: List<Class<out Reachability.Inspector>> = AndroidReachabilityInspectors.defaultAndroidInspectors(),
val labelers: List<Labeler> = AndroidLabelers.defaultAndroidLabelers(
InternalLeakCanary.application
),
/**
* Note: this is currently not implemented in the new heap parser.
*/
val computeRetainedHeapSize: Boolean = false
)
@Volatile
var config: Config = Config()
}
|
package cn.ifafu.ifafu.ui.main.old_theme.scorepreview
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import cn.ifafu.ifafu.databinding.MainOldScorePreviewFragmentBinding
import cn.ifafu.ifafu.ui.score.ScoreActivity
import cn.ifafu.ifafu.util.setDeBoundClickListener
import cn.ifafu.ifafu.ui.common.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ScorePreviewFragment : BaseFragment() {
private val mViewModel: ScorePreviewViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = MainOldScorePreviewFragmentBinding
.inflate(inflater, container, false).apply {
this.lifecycleOwner = viewLifecycleOwner
this.viewModel = mViewModel
this.root.setDeBoundClickListener(1000) {
startActivity(Intent(context, ScoreActivity::class.java))
}
}
return binding.root
}
fun refresh() {
mViewModel.refresh()
}
}
|
package me.earth.headlessforge.api.command
/**
* A CommandManager that can register Commands
* and execute messages.
*/
interface ICommandManager {
/** Finds a Command for the given String and executes it. */
fun execute(msg: String)
/**
* Add a command that will always be executed first when the execute method is called.
* Useful for stuff like Yes/No questions.
*/
fun addCallback(callback: ICommand)
/** Attempts to get an added command with the given name. */
fun get(name: String): ICommand?
/** Adds a command. */
fun add(command: ICommand)
/** Removes a command. */
fun remove(command: ICommand)
/** Returns a mutable collection of all added commands. */
fun getCommands(): Collection<ICommand>
}
|
package com.example.mahmoud_ashraf.tvshow.models
import android.arch.lifecycle.LiveData
import android.arch.paging.PagedList
data class TvShowsResult(
val data: LiveData<PagedList<Result>>,
val networkStatus: LiveData<NetworkStatus>,
val initialStatus: LiveData<NetworkStatus>
)
|
package se.transport.taxilon
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import spencerstudios.com.bungeelib.Bungee
class FaqActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_faq)
setupActionBar()
}
override fun onBackPressed() {
super.onBackPressed()
Bungee.slideRight(this)
}
private fun setupActionBar(){
val toolBar = findViewById<Toolbar>(R.id.app_bar) as Toolbar
toolBar.title=""
setSupportActionBar(toolBar)
val tvToolBar = findViewById<TextView>(R.id.tvToolbarTitle) as TextView
tvToolBar.text = getString(R.string.faqButtonString)
toolBar.setPadding(0, 0, 0, 0)//for tab otherwise give space in tab
toolBar.setContentInsetsAbsolute(0, 0)
}
fun backButton(v: View) {
onBackPressed()
Bungee.slideRight(this)
}
}
|
package com.easy.skin.utils
import android.content.Context
/**
* 工具类
* @author 李轩林
*/
internal object SkinThemeUtils {
fun getResId(context: Context, attrs: IntArray): IntArray {
val resIds = IntArray(attrs.size)
val ta = context.obtainStyledAttributes(attrs)
for (i in attrs.indices) {
resIds[i] = ta.getResourceId(i, 0)
}
ta.recycle()
return resIds
}
}
|
@file:JvmName("ExtensionsUtils")
package co.flickr.client.util
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.LiveDataReactiveStreams
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.support.v4.app.FragmentActivity
import co.flickr.client.app.presentation.ViewModelFactory
import org.reactivestreams.Publisher
fun <T> unsafeLazy(initializer: () -> T) = lazy(LazyThreadSafetyMode.NONE, initializer)
fun <T> Publisher<T>.toLiveData(): LiveData<T> = LiveDataReactiveStreams.fromPublisher(this)
inline fun <reified T : ViewModel> FragmentActivity.getViewModel(): T = ViewModelProviders.of(this, ViewModelFactory).get(T::class.java)
|
package com.egoriku.radiotok.datasource.intertal.datasource.playlist
import android.content.Context
import com.egoriku.radiotok.common.ext.logD
import com.egoriku.radiotok.common.ext.telephonyManager
import com.egoriku.radiotok.datasource.datasource.playlist.ILocalStationsDataSource
import com.egoriku.radiotok.datasource.entity.RadioEntity
import com.egoriku.radiotok.datasource.intertal.api.Api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal class LocalStationsDataSource(
context: Context,
private val api: Api
) : ILocalStationsDataSource {
private val telephonyManager = context.telephonyManager
private var result: List<RadioEntity>? = null
override suspend fun load(): List<RadioEntity> {
val countryCode = getCountryCode()
return when {
countryCode.isNullOrEmpty() -> emptyList()
else -> runCatching {
withContext(Dispatchers.IO) {
result ?: api.byCountyCode(countryCode = countryCode).also {
result = it
}
}
}.getOrDefault(emptyList())
}
}
private fun getCountryCode(): String? {
var countryCode = telephonyManager.networkCountryIso
if (countryCode == null) {
countryCode = telephonyManager.simCountryIso
}
return when {
countryCode != null -> {
if (countryCode.length == 2) {
logD("countrycode: $countryCode")
countryCode
} else {
logD("countrycode length != 2")
null
}
}
else -> {
logD("device countrycode and sim countrycode are null")
null
}
}
}
}
|
package com.home.kotlincoroutinesdemo.albums.model.remote
class ApiAlbumsHelperImpl(
private val apiService: ApiAlbumsService
) : ApiAlbumsHelper {
override suspend fun getAlbums() = apiService.getAlbums()
}
|
package com.awesome.zach.projectolympus
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
class NotesAdapter(private val mNotesList: List<Note>): RecyclerView.Adapter<NotesViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder {
val inflatedView = parent.inflate(R.layout.list_row, false)
return NotesViewHolder(inflatedView)
}
override fun getItemCount() = mNotesList.size
override fun onBindViewHolder(holder: NotesViewHolder, position: Int) {
// val note = mNotesList[position]
// holder.title.text = note.title
// holder.content.text = note.content
val itemNote = mNotesList[position]
holder.bindNote(itemNote)
}
}
|
package com.br.nextpage.data.dataSource
interface BookLocalDataSource {
// to do
}
|
package com.ikey.launch
import android.content.res.TypedArray
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.ikey.R
import com.ikey.databinding.ActivityTutorialBinding
import com.ikey.enums.NavigationFrom
import com.ikey.launch.adapter.TutorialAdapter
import com.ikey.launch.model.TutorialModel
import com.ikey.launch.viewmodel.TutorialVM
import com.ikey.util.StatusBarUtil
class TutorialActivity : AppCompatActivity() {
lateinit var binding: ActivityTutorialBinding
lateinit var tutorialVM: TutorialVM
var adapter : TutorialAdapter ? = null
var navigationFrom = NavigationFrom.NONE
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
StatusBarUtil.setLightMode(this@TutorialActivity)
getIntentData()
bindView()
viewPagerSetup()
}
private fun getIntentData(){
var bundle = intent.extras
if (bundle!=null){
if (bundle.getSerializable("navigationFrom") is NavigationFrom) {
navigationFrom = bundle.getSerializable("navigationFrom") as NavigationFrom
}
}
}
private fun bindView(){
binding = DataBindingUtil.setContentView(this@TutorialActivity,R.layout.activity_tutorial)
tutorialVM = TutorialVM(this@TutorialActivity)
binding.tutorialVM = tutorialVM
}
private fun viewPagerSetup(){
adapter = TutorialAdapter(this@TutorialActivity,tutorialData())
binding.viewpager.adapter = adapter
binding.circleIndicator.setViewPager(binding.viewpager)
}
private fun tutorialData(): ArrayList<TutorialModel>{
val images : TypedArray = resources.obtainTypedArray(R.array.tutorial_image_array)
val description = resources .getStringArray(R.array.tutorial_description_array)
val data = arrayListOf<TutorialModel>()
for (position in description.indices){
data.add(TutorialModel(description[position],images.getDrawable(position)))
}
return data
}
}
|
package com.example.githubapitask.view.main
import android.app.Application
import android.util.Log
import androidx.paging.PagedList
import com.example.githubapitask.model.entity.UserModel
import com.example.githubapitask.view.BaseViewModel
import io.reactivex.observers.DisposableObserver
import io.reactivex.subjects.PublishSubject
class MainViewModel(application: Application) : BaseViewModel(application) {
private val tag = this::class.java.simpleName
val usersSubject = PublishSubject.create<PagedList<UserModel>>()
val usersDataSourceEventSubject = PublishSubject.create<DataSourceEvent>()
init {
Log.d(tag, "init")
}
fun search(query: String) {
Log.d(tag, "search - $query")
val usersPageList =
UsersDataSource.createPagedList(disposables, usersDataSourceEventSubject, query)
showProgressBar()
disposables.add(
usersPageList.subscribeWith(object : DisposableObserver<PagedList<UserModel>>() {
override fun onComplete() {
Log.d(tag, "fetchPages.onComplete")
}
override fun onNext(pagedUserList: PagedList<UserModel>) {
usersSubject.onNext(pagedUserList)
}
override fun onError(error: Throwable) {
Log.e(tag, "fetchPages.onError - onError: $error")
}
})
)
}
}
|
package com.vaibhavdhunde.app.elearning.data.source.remote
import com.google.common.truth.Truth.assertThat
import com.vaibhavdhunde.app.elearning.api.FakeElearningApi
import com.vaibhavdhunde.app.elearning.data.FeedbacksRemoteDataSource
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
/**
* Tests for implementing [FeedbacksRemoteDataSource].
*/
class FeedbacksRemoteDataSourceTest {
// SUT
private lateinit var feedbacksRemoteDataSource: FeedbacksRemoteDataSource
// Use fake api for testing
private lateinit var api: FakeElearningApi
@Before
fun setUp() {
api = FakeElearningApi()
feedbacksRemoteDataSource = IFeedbacksRemoteDataSource(api)
}
@Test
fun addFeedback_success() = runBlocking {
// WHEN - adding feedback
val response = feedbacksRemoteDataSource.addFeedback("", "")
// THEN - verify that the response has expected values
assertThat(response.error).isFalse()
assertThat(response.message).isNotNull()
}
@Test
fun addFeedback_error() = runBlocking {
// GIVEN - api returns error
api.setShouldReturnError(true)
// WHEN - adding feedback
val response = feedbacksRemoteDataSource.addFeedback("", "")
// THEN - verify that the response has expected values
assertThat(response.error).isTrue()
assertThat(response.message).isNotNull()
}
}
|
package shared
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
fun main() = runBlocking<Unit> {
val counterContext = newSingleThreadContext("CounterContext")
var counter = 0
//sampleStart
CoroutineScope(counterContext).massiveRun { // run each coroutine in the single-threaded context
counter++
}
println("Counter = $counter")
//sampleEnd
}
|
package com.coeater.android.api
import com.coeater.android.model.FriendsInfo
import com.coeater.android.model.User
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.http.*
import java.io.File
interface UserApi {
@GET("users/friend/")
suspend fun getFriends(): FriendsInfo
@GET("users/friend/wait/")
suspend fun getFriendRequests(): FriendsInfo
@FormUrlEncoded
@POST("users/friend/")
suspend fun inviteFriend(
@Field("code") code : String
): User
@FormUrlEncoded
@POST("users/friend/")
suspend fun inviteFriend(
@Field("id") id : Int
): User
@FormUrlEncoded
@PUT("users/friend/")
suspend fun rejectFriend(
@Field("id") id : Int
): Unit
@FormUrlEncoded
@PUT("users/{id}/")
suspend fun setNickname(
@Path("id") id : Int,
@Field("nickname") nickname : String
): User
@Multipart
@PUT("users/{id}/")
suspend fun setProfile(
@Path("id") id : Int,
@Part("nickname") nickname: RequestBody,
@Part profile: MultipartBody.Part?
): User
}
|
package com.motional.rubiksquare
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil.setContentView
import androidx.fragment.app.DialogFragment
import com.motional.rubiksquare.databinding.ActivityMainBinding
import com.motional.rubiksquare.viewmodels.RubikSquareViewModel
class MainActivity : AppCompatActivity(), CompletionDialogFragment.DialogListener {
private val viewModel: RubikSquareViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView<ActivityMainBinding>(this, R.layout.activity_main).apply {
this.viewModel = this@MainActivity.viewModel
lifecycleOwner = this@MainActivity
setClickListener {
if (viewModel?.numPlayers?.value == 1) {
addPlayerTwo()
} else {
removePlayerTwo()
}
}
setSupportActionBar(this.toolbar)
}
subscribeUi()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_reset -> {
viewModel.resetCells()
true
}
R.id.action_end_game -> {
viewModel.endGame()
true
}
else -> super.onOptionsItemSelected(item)
}
private fun addPlayerTwo() {
val secondFragment = SecondFragment()
supportFragmentManager.beginTransaction()
.add(R.id.second_fragment, secondFragment)
.commit()
viewModel.numPlayers.value = 2
}
private fun removePlayerTwo() {
val secondFragment = supportFragmentManager.findFragmentById(R.id.second_fragment)
supportFragmentManager.beginTransaction()
.remove(secondFragment!!)
.commit()
viewModel.numPlayers.value = 1
}
private fun showCongratulationsDialog() {
if (supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) == null) {
val dialog = CompletionDialogFragment()
dialog.show(supportFragmentManager, FRAGMENT_TAG)
}
}
override fun onDialogPositiveClick(dialog: DialogFragment) {
viewModel.resetCells()
}
private fun subscribeUi() {
viewModel.numPlayers.observe(this) { num ->
viewModel.whichPlayerTurn.value = num
}
viewModel.cellsFirstPlayer.observe(this) {
if (viewModel.isGoalReached()) showCongratulationsDialog()
}
}
}
|
/*
* Copyright (c) 2016. Sunghyouk Bae <sunghyouk.bae@gmail.com>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.data.ignite.examples
import debop4k.core.collections.parForEach
import debop4k.core.uninitialized
import debop4k.core.utils.parallelStream
import debop4k.core.utils.use
import debop4k.data.ignite.AbstractIgniteTest
import debop4k.data.ignite.getCache
import org.apache.ignite.Ignite
import org.apache.ignite.Ignition
import org.apache.ignite.configuration.IgniteConfiguration
import org.apache.ignite.lang.IgniteCallable
import org.assertj.core.api.Assertions.assertThat
import org.junit.*
import java.util.*
class SimpleExample : AbstractIgniteTest() {
companion object {
@JvmField var ignite: Ignite = uninitialized()
@BeforeClass
@JvmStatic
fun setupClass() {
ignite = Ignition.getOrStart(IgniteConfiguration())
}
@AfterClass
@JvmStatic
fun cleanupClass() {
ignite.close()
}
}
@Test
fun testConfiguration() {
ignite.getCache<String, String?>("default").use { cache ->
cache.put("a", "abc")
cache.putIfAbsent("b", "b")
val b = cache.getAndPutIfAbsent("b", "not exists")
assertThat(b).isEqualTo("b")
assertThat(cache.get("b")).isEqualTo("b")
log.debug("cache matrics = {}", cache.metrics())
}
}
@Test
fun testCompute() {
val calls = ArrayList<IgniteCallable<Int>>()
// Iterate through all the words in the sentence and create Callable jobs.
"Count characters using callable".split(" ").forEach { word ->
calls.add(IgniteCallable { word.length })
}
// Execute collection of Callables on the grid.
val res = ignite.compute().call(calls)
// Add up all the results.
val sum = res.map { it }.sum()
log.debug("Total number of characters is '{}'.", sum)
assertThat(sum).isEqualTo(28)
}
@Test fun testCachePutAndGet() {
val range = 0..100
ignite.getCache<Int, String>("dataGrid").use { cache ->
// Store keys in cache (values will end up on different cache nodes).
range.forEach {
cache.put(it, it.toString())
}
range.forEach {
log.trace("\tGot [key=$it, value=${cache.get(it)}]")
assertThat(it).isEqualTo(cache.get(it).toInt())
}
}
}
@Test
fun testCachePutAndGetAsParallel() {
val range = 0..100
ignite.getCache<Int, String>("dataGrid").use { cache ->
// Store keys in cache (values will end up on different cache nodes).
range.parForEach {
cache.put(it, it.toString())
}
range.parForEach {
log.trace("\tGot [key=$it, value=${cache.get(it)}]")
assertThat(it).isEqualTo(cache.get(it).toInt())
}
}
}
@Test
fun testCachePutAndGetJavaParallel() {
val range = 0..100
ignite.getCache<Int, String>("dataGrid").use { cache ->
// Store keys in cache (values will end up on different cache nodes).
range.parallelStream().forEach {
cache.put(it, it.toString())
}
range.parallelStream().forEach {
log.trace("\tGot [key=$it, value=${cache.get(it)}]")
assertThat(it).isEqualTo(cache.get(it).toInt())
}
}
}
}
|
/*
* Copyright 2023 Michael Johnston
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mrbean355.roons.repository
import com.github.mrbean355.roons.Metadata
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class MetadataRepositoryKtTest {
@MockK
private lateinit var metadataRepository: MetadataRepository
@BeforeEach
internal fun setUp() {
MockKAnnotations.init(this)
}
@Test
internal fun testGetWelcomeMessage_NullValue_ReturnsNull() {
every { metadataRepository.findByKey("app_welcome_message") } returns null
val result = metadataRepository.getWelcomeMessage()
assertNull(result)
}
@Test
internal fun testGetWelcomeMessage_NonNullValue_ReturnsValue() {
every { metadataRepository.findByKey("app_welcome_message") } returns mockk {
every { value } returns "hello world"
}
val result = metadataRepository.getWelcomeMessage()
assertEquals("hello world", result)
}
@Test
internal fun testSaveWelcomeMessage_EntityNotFound_CreatesNewEntity() {
every { metadataRepository.findByKey("app_welcome_message") } returns null
every { metadataRepository.save(any()) } returns mockk()
metadataRepository.saveWelcomeMessage("Game on")
verify { metadataRepository.save(Metadata("app_welcome_message", "Game on")) }
}
@Test
internal fun testSaveWelcomeMessage_EntityFound_UpdatesExistingEntity() {
every { metadataRepository.findByKey("app_welcome_message") } returns Metadata("app_welcome_message", "VIVON ZULUL")
every { metadataRepository.save(any()) } returns mockk()
metadataRepository.saveWelcomeMessage("Game on")
verify { metadataRepository.save(Metadata("app_welcome_message", "Game on")) }
}
}
|
package com.stocksexchange.android.ui.trade.views
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.content.withStyledAttributes
import com.stocksexchange.android.Constants.TRADING_AMOUNT_SEEK_BAR_MAX_PROGRESS
import com.stocksexchange.android.R
import com.stocksexchange.android.ui.views.base.containers.BaseRelativeLayoutView
import com.stocksexchange.core.utils.extensions.*
import kotlinx.android.synthetic.main.trade_amount_label_container_layout.view.*
/**
* A container that holds a label and extra controls (like a slider).
*/
class TradeAmountLabelContainer @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : BaseRelativeLayoutView(context, attrs, defStyleAttr) {
companion object {
private const val ATTRIBUTE_KEY_LABEL_TEXT_COLOR = "label_text_color"
private const val ATTRIBUTE_KEY_LABEL_TEXT = "label_text"
private const val DEFAULT_LABEL_TEXT_COLOR = Color.WHITE
private const val DEFAULT_LABEL_TEXT = ""
}
private var mLabelViewsArray: Array<TextView> = arrayOf()
override fun saveAttributes(attrs: AttributeSet?, defStyleAttr: Int) {
super.saveAttributes(attrs, defStyleAttr)
context.withStyledAttributes(attrs, R.styleable.TradeAmountLabelContainer, defStyleAttr, 0) {
with(mAttributes) {
save(ATTRIBUTE_KEY_LABEL_TEXT_COLOR, getColor(R.styleable.TradeAmountLabelContainer_labelTextColor, DEFAULT_LABEL_TEXT_COLOR))
save(ATTRIBUTE_KEY_LABEL_TEXT, (getText(R.styleable.TradeAmountLabelContainer_labelText) ?: DEFAULT_LABEL_TEXT))
}
}
}
override fun applyAttributes() {
with(mAttributes) {
setLabelTextColor(get(ATTRIBUTE_KEY_LABEL_TEXT_COLOR, DEFAULT_LABEL_TEXT_COLOR))
setLabelText(get(ATTRIBUTE_KEY_LABEL_TEXT, DEFAULT_LABEL_TEXT))
}
}
override fun init() {
super.init()
initLabelViews()
initSeekBar()
}
private fun initLabelViews() {
mLabelViewsArray = arrayOf(labelTv, seekBarPercentLabelTv)
}
private fun initSeekBar() {
seekBar.max = TRADING_AMOUNT_SEEK_BAR_MAX_PROGRESS
}
fun showSeekBarControls() {
seekBar.makeVisible()
seekBarPercentLabelTv.makeVisible()
}
fun hideSeekBarControls() {
seekBar.makeGone()
seekBarPercentLabelTv.makeGone()
}
fun enableSeekBarControlsStateSaving() {
seekBar.isSaveEnabled = true
seekBarPercentLabelTv.isSaveEnabled = true
}
fun disableSeekbarControlsStateSaving() {
seekBar.isSaveEnabled = false
seekBarPercentLabelTv.isSaveEnabled = false
}
fun setSeekBarEnabled(isEnabled: Boolean) {
seekBar.isEnabled = isEnabled
}
fun setSeekBarThumbColor(@ColorInt color: Int) {
seekBar.setThumbColor(color)
}
fun setSeekBarPrimaryProgressColor(@ColorInt color: Int) {
seekBar.setPrimaryProgressColor(color)
}
fun setSeekBarSecondaryProgressColor(@ColorInt color: Int) {
seekBar.setSecondaryProgressColor(color)
}
fun setLabelTextColor(@ColorInt color: Int) {
mLabelViewsArray.forEach {
it.setTextColor(color)
}
}
fun setSeekBarProgress(progress: Int) {
seekBar.progress = progress
}
fun setLabelText(text: String) {
labelTv.text = text
}
fun setSeekBarPercentLabelText(text: String) {
seekBarPercentLabelTv.text = text
}
fun setSeekBarChangeListener(listener: SeekBar.OnSeekBarChangeListener) {
seekBar.setOnSeekBarChangeListener(listener)
}
fun isSeekBarEnabled(): Boolean = seekBar.isEnabled
fun getSeekBarProgress(): Int = seekBar.progress
fun getSeekBarPercentLabelText(): CharSequence = seekBarPercentLabelTv.text
override fun getLayoutResourceId(): Int = R.layout.trade_amount_label_container_layout
}
|
package io.infinity.newsapp.services.networkservices
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
sealed class MyState {
object Fetched : MyState()
object Error : MyState()
}
sealed class NetworkStatus {
object Available : NetworkStatus()
object Unavailable : NetworkStatus()
}
class NetworkStatusTracker(context: Context) {
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@ExperimentalCoroutinesApi
val networkStatus = callbackFlow<NetworkStatus> {
val networkStatusCallback = object : ConnectivityManager.NetworkCallback() {
override fun onUnavailable() {
println("onUnavailable")
offer(NetworkStatus.Unavailable)
}
override fun onAvailable(network: Network) {
println("onAvailable")
offer(NetworkStatus.Available)
}
override fun onLost(network: Network) {
println("onLost")
offer(NetworkStatus.Unavailable)
}
}
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(request, networkStatusCallback)
awaitClose {
connectivityManager.unregisterNetworkCallback(networkStatusCallback)
}
}
.distinctUntilChanged()
}
@FlowPreview
inline fun <Result> Flow<NetworkStatus>.map(
crossinline onUnavailable: suspend () -> Result,
crossinline onAvailable: suspend () -> Result,
): Flow<Result> = map { status ->
when (status) {
NetworkStatus.Unavailable -> onUnavailable()
NetworkStatus.Available -> onAvailable()
}
}
@FlowPreview
inline fun <Result> Flow<NetworkStatus>.flatMap(
crossinline onUnavailable: suspend () -> Flow<Result>,
crossinline onAvailable: suspend () -> Flow<Result>,
): Flow<Result> = flatMapConcat { status ->
when (status) {
NetworkStatus.Unavailable -> onUnavailable()
NetworkStatus.Available -> onAvailable()
}
}
|
package com.example.bookbnb.viewmodels
import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.lifecycle.*
import com.example.bookbnb.R
import com.example.bookbnb.models.User
import com.example.bookbnb.network.BookBnBApi
import com.example.bookbnb.network.ResultWrapper
import kotlinx.coroutines.launch
class PerfilViewModel(application: Application) : BaseAndroidViewModel(application) {
private val _user = MutableLiveData<User>()
val user : MutableLiveData<User>
get() = _user
private val _navigateToEditarPerfil = MutableLiveData<Boolean>(false)
val navigateToEditarPerfil : MutableLiveData<Boolean>
get() = _navigateToEditarPerfil
private val _navigateToPerfil = MutableLiveData<Boolean>(false)
val navigateToPerfil : MutableLiveData<Boolean>
get() = _navigateToPerfil
val formErrors = ObservableArrayList<FormErrors>()
enum class FormErrors {
MISSING_NOMBRE,
MISSING_APELLIDO
}
fun isFormValid(): Boolean {
formErrors.clear()
if (_user.value?.name.isNullOrEmpty()) {
formErrors.add(FormErrors.MISSING_NOMBRE)
}
if (_user.value?.surname.isNullOrEmpty()) {
formErrors.add(FormErrors.MISSING_APELLIDO)
}
return formErrors.isEmpty()
}
fun onSavePerfilClick(){
viewModelScope.launch {
try {
showLoadingSpinner(false)
if (isFormValid()) {
when (val editPerfilResponse = BookBnBApi(getApplication()).editPerfil(user.value!!)) {
is ResultWrapper.NetworkError -> showSnackbarErrorMessage(
getApplication<Application>().getString(
R.string.network_error_msg
)
)
is ResultWrapper.GenericError -> showGenericError(editPerfilResponse)
is ResultWrapper.Success -> onDoneSavingPerfil()
}
}
} finally {
hideLoadingSpinner()
}
}
}
fun onDoneSavingPerfil(){
showSnackbarSuccessMessage("El perfil fue guardado correctamente")
_navigateToPerfil.value = true
}
fun onDoneNavigatingToPerfil(){
_navigateToPerfil.value = false
}
fun onNavigateToEditarPerfil(){
_navigateToEditarPerfil.value = true
}
fun onDoneNavigatingToEditarPerfil(){
_navigateToEditarPerfil.value = false
}
fun setUser(userId: String){
viewModelScope.launch {
try {
_showLoadingSpinner.value = true
when (val userResponse = BookBnBApi(getApplication()).getUser(userId)) {
is ResultWrapper.NetworkError -> showSnackbarErrorMessage(getApplication<Application>().getString(
R.string.network_error_msg))
is ResultWrapper.GenericError -> showGenericError(userResponse)
is ResultWrapper.Success -> _user.value = userResponse.value
}
}
finally {
_showLoadingSpinner.value = false
}
}
}
}
class PerfilViewModelFactory(val app: Application) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(PerfilViewModel::class.java)) {
return PerfilViewModel(app) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
|
fun main ()
{
println("Enter a number")
var x = Integer.valueOf(readLine())
if (x>0)
{
println("Positive")
}
else if (x<0)
{
println("Negative")
}
else
{
println("Zero")
}
}
|
package net.corda.node.services.identity
import net.corda.core.crypto.Crypto
import net.corda.core.crypto.generateKeyPair
import net.corda.core.identity.AnonymousParty
import net.corda.core.identity.CordaX500Name
import net.corda.core.identity.Party
import net.corda.core.identity.PartyAndCertificate
import net.corda.core.node.NodeInfo
import net.corda.core.node.services.UnknownAnonymousPartyException
import net.corda.core.serialization.serialize
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.coretesting.internal.DEV_INTERMEDIATE_CA
import net.corda.coretesting.internal.DEV_ROOT_CA
import net.corda.node.services.network.PersistentNetworkMapCache
import net.corda.node.services.persistence.PublicKeyToOwningIdentityCacheImpl
import net.corda.nodeapi.internal.createDevNodeIdentity
import net.corda.nodeapi.internal.crypto.CertificateType
import net.corda.nodeapi.internal.crypto.X509Utilities
import net.corda.nodeapi.internal.crypto.x509Certificates
import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.nodeapi.internal.persistence.DatabaseConfig
import net.corda.testing.core.ALICE_NAME
import net.corda.testing.core.BOB_NAME
import net.corda.testing.core.CHARLIE_NAME
import net.corda.testing.core.DUMMY_NOTARY_NAME
import net.corda.testing.core.SerializationEnvironmentRule
import net.corda.testing.core.TestIdentity
import net.corda.testing.core.getTestPartyAndCertificate
import net.corda.testing.internal.TestingNamedCacheFactory
import net.corda.testing.internal.configureDatabase
import net.corda.testing.internal.createDevIntermediateCaCertPath
import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.assertDoesNotThrow
import java.security.cert.CertPathValidatorException
import java.security.cert.X509CertSelector
import javax.security.auth.x500.X500Principal
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
class PersistentIdentityServiceTests {
private companion object {
val alice = TestIdentity(ALICE_NAME, 70)
val bob = TestIdentity(BOB_NAME, 80)
val notary = TestIdentity(DUMMY_NOTARY_NAME, 90)
val ALICE get() = alice.party
val ALICE_IDENTITY get() = alice.identity
val ALICE_PUBKEY get() = alice.publicKey
val BOB get() = bob.party
val BOB_IDENTITY get() = bob.identity
val BOB_PUBKEY get() = bob.publicKey
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val cacheFactory = TestingNamedCacheFactory()
private lateinit var database: CordaPersistence
private lateinit var identityService: PersistentIdentityService
private lateinit var networkMapCache: PersistentNetworkMapCache
@Before
fun setup() {
val cacheFactory = TestingNamedCacheFactory()
identityService = PersistentIdentityService(cacheFactory = cacheFactory)
database = configureDatabase(
makeTestDataSourceProperties(),
DatabaseConfig(),
identityService::wellKnownPartyFromX500Name,
identityService::wellKnownPartyFromAnonymous
)
identityService.database = database
identityService.start(
setOf(DEV_ROOT_CA.certificate),
alice.identity,
listOf(notary.party),
PublicKeyToOwningIdentityCacheImpl(database, cacheFactory)
)
networkMapCache = PersistentNetworkMapCache(cacheFactory, database, identityService)
}
@After
fun shutdown() {
database.close()
}
@Test(timeout=300_000)
fun `get all identities`() {
// Nothing registered, so empty set
assertNull(identityService.getAllIdentities().firstOrNull())
identityService.verifyAndRegisterIdentity(ALICE_IDENTITY)
var expected = setOf(ALICE)
var actual = identityService.getAllIdentities().map { it.party }.toHashSet()
assertEquals(expected, actual)
// Add a second party and check we get both back
identityService.verifyAndRegisterIdentity(BOB_IDENTITY)
expected = setOf(ALICE, BOB)
actual = identityService.getAllIdentities().map { it.party }.toHashSet()
assertEquals(expected, actual)
}
@Test(timeout=300_000)
fun `get identity by key`() {
assertNull(identityService.partyFromKey(ALICE_PUBKEY))
networkMapCache.verifyAndRegisterIdentity(ALICE_IDENTITY)
assertEquals(ALICE, identityService.partyFromKey(ALICE_PUBKEY))
assertNull(identityService.partyFromKey(BOB_PUBKEY))
}
@Test(timeout=300_000)
fun `get identity by name with no registered identities`() {
assertNull(identityService.wellKnownPartyFromX500Name(ALICE.name))
}
@Test(timeout=300_000)
fun `get identity by substring match`() {
networkMapCache.verifyAndRegisterIdentity(ALICE_IDENTITY)
networkMapCache.verifyAndRegisterIdentity(BOB_IDENTITY)
val alicente = getTestPartyAndCertificate(CordaX500Name(organisation = "Alicente Worldwide", locality = "London", country = "GB"), generateKeyPair().public)
networkMapCache.verifyAndRegisterIdentity(alicente)
assertEquals(setOf(ALICE, alicente.party), identityService.partiesFromName("Alice", false))
assertEquals(setOf(ALICE), identityService.partiesFromName("Alice Corp", true))
assertEquals(setOf(BOB), identityService.partiesFromName("Bob Plc", true))
}
@Test(timeout=300_000)
fun `get identity by name`() {
val identities = listOf("Organisation A", "Organisation B", "Organisation C")
.map { getTestPartyAndCertificate(CordaX500Name(organisation = it, locality = "London", country = "GB"), generateKeyPair().public) }
assertNull(identityService.wellKnownPartyFromX500Name(identities.first().name))
identities.forEach {
networkMapCache.verifyAndRegisterIdentity(it)
}
identities.forEach {
assertEquals(it.party, identityService.wellKnownPartyFromX500Name(it.name))
}
}
/**
* Generate a certificate path from a root CA, down to a transaction key, store and verify the association.
*/
@Test(timeout=300_000)
fun `assert unknown anonymous key is unrecognised`() {
val rootKey = Crypto.generateKeyPair(X509Utilities.DEFAULT_TLS_SIGNATURE_SCHEME)
val rootCert = X509Utilities.createSelfSignedCACertificate(ALICE.name.x500Principal, rootKey)
val txKey = Crypto.generateKeyPair(X509Utilities.DEFAULT_IDENTITY_SIGNATURE_SCHEME)
val identity = Party(rootCert)
val txIdentity = AnonymousParty(txKey.public)
assertFailsWith<UnknownAnonymousPartyException> {
identityService.assertOwnership(identity, txIdentity)
}
}
/**
* Generate a pair of certificate paths from a root CA, down to a transaction key, store and verify the associations.
* Also checks that incorrect associations are rejected.
*/
@Test(timeout=300_000)
fun `get anonymous identity by key`() {
val (alice, aliceTxIdentity) = createConfidentialIdentity(ALICE.name)
val (_, bobTxIdentity) = createConfidentialIdentity(ALICE.name)
// Now we have identities, construct the service and let it know about both
identityService.verifyAndRegisterIdentity(alice)
identityService.verifyAndRegisterIdentity(aliceTxIdentity)
var actual = @Suppress("DEPRECATION") identityService.certificateFromKey(aliceTxIdentity.party.owningKey)
assertEquals(aliceTxIdentity, actual!!)
assertNull(@Suppress("DEPRECATION") identityService.certificateFromKey(bobTxIdentity.party.owningKey))
identityService.verifyAndRegisterIdentity(bobTxIdentity)
actual = @Suppress("DEPRECATION") identityService.certificateFromKey(bobTxIdentity.party.owningKey)
assertEquals(bobTxIdentity, actual!!)
}
/**
* Generate a pair of certificate paths from a root CA, down to a transaction key, store and verify the associations.
* Also checks that incorrect associations are rejected.
*/
@Test(timeout=300_000)
fun `assert ownership`() {
val (alice, anonymousAlice) = createConfidentialIdentity(ALICE.name)
val (bob, anonymousBob) = createConfidentialIdentity(BOB.name)
// Now we have identities, construct the service and let it know about both
identityService.verifyAndRegisterIdentity(anonymousAlice)
identityService.verifyAndRegisterIdentity(anonymousBob)
// Verify that paths are verified
identityService.assertOwnership(alice.party, anonymousAlice.party.anonymise())
identityService.assertOwnership(bob.party, anonymousBob.party.anonymise())
assertFailsWith<IllegalArgumentException> {
identityService.assertOwnership(alice.party, anonymousBob.party.anonymise())
}
assertFailsWith<IllegalArgumentException> {
identityService.assertOwnership(bob.party, anonymousAlice.party.anonymise())
}
assertFailsWith<IllegalArgumentException> {
val owningKey = DEV_INTERMEDIATE_CA.certificate.publicKey
val subject = CordaX500Name.build(DEV_INTERMEDIATE_CA.certificate.subjectX500Principal)
identityService.assertOwnership(Party(subject, owningKey), anonymousAlice.party.anonymise())
}
}
@Test(timeout=300_000)
fun `Test Persistence`() {
val (alice, anonymousAlice) = createConfidentialIdentity(ALICE.name)
val (bob, anonymousBob) = createConfidentialIdentity(BOB.name)
// Register well known identities
networkMapCache.verifyAndRegisterIdentity(alice)
networkMapCache.verifyAndRegisterIdentity(bob)
// Register an anonymous identities
identityService.verifyAndRegisterIdentity(anonymousAlice)
identityService.verifyAndRegisterIdentity(anonymousBob)
// Create new identity service mounted onto same DB
val newPersistentIdentityService = PersistentIdentityService(TestingNamedCacheFactory()).also {
it.database = database
it.start(
setOf(DEV_ROOT_CA.certificate),
Companion.alice.identity,
pkToIdCache = PublicKeyToOwningIdentityCacheImpl(database, cacheFactory)
)
}
newPersistentIdentityService.assertOwnership(alice.party, anonymousAlice.party.anonymise())
newPersistentIdentityService.assertOwnership(bob.party, anonymousBob.party.anonymise())
val aliceParent = newPersistentIdentityService.wellKnownPartyFromAnonymous(anonymousAlice.party.anonymise())
assertEquals(alice.party, aliceParent!!)
val bobReload = @Suppress("DEPRECATION") newPersistentIdentityService.certificateFromKey(anonymousBob.party.owningKey)
assertEquals(anonymousBob, bobReload!!)
}
@Test(timeout=300_000)
fun `ensure no exception when looking up an unregistered confidential identity`() {
val (_, anonymousAlice) = createConfidentialIdentity(ALICE.name)
// Ensure no exceptions are thrown if we attempt to look up an unregistered CI
assertNull(identityService.wellKnownPartyFromAnonymous(AnonymousParty(anonymousAlice.owningKey)))
}
@Test(timeout=300_000)
fun `register duplicate confidential identities`(){
val (alice, anonymousAlice) = createConfidentialIdentity(ALICE.name)
identityService.registerKey(anonymousAlice.owningKey, alice.party)
// If an existing entry is found matching the party then the method call is idempotent
assertDoesNotThrow {
identityService.registerKey(anonymousAlice.owningKey, alice.party)
}
}
@Test(timeout=300_000)
fun `resolve key to party for key without certificate`() {
// Register Alice's PartyAndCert as if it was done so via the network map cache.
networkMapCache.verifyAndRegisterIdentity(alice.identity)
// Use a key which is not tied to a cert.
val publicKey = Crypto.generateKeyPair().public
// Register the PublicKey to Alice's CordaX500Name.
identityService.registerKey(publicKey, alice.party)
assertEquals(alice.party, identityService.partyFromKey(publicKey))
}
@Test(timeout=300_000)
fun `register incorrect party to public key `(){
networkMapCache.verifyAndRegisterIdentity(ALICE_IDENTITY)
val (alice, anonymousAlice) = createConfidentialIdentity(ALICE.name)
identityService.registerKey(anonymousAlice.owningKey, alice.party)
// Should have no side effect but logs a warning that we tried to overwrite an existing mapping.
assertFailsWith<IllegalStateException> { identityService.registerKey(anonymousAlice.owningKey, bob.party) }
assertEquals(ALICE, identityService.wellKnownPartyFromAnonymous(AnonymousParty(anonymousAlice.owningKey)))
}
@Test(timeout=300_000)
fun `P&C size`() {
val (_, anonymousAlice) = createConfidentialIdentity(ALICE.name)
val serializedCert = anonymousAlice.serialize()
println(serializedCert)
}
private fun createConfidentialIdentity(x500Name: CordaX500Name): Pair<PartyAndCertificate, PartyAndCertificate> {
val issuerKeyPair = generateKeyPair()
val issuer = getTestPartyAndCertificate(x500Name, issuerKeyPair.public)
val txKey = Crypto.generateKeyPair()
val txCert = X509Utilities.createCertificate(
CertificateType.CONFIDENTIAL_LEGAL_IDENTITY,
issuer.certificate,
issuerKeyPair,
x500Name.x500Principal,
txKey.public)
val txCertPath = X509Utilities.buildCertPath(txCert, issuer.certPath.x509Certificates)
return Pair(issuer, PartyAndCertificate(txCertPath))
}
private fun PersistentNetworkMapCache.verifyAndRegisterIdentity(identity: PartyAndCertificate) {
addOrUpdateNode(NodeInfo(listOf(NetworkHostAndPort("localhost", 12345)), listOf(identity), 1, 0))
}
/**
* Ensure if we feed in a full identity, we get the same identity back.
*/
@Test(timeout=300_000)
fun `deanonymising a well known identity should return the identity`() {
val expected = ALICE
networkMapCache.verifyAndRegisterIdentity(ALICE_IDENTITY)
val actual = identityService.wellKnownPartyFromAnonymous(expected)
assertEquals(expected, actual)
}
/**
* Ensure we don't blindly trust what an anonymous identity claims to be.
*/
@Test(timeout=300_000)
fun `deanonymising a false well known identity should return null`() {
val notAlice = Party(ALICE.name, generateKeyPair().public)
networkMapCache.verifyAndRegisterIdentity(ALICE_IDENTITY)
val actual = identityService.wellKnownPartyFromAnonymous(notAlice)
assertNull(actual)
}
@Test(timeout = 300_000)
fun `rotate identity`() {
networkMapCache.verifyAndRegisterIdentity(ALICE_IDENTITY)
val anonymousParty = AnonymousParty(generateKeyPair().public)
identityService.registerKeyToParty(anonymousParty.owningKey)
assertEquals(ALICE, identityService.partyFromKey(anonymousParty.owningKey))
assertEquals(ALICE, identityService.wellKnownPartyFromAnonymous(anonymousParty))
assertEquals(ALICE, identityService.wellKnownPartyFromAnonymous(ALICE))
assertEquals(ALICE, identityService.wellKnownPartyFromX500Name(ALICE.name))
// Make sure that registration of CI with certificate doesn't disrupt well-known party resolution.
val (_, anonymousIdentityWithCert) = createConfidentialIdentity(ALICE.name)
identityService.verifyAndRegisterIdentity(anonymousIdentityWithCert)
assertEquals(ALICE, identityService.wellKnownPartyFromAnonymous(anonymousParty))
assertEquals(ALICE, identityService.wellKnownPartyFromAnonymous(ALICE))
assertEquals(ALICE, identityService.wellKnownPartyFromX500Name(ALICE.name))
val alice2 = getTestPartyAndCertificate(ALICE.name, generateKeyPair().public)
networkMapCache.verifyAndRegisterIdentity(alice2)
assertEquals(alice2.party, identityService.wellKnownPartyFromAnonymous(anonymousParty))
assertEquals(alice2.party, identityService.wellKnownPartyFromAnonymous(ALICE))
assertEquals(alice2.party, identityService.wellKnownPartyFromX500Name(ALICE.name))
assertEquals(alice2.party, identityService.wellKnownPartyFromAnonymous(alice2.party))
assertEquals(setOf(alice2.party), identityService.partiesFromName("Alice Corp", true))
}
@Test(timeout = 300_000)
fun `multiple trust roots`() {
val (root2, doorman2) = createDevIntermediateCaCertPath(X500Principal("CN=Root2"))
val node2 = createDevNodeIdentity(doorman2, BOB_NAME)
val bob2 = PartyAndCertificate(X509Utilities.buildCertPath(node2.certificate, doorman2.certificate, root2.certificate))
val newIdentityService = PersistentIdentityService(cacheFactory)
newIdentityService.database = database
newIdentityService.start(
setOf(DEV_ROOT_CA.certificate, root2.certificate),
bob2,
listOf(),
PublicKeyToOwningIdentityCacheImpl(database, cacheFactory))
// Trust root should be taken from bobWithRoot2 identity.
assertEquals(root2.certificate, newIdentityService.trustRoot)
assertEquals(root2.certificate, newIdentityService.trustAnchor.trustedCert)
assertEquals(listOf(DEV_ROOT_CA.certificate, root2.certificate), newIdentityService.trustAnchors.map { it.trustedCert })
assertThat(newIdentityService.caCertStore.getCertificates(X509CertSelector())).contains(bob2.certificate, root2.certificate)
// Verify identities with trusted root.
newIdentityService.verifyAndRegisterIdentity(bob2)
newIdentityService.verifyAndRegisterIdentity(ALICE_IDENTITY)
val (root3, doorman3) = createDevIntermediateCaCertPath(X500Principal("CN=Root3"))
val node3 = createDevNodeIdentity(doorman3, CHARLIE_NAME)
val charlie3 = PartyAndCertificate(X509Utilities.buildCertPath(node3.certificate, doorman3.certificate, root3.certificate))
// Fail to verify identities with untrusted root.
assertFailsWith<CertPathValidatorException> {
newIdentityService.verifyAndRegisterIdentity(charlie3)
}
}
}
|
package com.project.kaamwaala.fragment.admin.adminstall
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.pixplicity.easyprefs.library.Prefs
import com.project.kaamwaala.R
import com.project.kaamwaala.activity.admin.InventoryActivity
import com.project.kaamwaala.adapter.admin.stall.AdminStallListAdapter
import com.project.kaamwaala.dialog.admin.CreateStallDialog
import com.project.kaamwaala.model.admin_stall_detail.AdminStallDetailRequest
import com.project.kaamwaala.model.admin_stall_detail.AdminStallDetailResponse
import com.project.kaamwaala.model.adminstalllist.AdminStallListRequest
import com.project.kaamwaala.model.adminstalllist.AdminStallListResponse
import com.project.kaamwaala.model.adminstalllist.StoreItem
import com.project.kaamwaala.model.createstall.CreateStallRequest
import com.project.kaamwaala.model.createstall.CreateStallResponse
import com.project.kaamwaala.network.PrefsConstants
import com.project.kaamwaala.OnItemClickCreateStall
import com.project.kaamwaala.OnItemClickStall
import io.paperdb.Paper
import kotlinx.android.synthetic.main.fragment_admin_stall.*
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.kodein
import org.kodein.di.generic.instance
class AdminStallFragment: Fragment(), KodeinAware, OnItemClickStall, OnItemClickCreateStall {
override val kodein by kodein()
private val factory: AdminStallVMF by instance<AdminStallVMF>()
private lateinit var VM: AdminStallVM
var listLive: MutableList<StoreItem> = mutableListOf()
var listOpening: MutableList<StoreItem> = mutableListOf()
var list: MutableList<String> = mutableListOf()
lateinit var callback: OnItemClickStall
lateinit var callback1: OnItemClickCreateStall
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view: View=inflater.inflate(R.layout.fragment_admin_stall, container, false)
VM = ViewModelProviders.of(this, factory).get(AdminStallVM::class.java)
callback=this
callback1=this
Paper.init(activity)
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
cardviewStore.setOnClickListener { createstallDialog() }
ivAdd.setOnClickListener { createstallDialog() }
StallListApi(AdminStallListRequest(Prefs.getString(PrefsConstants.UserId,""),"","0"))
}
private fun createstallDialog() {
val ft = activity!!.supportFragmentManager.beginTransaction()
val newFragment = CreateStallDialog()
newFragment.show(ft, "dialog")
newFragment.setCallBack(callback1)
}
//=====================================Admin================================================//
private fun StallListApi(adminStallListRequest: AdminStallListRequest) {
VM?.responseStallList = MutableLiveData()
VM?.responseStallList?.observe(this, Observer {
progressbar.visibility=View.GONE
val response = ( it as AdminStallListResponse)
if(response.Status)
{
rlCreate.visibility=View.GONE
rlStall.visibility=View.VISIBLE
//startActivity(Intent(dialog!!.context,InventoryActivity::class.java))
listOpening.clear()
listLive.clear()
for (i in 0 until response.StoreListItem.size) {
if(response.StoreListItem.get(i).isApproved=="False")
{
listOpening.add(response.StoreListItem[i])
}
else
{
listLive.add(response.StoreListItem[i])
}
}
rvLiveStall.apply {
rvLiveStall.layoutManager = LinearLayoutManager(context)
adapter = AdminStallListAdapter(listLive,callback) }
rvOpeningStall.apply {
rvOpeningStall.layoutManager =LinearLayoutManager(context)
adapter = AdminStallListAdapter(listOpening,callback) }
}
else
{
progressbar.visibility=View.GONE
rlCreate.visibility=View.VISIBLE
rlStall.visibility=View.GONE
}
})
VM.stalllist(adminStallListRequest)
}
override fun onClickStall(storeid: String) {
Progressbar.visibility=View.VISIBLE
StallDetailApi(AdminStallDetailRequest(Prefs.getString(PrefsConstants.UserId,""),storeid,"0"))
}
override fun onClickCreateStall(storename: String) {
Progressbar.visibility=View.VISIBLE
CreateStallApi(CreateStallRequest("","","","",0,"",0,"",""
,"","","","","","","" ,
"",false,0,"Insert",0,"",0,"","",
"","","","","","",0,
"",storename,"","", Prefs.getString(PrefsConstants.UserId,""),"",""
,""))
}
//==========================================API===================================================//
private fun CreateStallApi(createStallRequest:CreateStallRequest) {
VM?.responseStall = MutableLiveData()
VM?.responseStall?.observe(this, Observer {
val response = ( it as CreateStallResponse)
if(response.Status)
{
StallListApi(AdminStallListRequest(Prefs.getString(PrefsConstants.UserId,""),"","0"))
}
else
{
Progressbar.visibility=View.GONE
Toast.makeText(activity, "Something went wrong", Toast.LENGTH_SHORT).show()
}
})
VM.createstall(createStallRequest)
}
private fun StallDetailApi(adminStallDetailRequest: AdminStallDetailRequest) {
VM?.responseStallDetail = MutableLiveData()
VM?.responseStallDetail?.observe(this, Observer {
val response = ( it as AdminStallDetailResponse)
if(response.Status)
{
Paper.book().delete("stalldetail")
Paper.book()
.write("stalldetail", response)
Progressbar.visibility=View.GONE
startActivity(
Intent( activity,
InventoryActivity::class.java))
}
else
{
}
})
VM.stalldetail(adminStallDetailRequest)
}
}
|
package com.wNagiesEducationalCenterj_9905.common.utils
import android.app.Activity
import android.content.Context
import android.util.Patterns
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.wNagiesEducationalCenterj_9905.R
import javax.inject.Inject
class InputValidationProvider @Inject constructor(
private val context: Context
) {
fun isEditTextFilled
(editText: EditText,message:String? = null,isEmail:Boolean = false):Boolean{
val value = editText.text.toString().trim()
if (value.isEmpty()){
editText.error = message?:context.getString(R.string.prompt_empty_field)
hideKeyboardFrom(editText)
return false
}
if (isEmail){
return if (!Patterns.EMAIL_ADDRESS.matcher(value).matches()){
editText.error = message?:context.getString(R.string.prompt_empty_field)
hideKeyboardFrom(editText)
false
}else true
}
return true
}
fun isEditTextFilledMatches
(editText0:EditText,editText1:EditText,message: String? = null):Boolean{
val value0 = editText0.text.toString().trim()
val value1 = editText1.text.toString().trim()
if (!value0.contentEquals(value1)){
editText1.error = message?:context.getString(R.string.prompt_password_mismatch)
hideKeyboardFrom(editText1)
return false
}
return true
}
private fun hideKeyboardFrom(view: View) {
val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken,WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
}
|
package hr.fjukic.app_home.home.model
import hr.fjukic.app_home.home.utils.HomeScreenElementType
data class HomeCardUI(
val title: String,
val description: String = "",
val drawableId: Int? = null,
val elementType: HomeScreenElementType = HomeScreenElementType.HOME_CARD
)
|
package ru.ktsstudio.wishlist.data.network.model.response
data class AuthData (
val firstName: String?,
val lastName: String?,
val photo: String?,
val email: String = "",
val token: String?,
val id: String?
)
|
package org.remdev.widgetfactory.demoapp.fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import org.remdev.widgetfactory.careplan.widgets.LicenseAgreementView
import org.remdev.widgetfactory.demoapp.R
class LicenseAgreementViewFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.fragment_license_agreement, container, false)
val licenseAgreementView = view.findViewById<LicenseAgreementView>(R.id.cv_license_agreement)
licenseAgreementView.setCallback(object: LicenseAgreementView.LicenceCallback {
override fun onAccept() {
Toast.makeText(activity, "On accept clicked", Toast.LENGTH_SHORT).show()
activity?.finish()
}
override fun onClose() {
Toast.makeText(activity, "On close Clicked", Toast.LENGTH_SHORT).show()
activity?.finish()
}
})
licenseAgreementView.addSection("Legal", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.\n\nNemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.")
licenseAgreementView.addSection("Additional", "Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.")
return view
}
}
|
package io.quarkus.code.rest
import io.quarkus.code.config.CodeQuarkusConfig
import io.quarkus.code.config.GitHubConfig
import io.quarkus.code.config.GoogleAnalyticsConfig
import io.quarkus.code.model.*
import io.quarkus.code.service.PlatformService
import io.quarkus.code.service.QuarkusProjectService
import io.quarkus.registry.catalog.PlatformCatalog
import io.quarkus.runtime.StartupEvent
import org.apache.http.NameValuePair
import org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.message.BasicNameValuePair
import org.eclipse.microprofile.openapi.annotations.Operation
import org.eclipse.microprofile.openapi.annotations.enums.SchemaType
import org.eclipse.microprofile.openapi.annotations.media.Content
import org.eclipse.microprofile.openapi.annotations.media.Schema
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse
import org.eclipse.microprofile.openapi.annotations.tags.Tag
import java.lang.IllegalArgumentException
import java.nio.charset.StandardCharsets
import java.time.format.DateTimeFormatter
import java.util.logging.Level
import java.util.logging.Logger
import javax.enterprise.event.Observes
import javax.inject.Inject
import javax.validation.Valid
import javax.ws.rs.*
import javax.ws.rs.core.MediaType.APPLICATION_JSON
import javax.ws.rs.core.MediaType.TEXT_PLAIN
import javax.ws.rs.core.Response
@Path("/")
class CodeQuarkusResource {
companion object {
private val LOG = Logger.getLogger(CodeQuarkusResource::class.java.name)
var formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss' GMT'")
private const val LAST_MODIFIED_HEADER = "Last-Modified"
}
@Inject
internal lateinit var config: CodeQuarkusConfig
@Inject
lateinit var gaConfig: GoogleAnalyticsConfig
@Inject
lateinit var gitHubConfig: GitHubConfig
@Inject
internal lateinit var platformService: PlatformService
@Inject
internal lateinit var projectCreator: QuarkusProjectService
fun onStart(@Observes e: StartupEvent) {
LOG.log(Level.INFO) {
"""
Code Quarkus is started with:
environment = ${config().environment}
sentryDSN = ${config().sentryDSN}
quarkusPlatformVersion = ${config().quarkusPlatformVersion},
quarkusDevtoolsVersion = ${config().quarkusDevtoolsVersion},
gitCommitId: ${config().gitCommitId},
features: ${config().features}
""".trimIndent()
}
}
@GET
@Path("/config")
@Produces(APPLICATION_JSON)
@Operation(summary = "Get the Quarkus Launcher configuration", hidden = true)
fun config(): PublicConfig {
return PublicConfig(
environment = config.environment.orElse("dev"),
gaTrackingId = gaConfig.trackingId.filter(String::isNotBlank).orElse(null),
sentryDSN = config.sentryFrontendDSN.filter(String::isNotBlank).orElse(null),
quarkusPlatformVersion = config.quarkusPlatformVersion,
quarkusDevtoolsVersion = config.quarkusDevtoolsVersion,
quarkusVersion= config.quarkusPlatformVersion,
gitCommitId = config.gitCommitId,
gitHubClientId = gitHubConfig.clientId.filter(String::isNotBlank).orElse(null),
features = config.features.map { listOf(it) }.orElse(listOf())
)
}
@GET
@Path("/platforms")
@Produces(APPLICATION_JSON)
@Operation(summary = "Get all available platforms")
@Tag(name = "Platform", description = "Platform related endpoints")
@APIResponse(
responseCode = "200",
description = "All available platforms",
content = [Content(
mediaType = APPLICATION_JSON,
schema = Schema(implementation = PlatformCatalog::class)
)]
)
fun platforms(): Response {
val platformCatalog = platformService.platformCatalog
val lastUpdated = platformService.cacheLastUpdated
return Response.ok(platformCatalog).header(LAST_MODIFIED_HEADER, lastUpdated.format(formatter)).build()
}
@GET
@Path("/streams")
@Produces(APPLICATION_JSON)
@Operation(summary = "Get all available streams")
@Tag(name = "Platform", description = "Platform related endpoints")
@APIResponse(
responseCode = "200",
description = "All available streams",
content = [Content(
mediaType = APPLICATION_JSON,
schema = Schema(implementation = Stream::class, type = SchemaType.ARRAY)
)]
)
fun streams(): Response {
val streamKeys = platformService.streams
val lastUpdated = platformService.cacheLastUpdated
return Response.ok(streamKeys).header(LAST_MODIFIED_HEADER, lastUpdated.format(formatter)).build()
}
@GET
@Path("/extensions")
@Produces(APPLICATION_JSON)
@Operation(operationId = "extensions", summary = "Get the Quarkus Launcher list of Quarkus extensions")
@Tag(name = "Extensions", description = "Extension related endpoints")
@APIResponse(
responseCode = "200",
description = "List of Quarkus extensions",
content = [Content(
mediaType = APPLICATION_JSON,
schema = Schema(implementation = CodeQuarkusExtension::class, type = SchemaType.ARRAY)
)]
)
fun extensions(@QueryParam("platformOnly") @DefaultValue("true") platformOnly: Boolean): Response {
var extensions = platformService.recommendedCodeQuarkusExtensions
if (platformOnly) {
extensions = extensions.filter { it.platform }
}
val lastUpdated = platformService.cacheLastUpdated
return Response.ok(extensions).header(LAST_MODIFIED_HEADER, lastUpdated.format(formatter)).build()
}
@GET
@Path("/extensions/stream/{streamKey}")
@Produces(APPLICATION_JSON)
@Operation(operationId = "extensionsForStream", summary = "Get the Quarkus Launcher list of Quarkus extensions")
@Tag(name = "Extensions", description = "Extension related endpoints")
@APIResponse(
responseCode = "200",
description = "List of Quarkus extensions for a certain stream",
content = [Content(
mediaType = APPLICATION_JSON,
schema = Schema(implementation = CodeQuarkusExtension::class, type = SchemaType.ARRAY)
)]
)
fun extensionsForStream(
@PathParam("streamKey") streamKey: String,
@QueryParam("platformOnly") @DefaultValue("true") platformOnly: Boolean
): Response {
var extensions = platformService.getCodeQuarkusExtensions(streamKey)
if (platformOnly) {
extensions = extensions?.filter { it.platform }
}
val lastUpdated = platformService.cacheLastUpdated
return Response.ok(extensions).header(LAST_MODIFIED_HEADER, lastUpdated.format(formatter)).build()
}
@POST
@Path("/project")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Operation(summary = "Prepare a Quarkus application project to be downloaded")
@Tag(name = "Project", description = "Project creation endpoints")
fun project(@Valid projectDefinition: ProjectDefinition?): CreatedProject {
val params = ArrayList<NameValuePair>()
if (projectDefinition != null) {
if (projectDefinition.streamKey != null) {
params.add(BasicNameValuePair("S", projectDefinition.streamKey))
}
if (projectDefinition.groupId != ProjectDefinition.DEFAULT_GROUPID) {
params.add(BasicNameValuePair("g", projectDefinition.groupId))
}
if (projectDefinition.artifactId != ProjectDefinition.DEFAULT_ARTIFACTID) {
params.add(BasicNameValuePair("a", projectDefinition.artifactId))
}
if (projectDefinition.version != ProjectDefinition.DEFAULT_VERSION) {
params.add(BasicNameValuePair("v", projectDefinition.version))
}
if (projectDefinition.buildTool != ProjectDefinition.DEFAULT_BUILDTOOL) {
params.add(BasicNameValuePair("b", projectDefinition.buildTool))
}
if (projectDefinition.noCode != ProjectDefinition.DEFAULT_NO_CODE || projectDefinition.noExamples != ProjectDefinition.DEFAULT_NO_CODE) {
params.add(BasicNameValuePair("nc", projectDefinition.noCode.toString()))
}
if (projectDefinition.extensions.isNotEmpty()) {
projectDefinition.extensions.forEach { params.add(BasicNameValuePair("e", it)) }
}
if (projectDefinition.path != null) {
params.add(BasicNameValuePair("p", projectDefinition.path))
}
if (projectDefinition.className != null) {
params.add(BasicNameValuePair("c", projectDefinition.className))
}
}
val path = if (params.isEmpty()) "/d" else "/d?${URLEncodedUtils.format(params, StandardCharsets.UTF_8)}"
if (path.length > 1900) {
throw BadRequestException(
Response
.status(Response.Status.BAD_REQUEST)
.entity("The path is too long. Choose a sensible amount of extensions.")
.type(TEXT_PLAIN)
.build()
)
}
return CreatedProject(path)
}
@GET
@Path("/download")
@Produces("application/zip")
@Operation(operationId = "downloadForStream", summary = "Download a custom Quarkus application with the provided settings")
@Tag(name = "Download", description = "Download endpoints")
fun download(@Valid @BeanParam projectDefinition: ProjectDefinition): Response {
return try {
val platformInfo = platformService.getPlatformInfo(projectDefinition.streamKey)
Response
.ok(projectCreator.create(platformInfo, projectDefinition))
.type("application/zip")
.header("Content-Disposition", "attachment; filename=\"${projectDefinition.artifactId}.zip\"")
.build()
} catch (e: IllegalArgumentException) {
val message = "Bad request: ${e.message}"
LOG.warning(message)
Response
.status(Response.Status.BAD_REQUEST)
.entity(message)
.type(TEXT_PLAIN)
.build()
}
}
@POST
@Path("/download")
@Consumes(APPLICATION_JSON)
@Produces("application/zip")
@Operation(summary = "Download a custom Quarkus application with the provided settings")
@Tag(name = "Download", description = "Download endpoints")
fun postDownload(@Valid projectDefinition: ProjectDefinition?): Response {
try {
val project = projectDefinition ?: ProjectDefinition()
val platformInfo = platformService.getPlatformInfo(project.streamKey)
return Response
.ok(projectCreator.create(platformInfo, project))
.type("application/zip")
.header("Content-Disposition", "attachment; filename=\"${project.artifactId}.zip\"")
.build()
} catch (e: IllegalArgumentException) {
val message = "Bad request: ${e.message}"
LOG.warning(message)
return Response
.status(Response.Status.BAD_REQUEST)
.entity(message)
.type(TEXT_PLAIN)
.build()
}
}
}
|
package pl.valueadd.restcountries.persistence.dao
import androidx.room.Dao
import pl.valueadd.restcountries.persistence.entity.join.CountryBorderJoin
@Dao
abstract class CountryBorderDao : BaseDao<CountryBorderJoin>()
|
/*
* Copyright (C) 2019 Anton Malinskiy
*
* 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.malinskiy.adam
import com.malinskiy.adam.exception.RequestValidationException
import com.malinskiy.adam.log.AdamLogging
import com.malinskiy.adam.request.AsyncChannelRequest
import com.malinskiy.adam.request.ComplexRequest
import com.malinskiy.adam.request.MultiRequest
import com.malinskiy.adam.request.emu.EmulatorCommandRequest
import com.malinskiy.adam.request.misc.SetDeviceRequest
import com.malinskiy.adam.transport.SocketFactory
import com.malinskiy.adam.transport.use
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.Closeable
import java.net.InetAddress
import java.net.InetSocketAddress
class AndroidDebugBridgeClient(
val port: Int,
val host: InetAddress,
val socketFactory: SocketFactory
) : Closeable {
private val socketAddress: InetSocketAddress = InetSocketAddress(host, port)
suspend fun <T : Any?> execute(request: ComplexRequest<T>, serial: String? = null): T {
val validationResponse = request.validate()
if (!validationResponse.success) {
val requestSimpleClassName = request.javaClass.simpleName
throw RequestValidationException("Request $requestSimpleClassName did not pass validation: ${validationResponse.message}")
}
return socketFactory.tcp(
socketAddress = socketAddress,
idleTimeout = request.socketIdleTimeout
).use { socket ->
serial?.let {
SetDeviceRequest(it).handshake(socket)
}
request.process(socket)
}
}
fun <T : Any?, I : Any?> execute(request: AsyncChannelRequest<T, I>, scope: CoroutineScope, serial: String? = null): ReceiveChannel<T> {
val validationResponse = request.validate()
if (!validationResponse.success) {
val requestSimpleClassName = request.javaClass.simpleName
throw RequestValidationException("Request $requestSimpleClassName did not pass validation: ${validationResponse.message}")
}
return scope.produce {
socketFactory.tcp(
socketAddress = socketAddress,
idleTimeout = request.socketIdleTimeout
).use { socket ->
var backChannel = request.channel
var backChannelJob: Job? = null
try {
serial?.let {
SetDeviceRequest(it).handshake(socket)
}
request.handshake(socket)
backChannelJob = launch {
if (backChannel == null) return@launch
for (it in backChannel) {
if (!socket.isClosedForWrite) {
request.writeElement(it, socket)
}
}
}
while (true) {
if (isClosedForSend ||
socket.isClosedForRead ||
request.channel?.isClosedForReceive == true
) {
break
}
val finished = request.readElement(socket, this)
if (finished) break
}
} finally {
try {
withContext(NonCancellable) {
request.close(channel)
backChannelJob?.cancel()
}
} catch (e: Exception) {
log.debug(e) { "Exception during cleanup. Ignoring" }
}
}
}
}
}
suspend fun execute(request: EmulatorCommandRequest): String {
return socketFactory.tcp(
socketAddress = request.address,
idleTimeout = request.idleTimeoutOverride
).use { socket ->
request.process(socket)
}
}
suspend fun <T> execute(request: MultiRequest<T>, serial: String? = null): T {
val validationResponse = request.validate()
if (!validationResponse.success) {
val requestSimpleClassName = request.javaClass.simpleName
throw RequestValidationException("Request $requestSimpleClassName did not pass validation: ${validationResponse.message}")
}
return request.execute(this, serial)
}
companion object {
private val log = AdamLogging.logger {}
}
/**
* If you're reusing the socket factory across multiple clients then this will affect another client
*/
override fun close() = socketFactory.close()
}
|
package com.alejandrorios.core.contract
import com.alejandrorios.core.CoroutineContextProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
/**
* Created by Alejandro Rios on 2019-10-23
*/
interface BasePresenter<View : BaseView> {
var view: View?
val parentJob: Job
val coroutinesContextProvider: CoroutineContextProvider
fun bind(view: View) {
this.view = view
}
fun unBind() {
view = null
parentJob.apply {
cancelChildren()
}
}
fun launchJobOnMainDispatchers(job: suspend CoroutineScope.() -> Unit) {
CoroutineScope(coroutinesContextProvider.mainContext + parentJob).launch {
job()
}
}
}
|
package com.control.back.halo.basic.service
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.jpa.domain.Specification
import java.io.Serializable
interface IBaseService<T, ID : Serializable> {
fun find(id: ID): T
fun findAll(): List<T>
fun findList(ids: Array<ID>): List<T>
fun findList(ids: Iterable<ID>): List<T>
fun findAll(pageable: Pageable): Page<T>
fun findAll(spec: Specification<T>, pageable: Pageable): Page<T>
fun count(): Long
fun count(spec: Specification<T>): Long
fun exists(id: ID): Boolean
fun save(entity: T)
fun update(entity: T): T
fun delete(id: ID)
fun deleteByIds(vararg ids: ID)
fun delete(entitys: Array<T>)
fun delete(entitys: Iterable<T>)
fun delete(entity: T)
fun findList(spec: Specification<T>, sort: Sort): List<T>
}
|
package cn.cxy.browsebeauty.favorite
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import cn.cxy.browsebeauty.R
import cn.cxy.browsebeauty.db.bean.SelectImageInfo
import com.bumptech.glide.Glide
import com.cxyzy.utils.ext.show
import kotlinx.android.synthetic.main.item_favorite_list.view.*
class FavoriteAdapter(var selectionModeCallback: SelectionModeCallback) :
RecyclerView.Adapter<ViewHolder>() {
private var mDataList = mutableListOf<SelectImageInfo>()
private lateinit var mContext: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
mContext = parent.context
val view = LayoutInflater.from(mContext).inflate(R.layout.item_favorite_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val data = mDataList[position]
holder.itemView.iv.visibility = INVISIBLE
showImage(data, holder.itemView.iv, position)
showImageSelectCheckbox(holder, data, position)
holder.itemView.iv.setOnLongClickListener {
selectionModeCallback.onEnterSelectionMode(position)
true
}
}
private fun showImage(data: SelectImageInfo, view: ImageView, positionInImageList: Int) {
Glide.with(mContext).load(data.path).centerCrop().into(view)
view.setOnClickListener {
mContext.startActivity(
ImageActivity.buildIntent(
mContext,
data.toImageInfo(),
positionInImageList
)
)
}
view.show()
}
private fun showImageSelectCheckbox(
holder: RecyclerView.ViewHolder,
data: SelectImageInfo,
position: Int
) {
val imageSelectCheckbox = holder.itemView.imageSelectCheckbox
if (data.isSelected != null) {
imageSelectCheckbox.isChecked = data.isSelected!!
imageSelectCheckbox.show()
} else {
imageSelectCheckbox.show(false)
}
imageSelectCheckbox.setOnCheckedChangeListener { _, isChecked ->
selectionModeCallback.onChecked(position, isChecked)
}
}
fun setData(dataList: MutableList<SelectImageInfo>) {
mDataList.clear()
mDataList.addAll(dataList)
notifyDataSetChanged()
}
override fun getItemCount(): Int = mDataList.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
|
package doggy.back.infra.parties
import doggy.back.domain.partie.Partie
import doggy.back.domain.partie.PartiePersistance
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Component
@Component
class PartiePersistanceSql(
private val partiesRepository: PartiesDataRepository,
private val partieDatabaseMapper: PartieDatabaseMapper
) : PartiePersistance {
override fun sauverPartie(partie: Partie) {
val partieDatabase = partieDatabaseMapper.toPartieDatabase(partie)
partiesRepository.save(partieDatabase)
}
override fun recupererPartie(idPartie: String): Partie? {
return partiesRepository.findByIdOrNull(idPartie)?.let { partieDatabaseMapper.toPartie(it) }
}
}
|
package com.example.stock
import com.example.Order
import com.example.Product
import java.math.BigInteger
class StockServiceImpl(private val getProducts: () -> List<Product>) : StockService {
override fun getExistencesFromOrder(order: Order): List<Product> {
return getProducts()
.filter { order.products.contains(it.id) }
.filter { it.stock > BigInteger.ZERO }
}
}
|
package gg.rsmod.game.message.decoder
import gg.rsmod.game.message.MessageDecoder
import gg.rsmod.game.message.impl.IfButtonDMessage
/**
* @author Tom <rspsmods@gmail.com>
*/
class IfButtonDDecoder : MessageDecoder<IfButtonDMessage>() {
override fun decode(opcode: Int, opcodeIndex: Int, values: HashMap<String, Number>, stringValues: HashMap<String, String>): IfButtonDMessage {
val srcComponentHash = values["src_component_hash"]!!.toInt()
val srcSlot = values["src_slot"]!!.toInt()
val srcItem = values["src_item"]!!.toInt()
val dstComponentHash = values["dst_component_hash"]!!.toInt()
val dstSlot = values["dst_slot"]!!.toInt()
val dstItem = values["dst_item"]!!.toInt()
return IfButtonDMessage(srcComponentHash, srcSlot, srcItem, dstComponentHash, dstSlot, dstItem)
}
}
|
package org.nahoft.nahoft.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.WindowManager
import kotlinx.android.synthetic.main.activity_friends_user_guide.*
import org.nahoft.nahoft.R
class FriendsUserGuideActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_friends_user_guide)
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE)
// Show user guide in English
friends_user_guide_button_english.setOnClickListener {
friends_user_guide_textView.text = getString(R.string.friends_user_guide_english)
}
// Show user guide in Persian
friends_user_guide_button_persian.setOnClickListener {
friends_user_guide_textView.text = getString(R.string.friends_user_guide_persian)
}
}
}
|
package mmorihiro.matchland.model
enum class MessageType {
CONNECT, NotConnect, TouchUp, NotEnough, NewItem
}
|
package pl.gwynder.general.data.storage.entities
interface DataStoreEntity {
var id: String?
}
|
package com.example.exposeddrop_downmenu
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.example.exposeddrop_downmenu.databinding.FragmentFirstBinding
class FirstFragment : Fragment(R.layout.fragment_first) {
private lateinit var binding: FragmentFirstBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding = FragmentFirstBinding.bind(view)
}
//methods are kept in this bcs when u return to fragment only one language will show in list
override fun onResume() {
super.onResume()
val languages = resources.getStringArray(R.array.languages)
val arrayAdapter = ArrayAdapter(requireContext(), R.layout.dropdown_item, languages)
binding.autoCompleteTextView.setAdapter(arrayAdapter)
}
}
|
package com.mrebollob.drawaday.state
import com.mrebollob.drawaday.shared.domain.model.Result
/**
* Immutable data class that allows for loading, data, and exception to be managed independently.
*
* This is useful for screens that want to show the last successful result while loading or a later
* refresh has caused an error.
*/
data class UiState<T>(
val loading: Boolean = false,
val exception: Exception? = null,
val data: T? = null
) {
/**
* True if this contains an error
*/
val hasError: Boolean
get() = exception != null
/**
* True if this represents a first load
*/
val initialLoad: Boolean
get() = data == null && loading && !hasError
}
/**
* Copy a UiState<T> based on a Result<T>.
*
* Result.Success will set all fields
* Result.Error will reset loading and exception only
*/
fun <T> UiState<T>.copyWithResult(value: Result<T>): UiState<T> {
return when (value) {
is Result.Success -> copy(loading = false, exception = null, data = value.data)
is Result.Error -> copy(loading = false, exception = value.exception)
is Result.Loading -> copy(loading = true, exception = null, data = value.data)
}
}
|
package com.example.retrofitmovies.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.retrofitmovies.R
import com.example.retrofitmovies.model.Result
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_movie.view.*
class MoviesAdapter(var movieList: List<Result> = ArrayList()) ://this is constructor
RecyclerView.Adapter<MoviesAdapter.MovieViewHolder>() {
//two type of adapter con pr n fun pr
inner class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindMovie(result:Result) {
itemView.txt_movie.text = result.title
Picasso.get().load("https://image.tmdb.org/t/p/w200${result.poster_path}").into(itemView.image_movie)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movie, parent, false)
return MovieViewHolder(view)
}
override fun getItemCount(): Int {
return movieList.size
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
holder.bindMovie(movieList.get(position))
}
fun updateList(result: List<Result>) {
this.movieList = result
notifyDataSetChanged()
}
}
|
package org.firstinspires.ftc.teamcode.motionProfiles
import kotlin.math.abs
import kotlin.math.sqrt
import kotlin.math.pow
import kotlin.math.sign
class SCurveMotionProfile (var Vm: Double , var Am : Double, var Throw : Double, var gamma : Double, var startPos : Double){
val Sgn = Throw.sign * 1.0
val Yf = abs(Throw)
val Ys = Yf/2.0
val Yaux = (1.0/2.0) * (1+gamma) * (Vm.pow(2) / Am)
val Ya = if(Ys <= Yaux) Ys else Yaux;
val Vw = if(Ys <= Yaux) sqrt((Ys * Am)/((1.0/2.0) * (1+gamma))) else Vm
val To = Vw / Am
val Ta = To * (1 + gamma)
val tau = gamma * To
val Tm = Ta / 2.0
val Tk = 2.0 * (Ys - Ya) / Vm
val Ts = Ta + Tk / 2.0
val Tt = 2.0 * Ts
fun getPosition(time : Double) : Double{
return startPos + Sgn * position_base(time)
}
fun getVelocity(time : Double ) : Double{
return Sgn * velocity_base(time)
}
fun getTimeNeeded() : Double{
return Tt;
}
private fun position_base(time : Double ) : Double{
if(time > 0 && time < tau){
return ((1.0/2.0) * (Vw / To)) * (time.pow(3) / (3.0 * tau))
}
if(time > tau && time <= To){
return ((1.0/2.0) * (Vw / To)) * ((time - (tau / 2.0)).pow(2) + tau.pow(2) / 12.0)
}
if(time > To && time <= Ts){
return Ys + Vw * (time - Ts) + position_base(Ta - time)
}
if(time > Ts){
return Yf - position_base(Tt - time)
}
return 0.0
}
private fun velocity_base(time : Double ) : Double {
if(time > 0 && time < tau){
return (Am / 2.0) * (time.pow(2) / tau)
}
if(time > tau && time <= To){
return (Am / 2.0) * (2.0 * time - tau)
}
if(time > Tm && time <= Ts){
return Vw - velocity_base(Ta - time)
}
if(Ts < time){
return velocity_base(Tt - time)
}
return 0.0;
}
}
|
package com.semicolon.dsm_sdk_v1
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.semicolon.dsm_sdk_v1.BaseService.gson
import com.semicolon.dsm_sdk_v1.DsmSdk.Companion.loginCallbackCom
import com.semicolon.dsm_sdk_v1.DsmSdk.Companion.mustDoCallback
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class LoginClient : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.sdk_layout)
val webview: WebView = findViewById(R.id.webview)
val progressBar=findViewById<View>(R.id.progress_circular)
val redirectUrl=intent.getStringExtra("get_redirect").toString()
val clientId=intent.getStringExtra("get_client_id").toString()
val clientSecret=intent.getStringExtra("get_client_password").toString()
webview.settings.javaScriptEnabled = true // 자바스크립트 허용
webview.webViewClient = WebViewClient()
webview.webChromeClient = WebChromeClient()
webview.settings.domStorageEnabled=true
webview.loadUrl("https://developer.dsmkr.com/external/login?redirect_url=$redirectUrl&client_id=$clientId")
val post = mutableMapOf<String, String>() // post api안 body안에 담을 것
webview.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url) // 바뀐 url을 가져옴
return if (view.url?.contains("code") == true) {
val changeurl = view.url!! // 바뀐 url
//문자열 자르기!!
val code = changeurl.substring(changeurl.lastIndexOf("=") + 1) // 리다리엑트 url ?code= 의 뒷부분
post["client_id"] = clientId
post["client_secret"] = clientSecret// 우리가 직접 넣어야됨
post["code"] = code // ?code= 뒤에 있는거에여
webview.visibility= View.INVISIBLE
progressBar.visibility=View.VISIBLE
dsmAuthFunToken(post) // 이게 api post 시작!! 이 안에 다른 api 2개 들어있어요!!
false
} else {
true
}
}
})
}
private fun dsmAuthFunToken(Post: MutableMap<String, String>) {
val Basic = BaseService.serverbasic?.postlogin(Post)
Basic?.enqueue(object : retrofit2.Callback<DTOtoken> {
override fun onFailure(call: Call<DTOtoken>, t: Throwable) {
mustDoCallback(null, t)
}
override fun onResponse(call: Call<DTOtoken>, response: Response<DTOtoken>) {
val bodyBasic = response.body()
if(response.isSuccessful){
val access_token = bodyBasic?.access_token.toString()
val refrash_token = bodyBasic?.refresh_token.toString()
val token= DTOtoken(access_token, refrash_token)
mustDoCallback(token, null)
basicFun(access_token, loginCallbackCom) // access 토큰을 요청하는 api 함수
}else{
mustDoCallback(null,null)
}
}
})
}
fun refreshToken(refresh_token: String,callback:(String)->Unit){
val time = System.currentTimeMillis().toString() // 시간 받는거
val Basic = BaseService.serverbasic?.getrefresh(time, "Bearer $refresh_token")
Basic?.enqueue(object : retrofit2.Callback<refresh> {
override fun onFailure(call: Call<refresh>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<refresh>, response: Response<refresh>) {
val accessToken=response.body()?.access_token.toString()
callback(accessToken)
}
})
}
fun basicFun(access_token: String,callback: (getUser: DTOuser?) -> Unit) {
val time = System.currentTimeMillis().toString() // 시간 받는거
val BaseRetrofit = Retrofit.Builder()
.baseUrl("https://developer-api.dsmkr.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
val serverbasic: ServiceInterface? = BaseRetrofit.create(ServiceInterface::class.java) // severbasic 변수 사용해서 만드는 거
val Basic = serverbasic?.getbasic("Bearer $access_token", time)
Basic?.enqueue(object : retrofit2.Callback<DTOuser> {
override fun onFailure(call: Call<DTOuser>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<DTOuser>, response: Response<DTOuser>) {
if (response.body() != null) {
val userName = response.body()?.name.toString()
val userGcn = response.body()?.gcn.toString()
val userEmail = response.body()?.email.toString()
val inDto = DTOuser(userName, userGcn, userEmail)
callback(inDto)
finish()
}
}
})
}
}
|
package io.mockk.impl.instantiation
import kotlin.reflect.KClass
class JsInstantiator(instanceFactoryRegistry: CommonInstanceFactoryRegistry) :
AbstractInstantiator(instanceFactoryRegistry) {
@Suppress("UNCHECKED_CAST")
override fun <T : Any> instantiate(cls: KClass<T>): T {
return instantiateViaInstanceFactoryRegistry(cls) {
Proxy(InstanceStubTarget(), InstanceProxyHandler()) as T
}
}
}
internal class InstanceStubTarget {
override fun toString() = "<instance>"
}
internal class InstanceProxyHandler : EmptyProxyHandler() {
override fun get(target: dynamic, name: String, receiver: dynamic): Any? {
if (isJsNativeMethods(name)) {
return target[name]
}
return super.get(target, name, receiver)
}
}
|
package com.example.breakingBad.ui.episodeDetails
import androidx.lifecycle.*
import com.example.breakingBad.base.BaseViewModel
import com.example.breakingBad.data.models.character.Character
import com.example.breakingBad.data.models.character.Episode
import com.example.breakingBad.data.repository.Repository
import com.example.breakingBad.utils.getSplitName
import com.example.breakingBad.utils.handleNetworkError
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception
class EpisodeDetailsViewModel(private val episode: Episode) : BaseViewModel() {
private val _characters = MutableLiveData<List<Character>>()
val characters: LiveData<List<Character>> get() = _characters
init {
getCharacters()
}
private fun getCharacters() {
viewModelScope.launch {
try {
showLoading()
val characters = episode.characters.map {
withContext(Dispatchers.IO) {
Repository.getRemoteCharacterByName(
getSplitName(
it
)
).first()
}
}
_characters.postValue(characters)
} catch (e: Exception) {
handleNetworkError(e)
} finally {
hideLoading()
}
}
}
@Suppress("UNCHECKED_CAST")
class EpisodeDetailsViewModelFactory(
private val episode: Episode
) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return EpisodeDetailsViewModel(episode) as T
}
}
}
|
package com.aaandroiddev.cryptowatcher.ui.coinAllocation
import com.github.mikephil.charting.data.PieData
interface ICoinAllocation {
interface View {
fun drawPieChart(pieData: PieData)
fun enableGraphLoading()
fun disableGraphLoading()
}
interface Presenter {
fun onCreate()
fun onStop()
}
}
|
package com.example.myapplication
open class Teacher {
var designation = "Teacher"
var collegeName = "Beginnersbook"
fun does() {
println("Teaching")
}
}
|
package pl.valueadd.restcountries.persistence.dao
import androidx.room.Dao
import androidx.room.Query
import io.reactivex.Flowable
import pl.valueadd.restcountries.persistence.entity.CallingCodeEntity
@Dao
abstract class CallingCodeDao : BaseDao<CallingCodeEntity>() {
@Query(value = """
SELECT *
FROM calling_codes
WHERE calling_codes.country_id = :countryId
COLLATE NOCASE
""")
abstract fun observeCallingCodes(countryId: String): Flowable<List<CallingCodeEntity>>
}
|
package com.mmy.charitablexi.model.personal.presenter
import com.mmy.charitablexi.model.personal.ui.activity.AddAgreActivity
import com.mmy.charitablexi.model.personal.view.ChoiceAgreView
import com.mmy.frame.base.mvp.IPresenter
import com.mmy.frame.data.bean.AgreListBean
import com.mmy.frame.data.bean.IBean
import javax.inject.Inject
/**
* @file ChoiceAgrePresenter.kt
* @brief 描述
* @author lucas
* @date 2018/5/19 0019
* @version V1.0
* @par Copyright (c):
* @par History:
* version: zsr, 2017-09-23
*/
class ChoiceAgrePresenter @Inject constructor() :IPresenter<ChoiceAgreView>() {
fun getList(){
mM.request {
call = mApi.getAgreList()
_success = {
if (it is AgreListBean)
mV.refreshList(it.data)
}
}
}
fun addAgre(data: AddAgreActivity.BusAddAgre) {
mM.request {
call = mApi.addAgre(mApp.userInfo.id!!,data.title,data.content)
_success = {
if (it is IBean){
it.info.showToast(mFrameApp)
if (it.status==1){
getList()
}
}
}
}
}
}
|
package com.michal.idzkowski.trainingmetronome.storage
class TrainingContract {
companion object {
val tableName: String = "Trainings"
val columnId: String = "id"
val columnName: String = "name"
val columnColor: String = "color"
val createTable: String = "CREATE TABLE if not exists $tableName (" +
"$columnId integer PRIMARY KEY autoincrement, " +
"$columnName text, " +
"$columnColor text " +
")"
val dropTable: String = "DROP TABLE if exists ${tableName}"
fun selectAllTrainings(): String {
return "SELECT * FROM ${tableName}"
}
}
}
|
package com.davoh.list_adapter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listItems = mutableListOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
for (x in 6..10){
listItems.add("Item $x")
}
rv.layoutManager = LinearLayoutManager(this)
rv.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
val adapter = RvListAdapter()
rv.adapter = adapter
adapter.submitList(listItems)
fab.setOnClickListener {
val newList = ArrayList<String>()
newList.addAll(listItems)
val newItemValue = listItems.size + 1
newList.add("Item $newItemValue")
listItems.clear()
listItems.addAll(newList)
adapter.submitList(newList)
Log.d("Debugeando", "onClick")
}
}
}
|
package com.makentoshe.chiperchan
import com.makentoshe.chiperchan.model.cipher.RouteCipher
import junit.framework.Assert.assertEquals
import org.junit.Test
class RouteCipherTest {
@Test
fun `should encode and decode`() {
val encoded = RouteCipher(4).encode("я люблю бонч")
assertEquals("ябб лолюню ч", encoded)
val decoded = RouteCipher(4).decode(encoded)
assertEquals("я люблю бонч", decoded)
}
@Test
fun `should encode and decode 2`() {
val encoded = RouteCipher(5).encode("new day will dawn and I'll walk awa")
assertEquals("nalwdlkeyln w Iwa wda'awdianlla", encoded)
val decoded = RouteCipher(5).decode(encoded)
assertEquals("new day will dawn and I'll walk awa", decoded)
}
}
|
package iflix.play.webview.player
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.webkit.*
import android.widget.Button
import android.widget.TextView
class IflixPlayerWebViewActivity : AppCompatActivity() {
init {
WebView.setWebContentsDebuggingEnabled(true)
}
private var playing: Boolean = false
private lateinit var magicButton: Button
private lateinit var debugView: TextView
private lateinit var webView: WebView
private lateinit var webChromeClient: VideoEnabledWebChromeClient
companion object {
val INTENT_IFLIX_ASSET_TYPE = "asset_type"
val INTENT_IFLIX_ASSET_ID = "asset_id"
val IFLIX_ASSET_TYPE_MOVIE = "movie"
val IFLIX_ASSET_TYPE_SHOW = "show"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// force
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
setContentView(R.layout.activity_webview)
webView = findViewById(R.id.webView)
debugView = findViewById(R.id.debug_view)
magicButton = findViewById(R.id.magic_button)
magicButton.setOnClickListener {
Log.d("MagicButtonDispatch", "MagicButtonDispatch sending " + if (playing) "pause event" else "play event")
webView.evaluateJavascript(if (playing) {
"window.dispatchEvent(new Event('video-pause'));"
} else {
"window.dispatchEvent(new Event('video-play'));"
}) { Log.d("MagicButtonDispatch", "MagicButtonDispatch Result: $it")}
}
// Initialize the VideoEnabledWebChromeClient and set event handlers
val nonVideoLayout = findViewById<View>(R.id.nonVideoLayout)
val videoLayout = findViewById<ViewGroup>(R.id.videoLayout)
setTitle("")
// Get the web view settings instance
val settings = webView.settings
// Enable java script in web view
settings.javaScriptEnabled = true
// Enable and setup web view cache
settings.setAppCacheEnabled(true)
settings.cacheMode = WebSettings.LOAD_DEFAULT
settings.setAppCachePath(cacheDir.path)
// Enable disable images in web view
settings.blockNetworkImage = false
// Whether the WebView should load image resources
settings.loadsImagesAutomatically = true
// More web view settings
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
settings.safeBrowsingEnabled = true // api 26
}
settings.useWideViewPort = true
settings.loadWithOverviewMode = true
settings.javaScriptCanOpenWindowsAutomatically = true
settings.mediaPlaybackRequiresUserGesture = false
// include "partner/grab" in the user agent string for tracking
settings.userAgentString = System.getProperty("http.agent") + " partner/webtest"
// WebView settings
webView.fitsSystemWindows = true
webView.webViewClient = object: WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
setUpEventListeners(view ?: return)
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if (url.contains("/embed") && url.contains("iflix.com")) {
view.loadUrl(url)
} else {
view.getContext()?.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
return true
}
}
webChromeClient = object: VideoEnabledWebChromeClient(nonVideoLayout, videoLayout) {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onPermissionRequest(request: PermissionRequest?) {
request!!.grant(arrayOf(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID))
}
override fun onCreateWindow(view: WebView?, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message?): Boolean {
view?.getContext()?.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(view.getHitTestResult().extra)))
return false
}
}
// force fullscreen
window.decorView.makeFullscreen()
webView.webChromeClient = webChromeClient
// load the intent params
val assetType = intent.getStringExtra(INTENT_IFLIX_ASSET_TYPE)
val assetId = intent.getStringExtra(INTENT_IFLIX_ASSET_ID)
val url = "https://www.iflix.com/embed/$assetType/$assetId"
webView.loadUrl(url)
bindJavascriptInterface(webView)
}
private fun updateButtonState() {
if (playing) {
magicButton.text = "Pause"
} else {
magicButton.text = "Play"
}
}
private fun setUpEventListeners(webView: WebView) {
webView.evaluateJavascript("""
window.addEventListener('video-isLoaded', function () { iflixCallbacks.isLoaded() });
window.addEventListener('video-isLoading', function () { iflixCallbacks.isLoading() });
window.addEventListener('video-isPlaying', function () { iflixCallbacks.isPlaying() });
window.addEventListener('video-isPaused', function () { iflixCallbacks.isPaused() });
""") {}
}
private fun bindJavascriptInterface(webView: WebView) {
class IflixJavascriptInterface(private val context: Context) {
@JavascriptInterface
fun isLoaded() {
runOnUiThread {
debugView.text = "State: Loaded"
updateButtonState()
}
}
@JavascriptInterface
fun isLoading() {
runOnUiThread {
debugView.text = "State: Loading"
}
}
@JavascriptInterface
fun isPlaying() {
runOnUiThread {
debugView.text = "State: Playing"
playing = true
updateButtonState()
}
}
@JavascriptInterface
fun isPaused() {
runOnUiThread {
debugView.text = "State: Paused"
playing = false
updateButtonState()
}
}
}
webView.addJavascriptInterface(IflixJavascriptInterface(this), "iflixCallbacks")
}
override fun onBackPressed() {
// Notify the VideoEnabledWebChromeClient, and handle it ourselves if it doesn't handle it
if (!webChromeClient.onBackPressed()) {
if (webView.canGoBack()) {
webView.goBack()
} else {
// Standard back button implementation (for example this could close the app)
super.onBackPressed()
}
}
}
}
// making views full screen or non-immersive full screen
fun View.makeFullscreen() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
this.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
} else {
makeNonImmersiveFullscreen()
}
}
fun View.makeNonImmersiveFullscreen() {
this.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN)
}
|
package lunar.meshes
import lunar.LFace
import lunar.LMesh
import lunar.LVector
import java.util.*
fun boxMesh(boxWidth: Double, boxDepth: Double, boxHeight: Double, columns: Int, rows: Int, layers: Int) : LMesh{
var boxMesh: LMesh = LMesh()
val step: LVector = LVector(boxWidth/columns, boxDepth/rows, boxHeight/layers)
var indexTable: Array<Array<Array<Int>>> =
Array(columns+1) {
Array(rows+1){
Array(layers+1){-1}
}
}
//Create vertices
var index: Int = 0
for(i in indexTable.indices){
for(j in indexTable[0].indices){
for(k in indexTable[0][0].indices){
boxMesh.vertices.add(LVector(i*step.x, j*step.y, k*step.z))
indexTable[i][j][k] = index
index++
}
}
}
//Create faces
for (j in 1 until indexTable[0].size) {
for (k in 1 until indexTable[0][0].size) {
//Left Plane
boxMesh.faces.add(
LFace(
indexTable[0][j - 1][k - 1],
indexTable[0][j][k - 1],
indexTable[0][j - 1][k]
)
)
boxMesh.faces.add(
LFace(
indexTable[0][j][k - 1],
indexTable[0][j][k],
indexTable[0][j - 1][k]
)
)
//Right Plane
val l: Int = indexTable.size - 1
boxMesh.faces.add(
LFace(
indexTable[l][j][k - 1],
indexTable[l][j - 1][k - 1],
indexTable[l][j][k]
)
)
boxMesh.faces.add(
LFace(
indexTable[l][j - 1][k],
indexTable[l][j][k],
indexTable[l][j - 1][k - 1]
)
)
}
}
for (i in 1 until indexTable.size) {
for (k in 1 until indexTable[0][0].size) {
//Front plane
boxMesh.faces.add(
LFace(
indexTable[i-1][0][k],
indexTable[i][0][k-1],
indexTable[i-1][0][k-1]
)
)
boxMesh.faces.add(
LFace(
indexTable[i-1][0][k],
indexTable[i][0][k],
indexTable[i][0][k-1]
)
)
//Back Plane
val l: Int = indexTable[0].size - 1
boxMesh.faces.add(
LFace(
indexTable[i][l][k-1],
indexTable[i][l][k],
indexTable[i-1][l][k-1]
)
)
boxMesh.faces.add(
LFace(
indexTable[i-1][l][k-1],
indexTable[i][l][k],
indexTable[i-1][l][k]
)
)
}
}
for (i in 1 until indexTable.size) {
for (j in 1 until indexTable[0].size) {
//Bottom Plane
boxMesh.faces.add(
LFace(
indexTable[i-1][j-1][0],
indexTable[i][j][0],
indexTable[i-1][j][0]
)
)
boxMesh.faces.add(
LFace(
indexTable[i][j-1][0],
indexTable[i][j][0],
indexTable[i-1][j-1][0]
)
)
//Top Plane
val l: Int = indexTable[0][0].size - 1
boxMesh.faces.add(
LFace(
indexTable[i][j][l],
indexTable[i][j-1][l],
indexTable[i-1][j-1][l]
)
)
boxMesh.faces.add(
LFace(
indexTable[i][j][l],
indexTable[i-1][j-1][l],
indexTable[i-1][j][l]
)
)
}
}
return boxMesh
}
fun planeMesh(planeWidth: Double, planeHeight: Double, columns: Int, rows: Int): LMesh {
val planeMesh = LMesh()
val vectorGrid: ArrayList<ArrayList<LVector>> =
lunar.vectors.rectangularGrid(planeWidth, planeHeight, columns + 1, rows + 1)
//add vertices
for (array in vectorGrid) for (v in array) planeMesh.vertices.add(v)
//add faces
for (i in 1 until vectorGrid.size) {
for (j in 1 until vectorGrid[0].size) {
val indexMap = intArrayOf(
(i - 1) * vectorGrid[0].size + (j - 1),
i * vectorGrid[0].size + (j - 1),
(i - 1) * vectorGrid[0].size + j,
i * vectorGrid[0].size + j
)
planeMesh.faces.add(LFace(indexMap[0], indexMap[1], indexMap[2]))
planeMesh.faces.add(LFace(indexMap[3], indexMap[2], indexMap[1]))
}
}
return planeMesh
}
fun triangleMesh(a: LVector, b: LVector, c: LVector): LMesh {
val mesh = LMesh()
mesh.vertices.add(a)
mesh.vertices.add(b)
mesh.vertices.add(c)
mesh.faces.add(LFace(0, 1, 2))
return mesh
}
fun faceVertices(face: LFace, parentMesh: LMesh): ArrayList<LVector> {
val vectors = ArrayList<LVector>()
vectors.add(parentMesh.vertices[face.a])
vectors.add(parentMesh.vertices[face.b])
vectors.add(parentMesh.vertices[face.c])
return vectors
}
fun meshVertices(mesh: LMesh): ArrayList<LVector> {
return mesh.vertices
}
fun meshEdges(mesh: LMesh): ArrayList<ArrayList<LVector>> {
val edges = ArrayList<ArrayList<LVector>>()
for (i in mesh.vertices.indices) {
val a = mesh.vertices[i]
for (j in mesh.vertices.indices) {
if (j > i) {
val b = mesh.vertices[j]
var isPartner = false
for (f in mesh.faces) {
var aFound = false
var bFound = false
if (i == f.a || i == f.b || i == f.c) aFound = true
if (j == f.a || j == f.b || j == f.c) bFound = true
if (aFound && bFound) isPartner = true
}
if (isPartner) {
val edge = ArrayList<LVector>()
edge.add(a)
edge.add(b)
edges.add(edge)
}
}
}
}
return edges
}
fun culledFacesMesh(mesh: LMesh, pattern: ArrayList<Boolean>): LMesh {
mesh.faces = lunar.lists.dispatchedLists(mesh.faces, pattern)[0]
return mesh
}
fun culledVerticesMesh(mesh: LMesh, pattern: ArrayList<Boolean>): LMesh {
mesh.vertices = lunar.lists.dispatchedLists(mesh.vertices, pattern)[0]
var culledIndexes = ArrayList<Int>()
for (i in mesh.vertices.indices) culledIndexes.add(i)
culledIndexes = lunar.lists.dispatchedLists(culledIndexes, pattern)[0]
val culledFaces = ArrayList<LFace>()
for (f in mesh.faces) {
var fixedIndexA = false
var fixedIndexB = false
var fixedIndexC = false
for (i in culledIndexes.indices) {
if (culledIndexes[i] == f.a) {
f.a = i
fixedIndexA = true
}
if (culledIndexes[i] == f.b) {
f.b = i
fixedIndexB = true
}
if (culledIndexes[i] == f.c) {
f.c = i
fixedIndexC = true
}
}
if (fixedIndexA && fixedIndexB && fixedIndexC) culledFaces.add(LFace(f.a, f.b, f.c))
}
mesh.faces = culledFaces
return mesh
}
fun deletedFacesMesh(mesh: LMesh, indexes: ArrayList<Int>): LMesh {
val pattern = ArrayList<Boolean>()
for (i in indexes.indices) {
if (indexes[i] == i) pattern.add(false)
else pattern.add(true)
}
return culledFacesMesh(mesh, pattern)
}
fun deletedVerticesMesh(mesh: LMesh, indexes: ArrayList<Int>): LMesh
{
val pattern = ArrayList<Boolean>()
for (i in indexes.indices) {
if (indexes[i] == i) pattern.add(false)
else pattern.add(true)
}
return culledVerticesMesh(mesh, pattern)
}
fun joinedMesh(meshes: ArrayList<LMesh>): LMesh
{
val joinedMesh = LMesh()
for (m in meshes) {
val indexSize = joinedMesh.vertices.size
val verticesList = ArrayList<ArrayList<LVector>>()
verticesList.add(joinedMesh.vertices)
verticesList.add(m.vertices)
joinedMesh.vertices = lunar.lists.combinedList(verticesList)
for (f in m.faces) {
val updatedFace = LFace(f.a + indexSize, f.b + indexSize, f.c + indexSize)
joinedMesh.faces.add(updatedFace)
}
}
return joinedMesh
}
|
package model.paginas
import model.Especialidad
import model.IPagina
import model.Medico
import org.jsoup.Jsoup
class Temuco : IPagina {
override val url: String
get() = "https://clinicaalemanatemuco.cl/medicos-y-especialidades/listados-de-medicos-y-otros-profesionales"
override fun getEspecialidades(): List<Especialidad> {
TODO("Not yet implemented")
}
override fun getMedicos(especialidad: Especialidad): List<Medico> {
val returnList = mutableListOf<Medico>()
val doc = Jsoup
.connect(url)//url + "?especialidad=${URLEncoder.encode(especialidad, "iso-8859-1")}")
.get()
.getElementsByTag("tr")
.map {
Medico(
it.children()[0].text(),
"",
it.children()[1].text()
)
}.toCollection(returnList)
return returnList
}
}
|
package com.mchew.atrestaurants.di
import android.content.Context
import com.mchew.atrestaurants.core.ImageManager
import com.mchew.atrestaurants.core.PermissionManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object ApplicationModule {
@Provides
fun provideImageManager(
@ApplicationContext context: Context
): ImageManager {
return ImageManager(context)
}
@Provides
fun providePermissionManager(
@ApplicationContext context: Context
): PermissionManager {
return PermissionManager(context)
}
}
|
package com.example.stagepfe.Dao
import com.example.stagepfe.entite.Appointment
import java.util.HashMap
interface AppointmentCallback {
fun successAppointment(appointment: Appointment)
fun failureAppointment()
}
|
package ru.workout24.utills.custom_views
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import ru.workout24.R
class CustomRoundedButton : ConstraintLayout {
private val progress: ProgressBar by lazy {
findViewById<ProgressBar>(R.id.progress)
}
private val text: TextView by lazy {
findViewById<TextView>(R.id.txt_text)
}
private val icon: ImageView by lazy {
findViewById<ImageView>(R.id.img_icon)
}
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
)
: super(context, attrs, defStyleAttr) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomRoundedButton)
val text = typedArray.getString(R.styleable.CustomRoundedButton_textButton)
val image = typedArray.getDrawable(R.styleable.CustomRoundedButton_src)
if (text != null) {
this.text.text = text
}
if (image != null) {
this.icon.setImageDrawable(image)
}
typedArray.recycle()
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomRoundedButton)
val text = typedArray.getString(R.styleable.CustomRoundedButton_textButton)
val image = typedArray.getDrawable(R.styleable.CustomRoundedButton_src)
if (text != null) {
this.text.text = text
}
if (image != null) {
this.icon.setImageDrawable(image)
}
typedArray.recycle()
}
init {
LayoutInflater.from(context)
.inflate(R.layout.custom_rounded_button, this, true)
}
fun showProgress(value: Boolean = true) {
if (value) {
progress.visibility = View.VISIBLE
text.visibility = View.INVISIBLE
icon.visibility = View.INVISIBLE
} else {
progress.visibility = View.GONE
text.visibility = View.VISIBLE
icon.visibility = View.VISIBLE
}
}
}
|
package com.store.shopp
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class MovieModel(var title: String?,var price: String?, var detail: String?, var color: String?, var image: String?):
Parcelable
|
package com.example.pagingapplication.services.hackernews
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.pagingapplication.model.HackerNews
import kotlinx.coroutines.flow.Flow
interface HackerNewsRepository {
fun topStoriesFlow(): Flow<PagingData<HackerNews.Story>>
companion object {
val DEFAULT_PAGING_CONFIG = PagingConfig(pageSize = 10)
}
}
|
package br.com.yves.groupmatch.domain.models.calendar
import br.com.yves.groupmatch.domain.models.Week
import br.com.yves.groupmatch.domain.models.slots.CalendarTimeSlot
data class Calendar(
val id: Long = 0,
val owner: String,
val week: Week,
val calendarTimeSlots: MutableList<CalendarTimeSlot>,
val source: Source
) {
enum class Source {
LOCAL, REMOTE
}
}
|
package com.anu.utanglist
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.RoundedBitmapDrawable
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.*
import com.anu.utanglist.models.Debt
import com.anu.utanglist.utils.WebServiceHelper
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.BitmapImageViewTarget
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by irvan on 2/23/16.
*/
class DebtDetailActivity: AppCompatActivity() {
companion object {
final val EXTRA_DEBT_ID = "EXTRA_DEBT_ID"
final val EXTRA_DEBT_TYPE = "EXTRA_DEBT_TYPE"
}
private var toolbar: Toolbar? = null
private var progressBarLoading: ProgressBar? = null
private var layoutContainer: ScrollView? = null
private var imageViewPhoto: ImageView? = null
private var textViewAmount: TextView? = null
private var textViewName: TextView? = null
private var textViewNote: TextView? = null
private var buttonDebt: Button? = null
private var progressBarRequest: ProgressBar? = null
private var textViewLabelRequest: TextView? = null
private var debtType: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_debt_detail)
toolbar = findViewById(R.id.toolbar) as Toolbar
progressBarLoading = findViewById(R.id.loading) as ProgressBar
layoutContainer = findViewById(R.id.container) as ScrollView
imageViewPhoto = findViewById(R.id.photo) as ImageView
textViewAmount = findViewById(R.id.amount) as TextView
textViewName = findViewById(R.id.name) as TextView
textViewNote = findViewById(R.id.note) as TextView
buttonDebt = findViewById(R.id.debt) as Button
progressBarRequest = findViewById(R.id.request) as ProgressBar
textViewLabelRequest = findViewById(R.id.labelRequest) as TextView
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar?.setNavigationOnClickListener {
finish()
}
val debtId = intent.getStringExtra(EXTRA_DEBT_ID)
debtType = intent.getStringExtra(EXTRA_DEBT_TYPE)
if (debtType == Debt.TYPE_DEMAND) {
supportActionBar?.setTitle(R.string.title_debt_detail_demand)
buttonDebt?.setText(R.string.button_debt_demand)
performGetDebtDemandById(debtId)
} else {
supportActionBar?.setTitle(R.string.title_debt_detail_offer)
buttonDebt?.setText(R.string.button_debt_offer)
performGetDebtOfferById(debtId)
}
buttonDebt?.setOnClickListener {
if (debtType == Debt.TYPE_DEMAND) {
performDebtDemandRequest(debtId)
} else {
performDebtOfferRequest(debtId)
}
}
}
private fun performGetDebtDemandById(debtId: String) {
progressBarLoading?.visibility = View.VISIBLE
layoutContainer?.visibility = View.GONE
WebServiceHelper.service!!.getDebtDemandById(debtId).enqueue(object: Callback<Debt> {
override fun onResponse(call: Call<Debt>?, response: Response<Debt>?) {
progressBarLoading?.visibility = View.GONE
layoutContainer?.visibility = View.VISIBLE
if (response?.isSuccess!!) setCurrentDebt(response?.body())
}
override fun onFailure(call: Call<Debt>?, t: Throwable?) {
progressBarLoading?.visibility = View.GONE
layoutContainer?.visibility = View.GONE
Toast.makeText(this@DebtDetailActivity, R.string.error_connection, Toast.LENGTH_SHORT).show()
}
})
}
private fun performGetDebtOfferById(debtId: String) {
progressBarLoading?.visibility = View.VISIBLE
layoutContainer?.visibility = View.GONE
WebServiceHelper.service!!.getDebtOfferById(debtId).enqueue(object: Callback<Debt> {
override fun onResponse(call: Call<Debt>?, response: Response<Debt>?) {
progressBarLoading?.visibility = View.GONE
layoutContainer?.visibility = View.VISIBLE
if (response?.isSuccess!!) setCurrentDebt(response?.body())
}
override fun onFailure(call: Call<Debt>?, t: Throwable?) {
progressBarLoading?.visibility = View.GONE
layoutContainer?.visibility = View.GONE
Toast.makeText(this@DebtDetailActivity, R.string.error_connection, Toast.LENGTH_SHORT).show()
}
})
}
private fun performDebtDemandRequest(id: String) {
buttonDebt?.visibility = View.INVISIBLE
progressBarRequest?.visibility = View.VISIBLE
WebServiceHelper.service!!.debtDemandRequest(id).enqueue(object: Callback<Debt> {
override fun onResponse(call: Call<Debt>?, response: Response<Debt>?) {
progressBarRequest?.visibility = View.GONE
if (response?.isSuccess!!) {
buttonDebt?.visibility = View.INVISIBLE
textViewLabelRequest?.visibility = View.VISIBLE
textViewLabelRequest?.setText(R.string.label_debt_request_demand)
} else {
buttonDebt?.visibility = View.VISIBLE
}
}
override fun onFailure(call: Call<Debt>?, t: Throwable?) {
buttonDebt?.visibility = View.VISIBLE
progressBarRequest?.visibility = View.GONE
Toast.makeText(this@DebtDetailActivity, R.string.error_connection, Toast.LENGTH_SHORT).show()
}
})
}
private fun performDebtOfferRequest(id: String) {
buttonDebt?.visibility = View.INVISIBLE
progressBarRequest?.visibility = View.VISIBLE
WebServiceHelper.service!!.debtOfferRequest(id).enqueue(object: Callback<Debt> {
override fun onResponse(call: Call<Debt>?, response: Response<Debt>?) {
progressBarRequest?.visibility = View.GONE
if (response?.isSuccess!!) {
buttonDebt?.visibility = View.INVISIBLE
textViewLabelRequest?.visibility = View.VISIBLE
textViewLabelRequest?.setText(R.string.label_debt_request_offer)
} else {
buttonDebt?.visibility = View.VISIBLE
}
}
override fun onFailure(call: Call<Debt>?, t: Throwable?) {
buttonDebt?.visibility = View.VISIBLE
progressBarRequest?.visibility = View.GONE
Toast.makeText(this@DebtDetailActivity, R.string.error_connection, Toast.LENGTH_SHORT).show()
}
})
}
private fun setCurrentDebt(debt: Debt?) {
Glide.with(this)
.load(debt?.user?.photoUrl)
.asBitmap()
.placeholder(R.drawable.ic_profile_placeholder)
.centerCrop()
.into(object: BitmapImageViewTarget(imageViewPhoto) {
override fun setResource(resource: Bitmap?) {
val bitmapDrawable: RoundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, resource)
bitmapDrawable.isCircular = true
imageViewPhoto?.setImageDrawable(bitmapDrawable)
}
})
textViewAmount?.text = debt?.amount.toString()
textViewName?.text = debt?.user?.name
textViewNote?.text = debt?.note
}
}
|
package com.shopomy.webservice
import com.databindingwithrecyclerview.BuildConfig
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.security.KeyStore
import java.util.*
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
/**
* Created by sa on 31/03/17.
*
*
* Initialisation of Retrofit library with Okhttp3 and bind a base url.
*/
class ApiService {
var apiInterface: ApiInterface? = null
private set
var secureNetworkApi: ApiInterface? = null
private set
init {
initDefaultRetrofitService()
}
private fun initSecureRetrofitService() {
try {
//set default time out
val builder = OkHttpClient.Builder()
builder.connectTimeout(5, TimeUnit.MINUTES)
builder.readTimeout(5, TimeUnit.MINUTES)
builder.writeTimeout(5, TimeUnit.MINUTES)
/* builder.addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain?): Response {
val requestBuilder = chain!!.request().newBuilder()
requestBuilder.addHeader(ApiConstant.HEADER_LOCAL_LANGUAGE, getCountryShortName())
val secretToken = App.instance!!.preference!!.getData(Constants.PREF_SECRETE_TOKEN, "")
Log.e("secreteToken", secretToken)
Log.e("countrykey", getCountryShortName())
if (!TextUtils.isEmpty(secretToken)) {
requestBuilder.addHeader(ApiConstant.HEADER_AUTHORIZATION_NAME, secretToken)
}
return chain.proceed(requestBuilder.build())
}
})*/
// enable logging
if (BuildConfig.DEBUG) {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
builder.addInterceptor(logging)
} else {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.NONE
builder.addInterceptor(logging)
}
val retrofit = Retrofit.Builder()
.baseUrl(ApiConstant.HTTP_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(builder.build())
.build()
apiInterface = retrofit.create<ApiInterface>(ApiInterface::class.java!!)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun initDefaultRetrofitService() {
//set default time out
try {
val builder = OkHttpClient.Builder()
builder.connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
builder.readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
// Install the all-trusting trust manager
// final SSLContext sslContext = SSLContext.getInstance("TLS");
// TLSSocketFactory tlsSocketFactory = new TLSSocketFactory();
//builder.socketFactory(tlsSocketFactory);
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val trustManagers = trustManagerFactory.trustManagers
if (trustManagers.size != 1 || trustManagers[0] !is X509TrustManager) {
throw IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers))
}
val trustManager = trustManagers[0] as X509TrustManager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
val sslSocketFactory = sslContext.socketFactory
builder.sslSocketFactory(sslSocketFactory, trustManager)
//builder.followSslRedirects(true);
builder.addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain?): Response {
val requestBuilder = chain!!.request().newBuilder()
requestBuilder.addHeader(ApiConstant.HEADER_NEWS_API_KEY, ApiConstant.NEWS_KEY)
return chain.proceed(requestBuilder.build())
}
})
// enable logging
if (BuildConfig.DEBUG) {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
builder.addInterceptor(logging)
} else {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.NONE
builder.addInterceptor(logging)
}
val retrofit = Retrofit.Builder()
.baseUrl(ApiConstant.HTTP_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(builder.build())
.build()
apiInterface = retrofit.create<ApiInterface>(ApiInterface::class.java!!)
} catch (e: Exception) {
e.printStackTrace()
}
}
companion object {
private val DEFAULT_TIMEOUT = 180*1000
}
}
|
package com.ikukushev.nasaapp.pictures.apod
import com.ikukushev.nasaapp.data.NasaApi
import com.ikukushev.nasaapp.pictures.apod.db.ApodDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
data class ApodRepository @Inject constructor(
private val api: NasaApi,
private val apodDao: ApodDao
) {
suspend fun getLastApod() = withContext(Dispatchers.IO) {
api.getApod()
}
suspend fun getPreviousApods() = withContext(Dispatchers.IO) {
apodDao.getAll()
}
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4