content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package chan.spring.demo.member.dto.request
import jakarta.validation.constraints.NotBlank
data class WithdrawDto(
@field:NotBlank(message = "๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํ์ธ์.") val pw: String?
)
| chan-spring/src/main/kotlin/chan/spring/demo/member/dto/request/WithdrawDto.kt | 2570608344 |
package chan.spring.demo.member.repository
import com.querydsl.core.types.Projections
import com.querydsl.jpa.impl.JPAQueryFactory
import chan.spring.demo.exception.exception.MemberException
import chan.spring.demo.exception.message.MemberExceptionMessage
import chan.spring.demo.member.domain.Member
import chan.spring.demo.member.domain.QMember
import chan.spring.demo.member.domain.Role
import chan.spring.demo.member.dto.response.MemberInfo
import java.util.*
class MemberCustomRepositoryImpl(
private val jpaQueryFactory: JPAQueryFactory,
private val member: QMember = QMember.member
) : MemberCustomRepository {
override fun findMemberByEmail(email: String): Member {
return jpaQueryFactory.selectFrom(member)
.where(member.email.eq(email).and(member.auth.ne(Role.WITHDRAW)))
.fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, email)
}
override fun findMemberById(id: UUID): Member {
return jpaQueryFactory.selectFrom(member)
.where(member.id.eq(id).and(member.auth.ne(Role.WITHDRAW)))
.fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, id.toString())
}
override fun findMemberByEmailIncludeWithdraw(email: String): Member {
return jpaQueryFactory.selectFrom(member)
.where(member.email.eq(email))
.fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, email)
}
override fun findMemberInfoById(id: UUID): MemberInfo {
return jpaQueryFactory.select(
Projections.constructor(
MemberInfo::class.java,
member.id,
member.auth,
member.email
)
)
.from(member)
.where(member.id.eq(id).and(member.auth.ne(Role.WITHDRAW)))
.fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, id.toString())
}
override fun findAuthById(id: UUID): Role {
return jpaQueryFactory.select(member.auth)
.from(member)
.where(member.id.eq(id).and(member.auth.ne(Role.WITHDRAW)))
.fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, id.toString())
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/repository/MemberCustomRepositoryImpl.kt | 2579773105 |
package chan.spring.demo.member.repository
import chan.spring.demo.member.domain.Member
import org.springframework.data.jpa.repository.JpaRepository
interface MemberRepository : JpaRepository<Member, Long>, MemberCustomRepository
| chan-spring/src/main/kotlin/chan/spring/demo/member/repository/MemberRepository.kt | 2584784151 |
package chan.spring.demo.member.repository
import chan.spring.demo.member.domain.Member
import chan.spring.demo.member.domain.Role
import chan.spring.demo.member.dto.response.MemberInfo
import java.util.*
interface MemberCustomRepository {
fun findMemberByEmail(email: String): Member
fun findMemberById(id: UUID): Member
fun findMemberByEmailIncludeWithdraw(email: String): Member
fun findMemberInfoById(id: UUID): MemberInfo
fun findAuthById(id: UUID): Role
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/repository/MemberCustomRepository.kt | 3119944128 |
package chan.spring.demo.member.controller.response
import chan.spring.demo.member.dto.response.MemberInfo
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
object MemberResponse {
private const val SIGNUP_SUCCESS = "ํ์๊ฐ์
์ ์ฑ๊ณตํ์์ต๋๋ค.\n๋ฐ๊ฐ์ต๋๋ค."
private const val LOGIN_SUCCESS = "๋ก๊ทธ์ธ์ ์ฑ๊ณตํ์์ต๋๋ค.\nํ์ํฉ๋๋ค."
private const val UPDATE_PW_SUCCESS = "๋น๋ฐ๋ฒํธ๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ๋ณ๊ฒฝํ์์ต๋๋ค."
private const val LOGOUT_SUCCESS = "๋ก๊ทธ์์์ ์ฑ๊ณตํ์์ต๋๋ค."
private const val RECOVERY_SUCCESS = "๊ณ์ ๋ณต๊ตฌ์ ์ฑ๊ณตํ์์ต๋๋ค."
private const val WITHDRAW_SUCCESS = "ํ์ํํด๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ๋ง์ณค์ต๋๋ค.\n์๋
ํ๊ฐ์ธ์."
fun infoSuccess(member: MemberInfo) = ResponseEntity.ok(member)
fun signupSuccess() = ResponseEntity.status(HttpStatus.CREATED).body(SIGNUP_SUCCESS)
fun loginSuccess() = ResponseEntity.ok(LOGIN_SUCCESS)
fun updatePwSuccess() = ResponseEntity.ok(UPDATE_PW_SUCCESS)
fun logOutSuccess() = ResponseEntity.ok(LOGOUT_SUCCESS)
fun recoverySuccess() = ResponseEntity.ok(RECOVERY_SUCCESS)
fun withdrawSuccess() = ResponseEntity.ok(WITHDRAW_SUCCESS)
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/controller/response/MemberResponse.kt | 3895216291 |
package chan.spring.demo.member.controller
import chan.spring.demo.logger
import chan.spring.demo.member.dto.request.*
import chan.spring.demo.exception.exception.MemberException
import chan.spring.demo.exception.message.MemberExceptionMessage
import chan.spring.demo.jwt.dto.JwtTokenInfo
import chan.spring.demo.member.controller.constant.MemberControllerConstant
import chan.spring.demo.member.controller.constant.MemberRequestHeaderConstant
import chan.spring.demo.member.controller.constant.MemberUrl
import chan.spring.demo.member.controller.response.MemberResponse
import chan.spring.demo.member.dto.response.MemberInfo
import chan.spring.demo.member.log.MemberControllerLog
import chan.spring.demo.member.service.command.MemberCommandService
import chan.spring.demo.member.service.query.MemberQueryService
import jakarta.servlet.http.HttpServletResponse
import jakarta.validation.Valid
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.security.Principal
import java.util.*
@RestController
class MemberController
@Autowired
constructor(
private val memberQueryService: MemberQueryService,
private val memberCommandService: MemberCommandService
) {
@GetMapping(MemberUrl.INFO)
fun getMemberInfo(principal: Principal): ResponseEntity<MemberInfo> {
val member = memberQueryService.getMemberById(id = UUID.fromString(principal.name))
return MemberResponse.infoSuccess(member)
}
@PostMapping(MemberUrl.SIGNUP)
fun signup(
@RequestBody @Valid signupDto: SignupDto
): ResponseEntity<String> {
memberCommandService.signup(signupDto)
logger().info(MemberControllerLog.SIGNUP_SUCCESS + signupDto.email)
return MemberResponse.signupSuccess()
}
@PostMapping(MemberUrl.LOGIN)
fun login(
@RequestBody @Valid loginDto: LoginDto,
response: HttpServletResponse
): ResponseEntity<String> {
val tokenInfo = memberCommandService.login(loginDto)
response.apply {
addHeader(MemberControllerConstant.ACCESS_TOKEN, tokenInfo.accessToken)
addHeader(MemberControllerConstant.REFRESH_TOKEN, tokenInfo.refreshToken)
addHeader(MemberControllerConstant.MEMBER_ID, tokenInfo.id.toString())
}
logger().info(MemberControllerLog.LOGIN_SUCCESS + loginDto.email)
return MemberResponse.loginSuccess()
}
@PutMapping(MemberUrl.JWT_TOKEN_REISSUE)
fun jwtTokenReissue(
@RequestHeader(MemberRequestHeaderConstant.ID) id: String?,
@RequestHeader(MemberRequestHeaderConstant.REFRESH_TOKEN) refreshToken: String?
): ResponseEntity<JwtTokenInfo> {
if (id.isNullOrBlank() || refreshToken.isNullOrBlank()) {
throw MemberException(MemberExceptionMessage.TOKEN_REISSUE_HEADER_IS_NULL, "UNRELIABLE-MEMBER")
}
val memberId = UUID.fromString(id)
val reissueJwtToken = memberCommandService.reissueJwtToken(memberId, refreshToken)
logger().info(MemberControllerLog.JWT_TOKEN_REISSUE_SUCCESS + memberId)
return ResponseEntity.ok(reissueJwtToken)
}
@PatchMapping(MemberUrl.UPDATE_PASSWORD)
fun updatePassword(
@RequestBody @Valid updatePasswordDto: UpdatePasswordDto,
principal: Principal
): ResponseEntity<String> {
val memberId = UUID.fromString(principal.name)
memberCommandService.updatePassword(updatePasswordDto, memberId)
logger().info(MemberControllerLog.UPDATE_PW_SUCCESS + memberId)
return MemberResponse.updatePwSuccess()
}
@PostMapping(MemberUrl.LOGOUT)
fun logout(principal: Principal): ResponseEntity<String> {
val memberId = UUID.fromString(principal.name)
memberCommandService.logout(memberId)
logger().info(MemberControllerLog.LOGOUT_SUCCESS + memberId)
return MemberResponse.logOutSuccess()
}
@PostMapping(MemberUrl.RECOVERY_MEMBER)
fun recoveryMember(
@RequestBody @Valid recoveryDto: RecoveryDto
): ResponseEntity<String> {
memberCommandService.recoveryMember(recoveryDto)
logger().info(MemberControllerLog.RECOVERY_SUCCESS + recoveryDto.email)
return MemberResponse.recoverySuccess()
}
@DeleteMapping(MemberUrl.WITHDRAW)
fun withdraw(
@RequestBody @Valid withdrawDto: WithdrawDto,
principal: Principal
): ResponseEntity<String> {
val memberId = UUID.fromString(principal.name)
memberCommandService.withdraw(withdrawDto, memberId)
logger().info(MemberControllerLog.WITHDRAW_SUCCESS + memberId)
return MemberResponse.withdrawSuccess()
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/controller/MemberController.kt | 3701950676 |
package chan.spring.demo.member.controller.constant
object MemberUrl {
const val SIGNUP = "/member/signup"
const val LOGIN = "/member/login"
const val INFO = "/member/info"
const val JWT_TOKEN_REISSUE = "/auth/reissue"
const val UPDATE_PASSWORD = "/member/update/password"
const val LOGOUT = "/member/logout"
const val RECOVERY_MEMBER = "/member/recovery"
const val WITHDRAW = "/member/withdraw"
const val PROHIBITION = "/prohibition"
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/controller/constant/MemberUrl.kt | 2326422416 |
package chan.spring.demo.member.controller.constant
object MemberControllerConstant {
const val ACCESS_TOKEN = "access-token"
const val REFRESH_TOKEN = "refresh-token"
const val MEMBER_ID = "member-id"
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/controller/constant/MemberControllerConstant.kt | 610005557 |
package chan.spring.demo.member.controller.constant
object MemberRequestHeaderConstant {
const val ID = "id"
const val REFRESH_TOKEN = "refresh-token"
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/controller/constant/MemberRequestHeaderConstant.kt | 1327604481 |
package chan.spring.demo.member.log
object MemberServiceLog {
const val SUSPEND_MEMBER = "์ ์ง๋ ํ์์
๋๋ค. ํ์ Email : "
const val WRONG_PW = "์๋ชป๋ ๋น๋ฐ๋ฒํธ. ํ์ ID : "
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/log/MemberServiceLog.kt | 4249911603 |
package chan.spring.demo.member.log
object MemberControllerLog {
const val SIGNUP_SUCCESS = "ํ์๊ฐ์
์ฑ๊ณต. ํ์ Email : "
const val LOGIN_SUCCESS = "๋ก๊ทธ์ธ ์ฑ๊ณต. ํ์ Email : "
const val UPDATE_PW_SUCCESS = "๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ ์ฑ๊ณต. ํ์ ID : "
const val LOGOUT_SUCCESS = "ํ์ ๋ก๊ทธ์์ ์ฑ๊ณต. ํ์ ID : "
const val RECOVERY_SUCCESS = "ํ์ ๊ณ์ ๋ณต๊ตฌ ์ฑ๊ณต. ํ์ Email : "
const val WITHDRAW_SUCCESS = "ํ์ํํด ์ฑ๊ณต. ํ์ UUID : "
const val JWT_TOKEN_REISSUE_SUCCESS = "JWT ํ ํฐ ๊ฐฑ์ ์ฑ๊ณต. ํ์ ID : "
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/log/MemberControllerLog.kt | 3404465270 |
package chan.spring.demo.member.service.command
import chan.spring.demo.member.domain.Member
import chan.spring.demo.member.domain.Role
import chan.spring.demo.member.repository.MemberCustomRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.stereotype.Service
@Service
class CustomUserDetailsService
@Autowired
constructor(
private val memberRepository: MemberCustomRepository
) : UserDetailsService {
override fun loadUserByUsername(email: String): UserDetails {
val member = memberRepository.findMemberByEmail(email)
return createUserDetails(member)
}
private fun createUserDetails(member: Member): UserDetails {
return when (member.auth) {
Role.ADMIN -> {
createAdmin(member)
}
else -> {
createMember(member)
}
}
}
private fun createAdmin(member: Member): UserDetails {
return User.builder()
.username(member.id.toString())
.password(member.password)
.roles(Role.ADMIN.name)
.build()
}
private fun createMember(member: Member): UserDetails {
return User.builder()
.username(member.id.toString())
.password(member.password)
.roles(Role.MEMBER.name)
.build()
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/service/command/CustomUserDetailsService.kt | 1180184266 |
package chan.spring.demo.member.service.command
import chan.spring.demo.logger
import chan.spring.demo.exception.exception.MemberException
import chan.spring.demo.exception.message.MemberExceptionMessage
import chan.spring.demo.globalUtil.isMatchPassword
import chan.spring.demo.jwt.dto.JwtTokenInfo
import chan.spring.demo.jwt.filterLogic.JwtTokenProvider
import chan.spring.demo.jwt.service.JwtTokenService
import chan.spring.demo.member.domain.Member
import chan.spring.demo.member.dto.request.*
import chan.spring.demo.member.log.MemberServiceLog
import chan.spring.demo.member.repository.MemberRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
@Service
@Transactional
class MemberCommandService
@Autowired
constructor(
private val memberRepository: MemberRepository,
private val authenticationManagerBuilder: AuthenticationManagerBuilder,
private val jwtTokenProvider: JwtTokenProvider,
private val jwtTokenService: JwtTokenService
) {
fun signup(signupDto: SignupDto) {
with(signupDto) {
Member.create(email!!, pw!!).also {
memberRepository.save(it)
}
}
}
fun login(loginDto: LoginDto): JwtTokenInfo {
val authentication: Authentication =
authenticationManagerBuilder
.`object`
.authenticate(UsernamePasswordAuthenticationToken(loginDto.email, loginDto.pw))
return jwtTokenProvider.generateToken(authentication).also {
jwtTokenService.createRefreshToken(it.id, it.refreshToken)
}
}
fun reissueJwtToken(
id: UUID,
refreshToken: String
): JwtTokenInfo {
val auth = memberRepository.findAuthById(id)
return jwtTokenService.reissueToken(id, refreshToken, auth)
}
fun updatePassword(
updatePasswordDto: UpdatePasswordDto,
id: UUID
) {
with(updatePasswordDto) {
memberRepository.findMemberById(id).also { it.updatePw(newPassword!!, oldPassword!!) }
}
}
fun logout(id: UUID) {
jwtTokenService.removeRefreshToken(id)
}
fun recoveryMember(recoveryDto: RecoveryDto) {
with(recoveryDto) {
memberRepository.findMemberByEmailIncludeWithdraw(email!!).also { it.recovery(pw!!) }
}
}
fun withdraw(
withdrawDto: WithdrawDto,
id: UUID
) {
memberRepository.findMemberById(id)
.takeIf { isMatchPassword(withdrawDto.pw!!, it.pw) }
?.also {
it.withdraw()
jwtTokenService.removeRefreshToken(id)
}
?: run {
logger().warn(MemberServiceLog.WRONG_PW + id)
throw MemberException(MemberExceptionMessage.WRONG_PASSWORD, id.toString())
}
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/service/command/MemberCommandService.kt | 736695683 |
package chan.spring.demo.member.service.query
import chan.spring.demo.member.repository.MemberCustomRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
@Service
@Transactional(readOnly = true)
class MemberQueryService
@Autowired
constructor(
private val memberRepository: MemberCustomRepository
) {
fun getMemberById(id: UUID) = memberRepository.findMemberInfoById(id)
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/service/query/MemberQueryService.kt | 1842247072 |
package chan.spring.demo.member.domain.constant
object MemberConstant {
const val PW_TYPE = "VARCHAR(100)"
const val ROLE_TYPE = "VARCHAR(13)"
const val ADMIN_EMAIL = "[email protected]"
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/domain/constant/MemberConstant.kt | 374465378 |
package chan.spring.demo.member.domain
import chan.spring.demo.converter.RoleConverter
import chan.spring.demo.exception.exception.MemberException
import chan.spring.demo.exception.message.MemberExceptionMessage
import chan.spring.demo.globalUtil.UUID_TYPE
import chan.spring.demo.globalUtil.createUUID
import chan.spring.demo.globalUtil.encodePassword
import chan.spring.demo.globalUtil.isMatchPassword
import chan.spring.demo.member.domain.constant.MemberConstant
import jakarta.persistence.*
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import java.util.*
@Entity
class Member private constructor(
@Id @Column(columnDefinition = UUID_TYPE) val id: UUID = createUUID(),
@Convert(converter = RoleConverter::class) @Column(
nullable = false,
columnDefinition = MemberConstant.ROLE_TYPE
) var auth: Role,
@Column(nullable = false, unique = true) val email: String,
@Column(nullable = false, columnDefinition = MemberConstant.PW_TYPE) var pw: String
) : UserDetails {
companion object {
private fun findFitAuth(email: String) = if (email == MemberConstant.ADMIN_EMAIL) Role.ADMIN else Role.MEMBER
fun create(
email: String,
pw: String
): Member {
return Member(
auth = findFitAuth(email),
email = email,
pw = encodePassword(pw)
)
}
}
fun isAdmin() = auth == Role.ADMIN
fun updatePw(
newPassword: String,
oldPassword: String
) {
require(isMatchPassword(oldPassword, pw)) {
throw MemberException(MemberExceptionMessage.WRONG_PASSWORD, id.toString())
}
pw = encodePassword(newPassword)
}
fun withdraw() {
this.auth = Role.WITHDRAW
}
fun recovery(inputPw: String) {
require(
isMatchPassword(inputPw, pw)
) { throw MemberException(MemberExceptionMessage.WRONG_PASSWORD, id.toString()) }
this.auth = Role.MEMBER
}
override fun getAuthorities(): MutableCollection<out GrantedAuthority> =
arrayListOf<GrantedAuthority>(SimpleGrantedAuthority(auth.auth))
override fun getUsername() = id.toString()
override fun getPassword() = pw
override fun isAccountNonExpired() = true
override fun isAccountNonLocked() = true
override fun isCredentialsNonExpired() = true
override fun isEnabled() = true
}
| chan-spring/src/main/kotlin/chan/spring/demo/member/domain/Member.kt | 906973947 |
package chan.spring.demo.member.domain
enum class Role(val auth: String) { MEMBER("ROLE_MEMBER"), ADMIN("ROLE_ADMIN"), WITHDRAW("ROLE_WITHDRAW") }
| chan-spring/src/main/kotlin/chan/spring/demo/member/domain/Role.kt | 4153554959 |
package chan.spring.demo.globalUtil
import java.util.*
const val UUID_TYPE = "BINARY(16)"
fun createUUID(): UUID = UUID.randomUUID()
| chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/UUIDUtil.kt | 3617902517 |
package chan.spring.demo.globalUtil
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
const val DATETIME_TYPE = "BIGINT(12)"
const val DATE_TYPE = "INT(8)"
fun getCurrentTimestamp(): Int {
return Instant.now().epochSecond.toInt()
}
fun getDatetimeDigit(dateTime: LocalDateTime): Long {
val year = dateTime.year.toString()
val month = checkSingleDigit(dateTime.monthValue)
val day = checkSingleDigit(dateTime.dayOfMonth)
val hour = checkSingleDigit(dateTime.hour)
val minute = checkSingleDigit(dateTime.minute)
return "$year$month$day$hour$minute".toLong()
}
fun getDateDigit(date: LocalDate): Int {
val year = date.year.toString()
val month = checkSingleDigit(date.monthValue)
val day = checkSingleDigit(date.dayOfMonth)
return "$year$month$day".toInt()
}
fun convertDateToLocalDate(date: Int): LocalDate {
val stringDate = date.toString()
val year = stringDate.substring(0, 4).toInt()
val month = stringDate.substring(4, 6).toInt()
val day = stringDate.substring(6).toInt()
return LocalDate.of(year, month, day)
}
private fun checkSingleDigit(digit: Int): String {
return if (digit in 0..9) {
"0$digit"
} else {
digit.toString()
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/DateTimeUtil.kt | 1438188613 |
package chan.spring.demo.globalUtil
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
fun encodePassword(password: String): String = BCryptPasswordEncoder().encode(password)
fun isMatchPassword(
password: String,
originalEncodedPassword: String
) = BCryptPasswordEncoder().matches(password, originalEncodedPassword)
| chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/PasswordUtil.kt | 455926569 |
package chan.spring.demo.globalUtil
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.core.types.dsl.EntityPathBase
import com.querydsl.core.types.dsl.NumberPath
fun <T, Q : EntityPathBase<T>> ltLastId(
lastId: Long?,
qEntity: Q,
idPathExtractor: (Q) -> NumberPath<Long>
): BooleanExpression? {
return lastId?.takeIf { it > 0 }?.let { idPathExtractor(qEntity).lt(it) }
}
fun <T, Q : EntityPathBase<T>> ltLastTimestamp(
lastTimestamp: Int?,
qEntity: Q,
timestampPathExtractor: (Q) -> NumberPath<Int>
): BooleanExpression? {
return lastTimestamp?.takeIf { it > 0 }?.let { timestampPathExtractor(qEntity).lt(it) }
}
fun <T> findLastIdOrDefault(
foundData: List<T>,
idExtractor: (T) -> Long
): Long {
return foundData.lastOrNull()?.let { idExtractor(it) } ?: 0
}
| chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/PageQueryUtil.kt | 864612930 |
package chan.spring.demo.exception.controllerAdvice
import chan.spring.demo.exception.controllerAdvice.constant.GlobalAdviceConstant
import jakarta.validation.ConstraintViolationException
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import java.util.*
@RestControllerAdvice
class GlobalControllerAdvice {
@ExceptionHandler(DataIntegrityViolationException::class)
fun handleDuplicateEntityValueException(): ResponseEntity<String> {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(GlobalAdviceConstant.DUPLICATE_ENTITY_VAL)
}
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationExceptions(exception: MethodArgumentNotValidException): ResponseEntity<String> {
val bindingResult = exception.bindingResult
val errorMessage =
Objects
.requireNonNull(bindingResult.fieldError)
?.defaultMessage
return ResponseEntity.badRequest().body(errorMessage)
}
@ExceptionHandler(ConstraintViolationException::class)
fun handleConstraintViolationException(ex: ConstraintViolationException): ResponseEntity<*> {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(ex.message)
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/GlobalControllerAdvice.kt | 2822401591 |
package chan.spring.demo.exception.controllerAdvice
import chan.spring.demo.exception.controllerAdvice.constant.MemberAdviceConstant
import chan.spring.demo.exception.exception.JwtCustomException
import chan.spring.demo.exception.exception.MemberException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
@RestControllerAdvice
class MemberControllerAdvice {
@ExceptionHandler(BadCredentialsException::class)
fun handleLoginFail(): ResponseEntity<String> {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(MemberAdviceConstant.LOGIN_FAIL)
}
@ExceptionHandler(MemberException::class)
fun handleMemberException(memberException: MemberException): ResponseEntity<String> {
return ResponseEntity
.status(memberException.memberExceptionMessage.status)
.body(memberException.message + memberException.memberIdentifier)
}
@ExceptionHandler(JwtCustomException::class)
fun handleJwtCustomException(jwtCustomException: JwtCustomException): ResponseEntity<String> {
return ResponseEntity
.status(jwtCustomException.jwtExceptionMessage.status)
.body(jwtCustomException.message)
}
}
| chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/MemberControllerAdvice.kt | 2337200362 |
package chan.spring.demo.exception.controllerAdvice.constant
object MemberAdviceConstant {
const val LOGIN_FAIL = "๋ก๊ทธ์ธ์ ์คํจํ์ต๋๋ค."
}
| chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/constant/MemberAdviceConstant.kt | 3500484945 |
package chan.spring.demo.exception.controllerAdvice.constant
object GlobalAdviceConstant {
const val DUPLICATE_ENTITY_VAL = "๋ฐ์ดํฐ ๋ฒ ์ด์ค ๋ฌด๊ฒฐ์ฑ ์กฐ๊ฑด์ ์๋ฐํ์์ต๋๋ค."
}
| chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/constant/GlobalAdviceConstant.kt | 2613627020 |
package chan.spring.demo.exception.message
enum class JwtExceptionMessage(val status: Int, val message: String) {
TOKEN_IS_NULL(404, "Token Is Null"),
INVALID_TOKEN(401, "Invalid JWT Token"),
EXPIRED_JWT_TOKEN(401, "Expired Jwt Token"),
UNSUPPORTED_TOKEN(401, "Unsupported JWT Token"),
EMPTY_CLAIMS(404, "JWT claims string is empty."),
NOT_EXIST_REFRESH_TOKEN(404, "Refresh Token is not exist"),
UN_MATCH_REFRESH_TOKEN(401, "Un Match Refresh Token")
}
| chan-spring/src/main/kotlin/chan/spring/demo/exception/message/JwtExceptionMessage.kt | 3631953171 |
package chan.spring.demo.exception.message
enum class MemberExceptionMessage(val status: Int, val message: String) {
WRONG_PASSWORD(400, "๋น๋ฐ๋ฒํธ๋ฅผ ํ๋ ธ์ต๋๋ค. ํ์์๋ณ์ : "),
MEMBER_IS_NULL(404, "ํ์์ด ์กด์ฌํ์ง ์์ต๋๋ค. ํ์์๋ณ์ : "),
TOKEN_REISSUE_HEADER_IS_NULL(404, "ํ ํฐ ๊ฐฑ์ ํค๋๊ฐ ๋น์ด์์ต๋๋ค.")
}
| chan-spring/src/main/kotlin/chan/spring/demo/exception/message/MemberExceptionMessage.kt | 2826933838 |
package chan.spring.demo.exception.exception
import chan.spring.demo.exception.message.MemberExceptionMessage
class MemberException(
val memberExceptionMessage: MemberExceptionMessage,
val memberIdentifier: String?
) : RuntimeException(memberExceptionMessage.message)
| chan-spring/src/main/kotlin/chan/spring/demo/exception/exception/MemberException.kt | 508066932 |
package chan.spring.demo.exception.exception
import chan.spring.demo.exception.message.JwtExceptionMessage
class JwtCustomException(val jwtExceptionMessage: JwtExceptionMessage) : RuntimeException(jwtExceptionMessage.message)
| chan-spring/src/main/kotlin/chan/spring/demo/exception/exception/JwtCustomException.kt | 1319417922 |
package com.example.aesdecryption
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.aesdecryption", appContext.packageName)
}
} | AesDecryption/app/src/androidTest/java/com/example/aesdecryption/ExampleInstrumentedTest.kt | 3254532223 |
package com.example.aesdecryption
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | AesDecryption/app/src/test/java/com/example/aesdecryption/ExampleUnitTest.kt | 401737945 |
package com.example.aesdecryption
fun Char.fromHexToInt() : Int {
return if(this in '0' .. '9') this.code - '0'.code
else this.code - 'a'.code + 10
} | AesDecryption/app/src/main/java/com/example/aesdecryption/Extension.kt | 4088452463 |
package com.example.aesdecryption
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.aesdecryption.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.ServerSocket
import java.net.Socket
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
private val aes = CBC()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
decryptButton.setOnClickListener {
if(inputEditText.text?.isNotEmpty() == true){
CoroutineScope(Dispatchers.Main).launch{
val res = async(Dispatchers.Default){
aes.decrypt(inputEditText.text.toString())
}.await()
output.setText(res)
}
}
else{
Toast.makeText(this@MainActivity,"Fill in all information",Toast.LENGTH_SHORT).show()
}
}
}
val socket = ServerSocket(50000)
try{
CoroutineScope(Dispatchers.IO).launch {
while(true){
val client = socket.accept()
val reader = BufferedReader(InputStreamReader(client.getInputStream()))
val secretKey = reader.readLine()
val iv = reader.readLine()
val cipher = reader.readLine()
withContext(Dispatchers.Main){
binding.inputEditText.setText(cipher)
}
aes.setIV(iv)
aes.setSecretKey(secretKey)
}
}
}catch(ex : Exception) {
ex.printStackTrace()
}
}
} | AesDecryption/app/src/main/java/com/example/aesdecryption/MainActivity.kt | 2666287106 |
package com.example.aesdecryption
val iSBox = arrayOf(
arrayOf( 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb ),
arrayOf( 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb ),
arrayOf( 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e ),
arrayOf( 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 ),
arrayOf( 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 ),
arrayOf( 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 ),
arrayOf( 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 ),
arrayOf( 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b ),
arrayOf( 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 ),
arrayOf( 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e ),
arrayOf( 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ),
arrayOf( 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 ),
arrayOf( 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f ),
arrayOf( 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef ),
arrayOf( 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 ),
arrayOf( 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6,0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d )
)
val invMixCol = arrayOf(
arrayOf(0x0e, 0x0b, 0x0d, 0x09),
arrayOf(0x09, 0x0e, 0x0b, 0x0d),
arrayOf(0x0d, 0x09, 0x0e, 0x0b),
arrayOf(0x0b, 0x0d, 0x09, 0x0e)
)
val sBox = arrayOf(
arrayOf(0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76),
arrayOf(0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0),
arrayOf(0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15),
arrayOf(0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75),
arrayOf(0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84),
arrayOf(0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF),
arrayOf(0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8),
arrayOf(0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2),
arrayOf(0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73),
arrayOf(0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB),
arrayOf(0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79),
arrayOf(0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08),
arrayOf(0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A),
arrayOf(0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E),
arrayOf(0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF),
arrayOf(0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)
)
val roundConstant = arrayOf(0,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a) | AesDecryption/app/src/main/java/com/example/aesdecryption/Constant.kt | 225282360 |
package com.example.aesdecryption
import android.util.Log
class CBC {
private lateinit var _secretKey : String
private lateinit var iv : Array<Array<Int>>
private var word = Array(4){Array(4){0} }
private var numOfRound : Int = 0
private val numOfRoundKeyMap = mapOf(16 to 44,24 to 52,32 to 60)
fun setIV(temp : String) {
iv = Array(4){Array(4){0} }
for(i in 0 until 4){
for(j in 0 until 4){
iv[i][j] = temp[4*i+j].fromHexToInt()
}
}
}
private fun rotWord(word : Array<Int>) : Array<Int>{
val temp = word[0]
for(i in 0 until 3){
word[i] = word[i+1]
}
word[3] = temp
return word
}
fun subWord(word : Array<Int>) : Array<Int>{
for(i in 0 until 4){
word[i] = subByte(word[i])
}
return word
}
fun subByte(byte : Int ) : Int{
return throughSBox(byte)
}
private fun throughSBox(value : Int) : Int{
var hex = Integer.toHexString(value)
hex = padByte(hex)
val first = hex[0].fromHexToInt()
val second = hex[1].fromHexToInt()
return sBox[first][second]
}
fun copyWord(a : Array<Int>,b : Array<Int>) {
for(i in 0 until 4){
a[i] = b[i]
}
}
fun rCon(word : Array<Int>,round : Int) : Array<Int>{
word[0] = word[0] xor roundConstant[round]
return word
}
fun keyExpansion(){
val keyLength = _secretKey.length/2
for(i in 0 until keyLength/4){
for(j in 0 until 4){
word[i][j] = "${_secretKey[2*(4*i+j)]}${_secretKey[2*(4*i+j)+1]}".toInt(16)
}
}
for(i in keyLength/4 until numOfRoundKeyMap[keyLength]!!){
for(j in 0 until 4){
var temp = Array(4){0}
copyWord(temp,word[i-1])
if(i%(keyLength/4) == 0){
temp = rCon(subWord(rotWord(temp)),i/(keyLength/4))
}
word[i] = xorWord(temp,word[i-(keyLength/4)])
}
}
for(j in 0 until 44){
val i = 0
Log.i("word[$] ","${word[j][i] } ${word[j][i+1] } ${word[j][i+2] } ${word[j][i+3] }")
}
}
fun setSecretKey(key : String){
_secretKey = key
when(_secretKey.length){
32 -> {
numOfRound = 10
word = Array(44){Array(4){0} }
}
48 -> {
numOfRound = 12
word = Array(52){Array(4){0} }
}
64 -> {
numOfRound = 14
word = Array(60){Array(4){0} }
}
}
keyExpansion()
}
private fun hexToState(hex : String,blocks : Int) : Array<Array<Array<Int>>>{
val state = Array(blocks){Array(4){Array(4){0} } }
for(i in 0 until blocks){
for(j in 0 until 4){
for(k in 0 until 4){
state[i][j][k] = "${hex[i*32+j*8+2*k]}${hex[i*32+j*8+2*k+1]}".toInt(16)
}
}
}
return state
}
private fun copy(a1 : Array<Array<Int>>,a2 : Array<Array<Int>>){
for(i in 0 until 4){
for(j in 0 until 4){
a2[i][j] = a1[i][j]
}
}
}
fun addRoundKey(state : Array<Array<Int>>,round : Int){
for(i in 0 until 4){
state[i] = xorWord(state[i], word[4*round + i])
}
}
fun invSubState(state: Array<Array<Int>>){
for(i in 0 until 4){
for(j in 0 until 4){
state[i][j] = invSubByte(state[i][j])
}
}
}
fun intArrayToPlainText(state : Array<Array<Array<Int>>>,blocks : Int) : String{
var res = ""
for(k in 0 until blocks){
if(k == blocks - 1){
if(state[k][3][3] <= 15){
var temp = state[k][3][3]
var isPadded = true
var i = 3
var j = 3
while(temp > 0){
if(state[k][i][j] != state[k][3][3]){
isPadded = false
break
}
j--
if(j == -1){
i--
j = 3
}
temp--
}
if(isPadded){
if(0 == state[k+1][0][0]){
i = 0
j = 0
temp = 0
while(temp < 16 - state[k][3][3]){
res += state[k][i][j].toChar()
j++
if(j == 4){
i++
j = 0
}
temp++
}
return res
}
}
}
}
for(i in 0 until 4){
for(j in 0 until 4){
res += state[k][i][j].toChar()
}
}
}
return res
}
private fun throughISBox(value : Int) : Int{
var hex = Integer.toHexString(value)
hex = padByte(hex)
val first = hex[0].fromHexToInt()
val second = hex[1].fromHexToInt()
return iSBox[first][second]
}
fun invSubByte(byte : Int) : Int{
return throughISBox(byte)
}
fun padByte(str : String) : String{
var res = str
if(str.length == 1){
res = "0${str}"
}
return res
}
fun byteMultiplication(byte1 : Int,byte2 : Int) : Int{
if(byte2 == 0x01) return byte1
var res = 0
var a = byte1
var b = byte2
for(i in 0 until 8){
if(b and 0x01 == 0x01){
res = a xor res
}
var temp = 0
if(a and 0x80 == 0x80){
temp = 0x1b
}
a = (a shl 1)%256 xor temp
b = b shr 1
}
return res
}
fun invMixColumn(state : Array<Array<Int>>) : Array<Array<Int>>{
val temp = Array(4){Array(4){0} }
for(i in 0 until 4){
for(j in 0 until 4){
for(k in 0 until 4){
temp[j][i] = temp[j][i] xor byteMultiplication(invMixCol[i][k],state[j][k])
}
}
}
return temp
}
fun xorWord(word1 : Array<Int>,word2 : Array<Int>) : Array<Int>{
for(i in 0 until 4){
word1[i] = word1[i] xor word2[i]
}
return word1
}
fun xor4Words(state : Array<Array<Int>>,iV : Array<Array<Int>>){
for(i in 0 until 4){
state[i] = xorWord(state[i], iV[i])
}
}
fun invShiftRow(state : Array<Array<Int>>){
for(i in 1 until 4){
for(k in 0 until i){
val temp = state[3][i]
for (j in 3 downTo 1){
state[j][i] = state[j-1][i]
}
state[0][i] = temp
}
}
}
fun decrypt(cipherText : String) : String{
var iVTemp = iv
val blocks = cipherText.length/16/2
val state = hexToState(cipherText,blocks)
for(n in 0 until blocks-1){
// Store Cn-1
val temp = Array(4){Array(4){0}}
copy(state[n],temp)
// Pn = Cn-1 xor D(Kn,Cn)
addRoundKey(state[n],numOfRound)
for(i in numOfRound-1 downTo 1){
invShiftRow(state[n])
invSubState(state[n])
addRoundKey(state[n],i)
state[n] = invMixColumn(state[n])
}
invShiftRow(state[n])
invSubState(state[n])
addRoundKey(state[n],0)
xor4Words(state[n],iVTemp)
iVTemp = temp
}
return intArrayToPlainText(state,blocks-1)
}
} | AesDecryption/app/src/main/java/com/example/aesdecryption/CBC.kt | 3322770181 |
package ru.dmitriyt.graphtreeanalyser
import org.junit.jupiter.api.Test
import ru.dmitriyt.graphtreeanalyser.data.GraphCache
import ru.dmitriyt.graphtreeanalyser.data.TreeUtil
import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePack2Type
import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePackEquals1
import kotlin.test.assertEquals
class ReducedTreePack2TypeSubGraphs {
// [:H`ESgp`^, :H`EKWTjB, :H`EKWT`B, :H`EKIOlB, :H`EKIO`B]
@Test
fun test() {
val graph6 = ":H`ESgp`^"
val type = ReducedTreePack2Type.solve(GraphCache[graph6])
assertEquals(1, type)
}
} | graph-tree-analyser/src/test/kotlin/ru/dmitriyt/graphtreeanalyser/ReducedTreePack2TypeSubGraphs.kt | 2285201469 |
package ru.dmitriyt.graphtreeanalyser
class Args(
val n: Int,
val isMulti: Boolean = DEFAULT_IS_MULTI,
val partSize: Int = DEFAULT_PART_SIZE,
val useCache: Boolean = false,
) {
companion object {
const val DEFAULT_IS_MULTI = false
const val DEFAULT_PART_SIZE = 64
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/Args.kt | 2960125869 |
package ru.dmitriyt.graphtreeanalyser
import kotlinx.coroutines.runBlocking
import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePack2Type
import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePackEquals2
import ru.dmitriyt.graphtreeanalyser.presentation.graphs
fun main(rawArgs: Array<String>): Unit = runBlocking {
// repeat(20) {
// val args = ArgsManager(rawArgs).parse()
val args = Args(
n = 12,
isMulti = 12 > 10,
)
graphs(n = args.n) {
multiThreadingEnabled = args.isMulti
generate(generator = "gentreeg")
.filter(ReducedTreePackEquals2)
.apply {
calculateInvariant(ReducedTreePack2Type)
}
}
// }
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/Main.kt | 113726303 |
package ru.dmitriyt.graphtreeanalyser.data
sealed class AbstractGraphCode {
data class SingleComponent(val code: List<Int>) : AbstractGraphCode()
data class MultiComponent(val codes: List<List<Int>>) : AbstractGraphCode()
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/AbstractGraphCode.kt | 3592977748 |
package ru.dmitriyt.graphtreeanalyser.data.repository
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import ru.dmitriyt.graphtreeanalyser.domain.SolveResult
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphResult
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo
import java.io.File
object SolveRepository {
private val solveStorage = File("results").apply {
if (!exists()) {
mkdir()
}
}
private val gson = GsonBuilder().setPrettyPrinting().create()
fun get(graphTaskInfo: GraphTaskInfo, n: Int): SolveResult? {
val file = getSolveFile(graphTaskInfo, n)
if (!file.exists()) return null
return runCatching {
when (graphTaskInfo) {
is GraphTaskInfo.Condition -> {
val typeToken = object : TypeToken<List<String>>() {}.type
SolveResult.Condition(
graphs = gson.fromJson(file.readLines().joinToString("\n"), typeToken),
)
}
is GraphTaskInfo.Invariant -> {
val typeToken = object : TypeToken<Map<String, Int>>() {}.type
SolveResult.Invariant(
invariants = gson.fromJson<Map<String, Int>>(file.readLines().joinToString("\n"), typeToken)
.map { GraphResult(it.key, it.value) },
)
}
}
}
.onFailure {
it.printStackTrace()
}
.getOrNull()
}
fun set(graphTaskInfo: GraphTaskInfo, n: Int, solveResult: SolveResult) {
val file = getSolveFile(graphTaskInfo, n)
file.createNewFile()
when (solveResult) {
is SolveResult.Condition -> {
file.writeText(gson.toJson(solveResult.graphs))
}
is SolveResult.Invariant -> {
file.writeText(gson.toJson(solveResult.invariants.map { it.graph6 to it.invariant }.toMap()))
}
}
}
private fun getSolveFile(graphTaskInfo: GraphTaskInfo, n: Int): File {
val graphTaskName = when (graphTaskInfo) {
is GraphTaskInfo.Invariant -> graphTaskInfo.task.toString()
is GraphTaskInfo.Condition -> graphTaskInfo.task.toString()
}
return File(solveStorage, "${graphTaskName}_$n.json")
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/repository/SolveRepository.kt | 2148973004 |
package ru.dmitriyt.graphtreeanalyser.data
fun Graph.getAbstractCode(): AbstractGraphCode {
val components = getComponents()
fun getTreeCode(tree: Graph): List<Int> {
val center = TreeUtil.getTreeCenter(tree)
return TreeUtil.getCanonicalCode(tree, center)
}
return if (components.size == 1) {
AbstractGraphCode.SingleComponent(getTreeCode(components.first()))
} else {
AbstractGraphCode.MultiComponent(components.map { getTreeCode(it) }.sortedBy { it.toCodeString() })
}
}
fun Graph.getComponents(): List<Graph> {
val components = mutableListOf<List<Int>>()
val vertexes = mapList.keys
val visited = mutableMapOf<Int, Boolean>()
vertexes.forEach { visited[it] = false }
while (!visited.all { it.value }) {
val componentVertexes = TreeUtil.dfsWithoutEdge(this, vertexes.first { visited[it] == false }, -1)
componentVertexes.forEach {
visited[it] = true
}
components.add(componentVertexes)
}
return components.map { componentVertexes ->
Graph(
mapList.filter { componentVertexes.contains(it.key) }.map { entry ->
entry.key to entry.value.filter { componentVertexes.contains(it) }
}.toMap()
)
}
}
object TreeUtil {
fun bfs(g: Graph, source: Int): List<Int> {
val d = MutableList(g.n) { Int.MAX_VALUE }
d[source] = 0
val q = ArrayDeque<Int>()
q.addLast(source)
while (q.isNotEmpty()) {
val u = q.removeLast()
g.mapList[u].orEmpty().forEach { v ->
if (d[v] == Int.MAX_VALUE) {
d[v] = d[u] + 1
q.addLast(v)
}
}
}
return d
}
fun getTreeCenterVertexes(g: Graph): Set<Int> {
val actualVertexes = g.mapList.keys.toMutableSet()
while (actualVertexes.size > 2) {
val vertexesToRemove = mutableListOf<Int>()
g.mapList.forEach { (vertex, vertexes) ->
if (actualVertexes.contains(vertex)) {
if (vertexes.count { actualVertexes.contains(it) } == 1) {
vertexesToRemove.add(vertex)
}
}
}
vertexesToRemove.forEach { vertex ->
actualVertexes.remove(vertex)
}
}
return actualVertexes
}
fun getTreeCenter(g: Graph): Int {
val actualVertexes = getTreeCenterVertexes(g)
if (actualVertexes.size == 1) {
return actualVertexes.first()
}
val center1 = actualVertexes.first()
val center2 = actualVertexes.last()
val graph1Vertexes = dfsWithoutEdge(g, center1, center2)
val graph2Vertexes = dfsWithoutEdge(g, center2, center1)
if (graph1Vertexes.size < graph2Vertexes.size) {
return center1
}
if (graph2Vertexes.size < graph1Vertexes.size) {
return center2
}
val graph1 = g.filterVertexes { graph1Vertexes.contains(it) }
val graph2 = g.filterVertexes { graph2Vertexes.contains(it) }
return if (getCanonicalCode(graph1, center1).toCodeString() >= getCanonicalCode(
graph2,
center2
).toCodeString()
) {
center1
} else {
center2
}
}
fun dfsWithoutEdge(g: Graph, start: Int, skip: Int): List<Int> {
val visited = mutableMapOf<Int, Boolean>()
fun dfs(u: Int) {
visited[u] = true
g.mapList[u]?.forEach { vertex ->
if (vertex != skip && visited[vertex] != true) {
dfs(vertex)
}
}
}
dfs(start)
return visited.filter { it.value }.keys.toList()
}
fun getCanonicalCode(g: Graph, center: Int): List<Int> = try {
val codes = g.mapList.map { entry -> entry.key to mutableListOf<Int>() }.toMap().toMutableMap()
val leaves = g.getLeaves()
leaves.forEach { vertex ->
codes[vertex]?.add(1)
}
val levels = dijkstra(g, center)
val used = mutableListOf<Int>()
g.mapList.keys.forEach { i ->
if (codes[i]?.isEmpty() == true && i != center) {
used.add(i)
codeHelper(g, center, codes, i, null, used, levels)
}
}
var count = 1
repeat(g.mapList[center]!!.size) { i ->
count += codes[g.mapList[center]!![i]]?.get(0) ?: 0
}
codes[center]?.add(count)
val h = mutableListOf<List<Int>>()
repeat(g.mapList[center]!!.size) { i ->
h.add(codes[g.mapList[center]?.get(i)]!!)
}
h.sortBy { it.toCodeString() }
h.forEach { hi ->
hi.forEach { hij ->
codes[center]?.add(hij)
}
}
val code = mutableListOf<Int>()
codes[center]?.forEach {
code.add(it)
}
code
} catch (e: Exception) {
throw e
}
private fun codeHelper(
g: Graph,
center: Int,
codes: MutableMap<Int, MutableList<Int>>,
start: Int,
parent: Int?,
used: MutableList<Int>,
levels: Map<Int, Int>
) {
g.mapList[start]?.forEach { v ->
if (v != center && codes[v]?.size == 0 && v != parent && !used.contains(v) && levels[v]!! >= levels[start]!!) {
codeHelper(g, center, codes, v, parent, used, levels)
}
}
var count = 1
g.mapList[start]?.forEach { v ->
if (v != parent && v != center && levels[v]!! >= levels[start]!!) {
count += codes[v]?.get(0)!!
}
}
codes[start]?.add(count)
val h = mutableListOf<List<Int>>()
g.mapList[start]?.forEach { v ->
if (v != parent && v != center && levels[v]!! >= levels[start]!!) {
h.add(codes[v].orEmpty())
}
}
h.sortBy { it.toCodeString() }
h.forEach { hi ->
hi.forEach { hij ->
codes[start]?.add(hij)
}
}
}
private fun dijkstra(g: Graph, center: Int): Map<Int, Int> {
val used = mutableSetOf<Int>()
val d = g.mapList.map { entry -> entry.key to Int.MAX_VALUE }.toMap().toMutableMap()
d[center] = 0
repeat(g.mapList.size) {
var v: Int? = null
g.mapList.keys.forEach { j ->
if (!used.contains(j) && (v == null || d[j]!! < d[v]!!)) {
v = j
}
}
if (v == null) {
return d
}
used.add(v!!)
g.mapList[v]?.forEach { j ->
if (d[v]!! + 1 < d[j]!!) {
d[j] = d[v]!! + 1
}
}
}
return d
}
}
fun List<Int>.toCodeString(): String {
return map { 'a' + it }.joinToString("")
}
fun Graph.getLeaves(): List<Int> {
val leaves = mutableListOf<Int>()
mapList.forEach { (vertex, vertexes) ->
if (vertexes.size == 1) {
leaves.add(vertex)
}
}
return leaves
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/TreeUtil.kt | 1448146436 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
open class AbstractCondition(private val graphInvariant: GraphInvariant, private val invariantValue: Int) : GraphCondition {
override fun check(graph: Graph): Boolean {
return graphInvariant.solve(graph) == invariantValue
}
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/AbstractCondition.kt | 3834714781 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.getLeaves
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
data object LeavesCount : GraphInvariant {
override fun solve(graph: Graph): Int {
return graph.getLeaves().size
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/LeavesCount.kt | 2444742619 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
data object TreeCenterSizeEquals1 : AbstractCondition(graphInvariant = TreeCenterSize, invariantValue = 1) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeCenterSizeEquals1.kt | 3048121768 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.TreeUtil.bfs
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
data object TreeRadius : GraphInvariant {
override fun solve(graph: Graph): Int {
val e = graph.mapList.keys.map { bfs(graph, it).max() }
return e.min()
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeRadius.kt | 517861763 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
data object ReducedTreePackEquals2 : AbstractCondition(graphInvariant = ReducedTreePack, invariantValue = 2) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePackEquals2.kt | 145180486 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition
import ru.dmitriyt.graphtreeanalyser.presentation.and
data object TreeIsStarBicentral : GraphCondition by (ReducedTreePackEquals1 and TreeCenterSizeEquals2) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeIsStarBicentral.kt | 3811171220 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.TreeUtil
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
data object TreeCenterSize : GraphInvariant {
override fun solve(graph: Graph): Int {
return TreeUtil.getTreeCenterVertexes(graph).size
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeCenterSize.kt | 1307197563 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
data object ReducedTreePackEquals1 : AbstractCondition(graphInvariant = ReducedTreePack, invariantValue = 1) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePackEquals1.kt | 4229454435 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.TreeUtil.bfs
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
data object TreeDiameter : GraphInvariant {
override fun solve(graph: Graph): Int {
val u = bfs(graph, 0).withIndex().maxBy { it.value }.index
return bfs(graph, u).max()
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeDiameter.kt | 1386781881 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.AbstractGraphCode
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.getAbstractCode
import ru.dmitriyt.graphtreeanalyser.data.getLeaves
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
data object ReducedTreePack : GraphInvariant {
override fun solve(graph: Graph): Int {
val treePack = mutableListOf<AbstractGraphCode>()
val leaves = graph.getLeaves()
leaves.forEach { vertex ->
val newGraph = graph.filterVertexes { it != vertex }
treePack.add(newGraph.getAbstractCode())
}
return treePack.toSet().size
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePack.kt | 35483751 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
data object TreeCenterSizeEquals2 : AbstractCondition(graphInvariant = TreeCenterSize, invariantValue = 2) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeCenterSizeEquals2.kt | 1814221767 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition
import ru.dmitriyt.graphtreeanalyser.presentation.and
data object TreeIsStarCentral : GraphCondition by (ReducedTreePackEquals1 and TreeCenterSizeEquals1) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeIsStarCentral.kt | 3923409644 |
package ru.dmitriyt.graphtreeanalyser.data.algorithm
import ru.dmitriyt.graphtreeanalyser.data.AbstractGraphCode
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.TreeUtil
import ru.dmitriyt.graphtreeanalyser.data.getAbstractCode
import ru.dmitriyt.graphtreeanalyser.data.getLeaves
import ru.dmitriyt.graphtreeanalyser.domain.Logger
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
data object ReducedTreePack2Type : GraphInvariant {
override fun solve(graph: Graph): Int {
val type = getGraphType(graph)
println("GRAPH_TYPE = $type")
return type
}
private fun getGraphType(graph: Graph): Int {
val graphs = getScSbSubGraphs(graph) ?: run {
// ะฟะพะปััะธะปะธ ะฑะพะปััะต ะดะฒัั
ะบะพะผะฟะพะฝะตะฝั SC/SB
Logger.e("ะฟะพะปััะธะปะธ ะฑะพะปััะต ะดะฒัั
ะบะพะผะฟะพะฝะตะฝั SC/SB")
return 0
}
if (graphs.size == 2) {
// ะฝะฐัะปะธ ะดะฒะฐ ะบะฐะบะธั
ัะพ ะฟะพะดะณัะฐัะฐ SC ะธะปะธ SB
val graph1 = graphs[0]
val graph2 = graphs[1]
if (TreeIsStarCentral.check(graph1) && TreeIsStarCentral.check(graph2)) {
// ะดะฒะฐ SC ะณัะฐัะฐ
// ะฟัะพะฒะตัะธะผ ััะพ ะฟะตัะตัะตะบะฐัััั ะพะฝะธ ัะพะปัะบะพ ะฟะพ ัะตะฟะธ
val commonVertexes = graph1.mapList.keys.toSet().intersect(graph2.mapList.keys.toSet())
if (commonVertexes.size == 1) {
// ััะพ ะฟััั ะฝัะปะตะฒะพะน ะดะปะธะฝั - ัะพัะบะฐ ะฟะตัะตัะตัะตะฝะธั ะดะฒัั
SC
Logger.i("ััะพ ะฟััั ะฝัะปะตะฒะพะน ะดะปะธะฝั - ัะพัะบะฐ ะฟะตัะตัะตัะตะฝะธั ะดะฒัั
SC")
return 1
} else if (commonVertexes.isNotEmpty()) {
// SC1 ะธ SC2 ั ะพะฑัะตะน ัะฐัััั ะฑะพะปััะต ัะตะผ 1 ะฒะตััะธะฝะฐ, ะธ ััะพ ะฟะพ ะธะดะตะต ัะธะฟ 3,
// ะฟะพัะพะผ ะฝะฐะดะพ ะฑัะดะตั ะดะพัะฐะฑะพัะฐัั ะฟัะพะฒะตัะบะธ ะธัะบะปััะตะฝะธั ะดััะณะธั
ะณัะฐัะพะฒ, ะตัะปะธ ะฑัะดัั
Logger.i("SC1 ะธ SC2 ั ะพะฑัะตะน ัะฐัััั ะฑะพะปััะต ัะตะผ 1 ะฒะตััะธะฝะฐ")
return 3
} else {
// ะดะฒะฐ SC ัะพะตะดะธะฝะตะฝั ัะตัะตะท ัะตะฟั (ัะตะฟั ะฒ ะฝะธั
ะฝะต ะฒั
ะพะดะธั ะฟะพ ััะพะน ะฟัะพะณะต)
val overVertexes = graph.mapList.keys - graph1.mapList.keys - graph2.mapList.keys
if (isPath(graph, overVertexes)
&& isPathConnectedToCenterOfSCB(graph, graph1, overVertexes)
&& isPathConnectedToCenterOfSCB(graph, graph2, overVertexes)
) {
Logger.i("ะดะฒะฐ SC ัะพะตะดะธะฝะตะฝั ัะตัะตะท ัะตะฟั")
return 1
} else {
val center1 = TreeUtil.getTreeCenterVertexes(graph1).first()
val center2 = TreeUtil.getTreeCenterVertexes(graph2).first()
if (graph.mapList[center1].orEmpty().contains(center2)) {
// ะดะฒะฐ SC ัะพะตะดะธะฝะตะฝั ะฟัะพััะพ ะดััะณ ั ะดััะณะพะผ ะทะฐ ะฒะตััะธะฝั ัะตัะตะท ะฝัะปะตะฒัั ัะตะฟั
Logger.i("ะดะฒะฐ SC ัะพะตะดะธะฝะตะฝั ะฟัะพััะพ ะดััะณ ั ะดััะณะพะผ ะทะฐ ะฒะตััะธะฝั ัะตัะตะท ะฝัะปะตะฒัั ัะตะฟั")
return 1
} else {
Logger.e("ะฝะฐัะปะธ ะดะฒะฐ SC, ะฝะพ ะพะฝะธ ะฝะต ัะพะตะดะธะฝะตะฝั ัะตัะตะท ัะตะฟั (ะฒะพะทะผะพะถะฝะพ ะฝัะปะตะฒัั)")
// ะฝะฐัะปะธ ะดะฒะฐ SC, ะฝะพ ะพะฝะธ ะฝะต ัะพะตะดะธะฝะตะฝั ัะตัะตะท ัะตะฟั (ะฒะพะทะผะพะถะฝะพ ะฝัะปะตะฒัั)
}
}
}
} else if (TreeIsStarBicentral.check(graph1) && TreeIsStarBicentral.check(graph2)) {
// ะดะฒะฐ BC ะณัะฐัะฐ
val center1 = TreeUtil.getTreeCenterVertexes(graph1)
val center2 = TreeUtil.getTreeCenterVertexes(graph2)
if (center1 == center2) {
// ะฐ ััั ะตััั ะฒะฐัะธะฐะฝัั, ะผั ะฝะฐัะปะธ SB ะธ SB ั ะพะดะธะฝะฐะบะพะฒัะผ ัะตะฝััะพะผ, ะฝะพ ะฒะดััะณ ั ะฝะธั
ะตัะต ะตััั ะดััะณะฐั ะพะฑัะฐั ัะฐััั
val commonVertexes = graph1.mapList.keys.toSet().intersect(graph2.mapList.keys.toSet())
if (commonVertexes.size > 2) {
// ะฟะพ ะธะดะตะต ััั ะพะฑัะฐั ัะฐััั ะฑะพะปััะต ัะตะผ ะดะฒะต ะฒะตััะธะฝั ัะตะฝััะฐะปัะฝัั
, ะฝะพ ะฑะพะปััะต ะฝะธัะตะณะพ ะฝะต ะฟัะพะฒะตััะป ะฟะพ ัะธะฟั 4
return 4
} else {
return 2
}
} else {
Logger.e("ะฝะตะฟะพะฝััะฝะฐั ะฟะพะบะฐ ััะพ ัััะบะฐ - SB ะธ SB, ะบะพัะพััะต ะธะผะตัั ัะฐะทะฝัะน ัะตะฝัั, ะฟะพ ะธะดะตะต, ัะฐะบะพะณะพ ะฝะต ะผะพะถะตั ะฑััั")
// ะฝะตะฟะพะฝััะฝะฐั ะฟะพะบะฐ ััะพ ัััะบะฐ - SB ะธ SB, ะบะพัะพััะต ะธะผะตัั ัะฐะทะฝัะน ัะตะฝัั, ะฟะพ ะธะดะตะต, ัะฐะบะพะณะพ ะฝะต ะผะพะถะตั ะฑััั
}
} else {
// ััั ะฝะตะฟัะฐะฒะธะปัะฝะพ ััะธัะฐะตะผ ะณัะฐัั, ะฝะฐ ะฟัะธะผะตัะต n9/18
Logger.e("ัะพะฒะตััะตะฝะฝะพ ะฝะตะฟะพะฝััะฝะฐั ัััะบะฐ, ะฟะพ ะธะดะตะต ัะฐะบะพะน ะฝะต ะดะพะปะถะฝะพ ะฑััั (SC ะธ SB)")
Logger.e("${getGraphStarType(graph1)} : ${graph1.mapList.keys} and ${getGraphStarType(graph2)} ${graph2.mapList.keys}")
// ัะพะฒะตััะตะฝะฝะพ ะฝะตะฟะพะฝััะฝะฐั ัััะบะฐ, ะฟะพ ะธะดะตะต ัะฐะบะพะน ะฝะต ะดะพะปะถะฝะพ ะฑััั (SC ะธ SB)
}
} else if (graphs.size == 1) {
// ะผะพะถะตั ะฑััั ัะปััะฐะน, ะบะพะณะดะฐ ะบ ัะตะฟะธ ะบัะตะฟะธััั SC ะทะฐ ัะตัะตะดะธะฝั, ั.ะต. ัะตะฟั ััะพ ะฒััะพะถะดะตะฝะฝัะน ัะปััะฐะน ะฒัะพัะพะณะพ SC (ัะฐะบ ะบะฐะบ ัะพะปัะบะพ ะพะดะธะฝ ะปะธัั)
val graph1 = graphs[0]
val overVertexes = graph.mapList.keys - graph1.mapList.keys
if (TreeIsStarCentral.check(graph1)
&& isPath(graph, overVertexes)
&& isPathConnectedToCenterOfSCB(graph, graph1, overVertexes)
) {
Logger.i("ะบ ัะตะฟะธ ะบัะตะฟะธััั SC ะทะฐ ัะตัะตะดะธะฝั")
return 1
} else {
Logger.e("ะฝะฐัะปะธ 1 ะณัะฐั SC/SB, ะฝะพ ััะพ ะฝะต SC/SB + P")
// ะฝะฐัะปะธ 1 ะณัะฐั, ะฝะพ ััะพ ะฝะต SC + P
}
} else {
Logger.e("ะฝะฐัะปะธ > 2 ะณัะฐัะพะฒ, ะฒะพะพะฑัะต ะฝะตะฟะพะฝััะฝะพ ััะพ ัะฐะบะพะต")
// ะฝะฐัะปะธ > 2 ะณัะฐัะพะฒ, ะฒะพะพะฑัะต ะฝะตะฟะพะฝััะฝะพ ััะพ ัะฐะบะพะต
}
return 0
}
/**
* ะะพะปััะตะฝะธะต ะณัะฐัะพะฒ SC/SB, ะบะพัะพััะต ะธะผะตัััั ะฒ ะณัะฐัะต [graph] ั ะฟัะธะฒะตะดะตะฝะฝะพะน ะบะพะปะพะดะพะน 2 (ะฟะพ ะฟะพะดะพะฑะฝัะผ ะปะธััััะผะธ)
* ะะดะตะผ ะธ ะพััะตะบะฐะตะผ ะปะธัััั ะดััะณะพะณะพ ะฟะพะดะพะฑะธั, ะฟะพะบะฐ ะฝะต ะฟะพะปััะธะผ SC/SB
*/
fun getScSbSubGraphs(graph: Graph): List<Graph>? {
val leaveToSubgraphCode = mutableListOf<Pair<Int, AbstractGraphCode>>()
graph.getLeaves().forEach { vertex ->
val newGraph = graph.filterVertexes { it != vertex }
leaveToSubgraphCode.add(vertex to newGraph.getAbstractCode())
}
val sameLeavesGroups = leaveToSubgraphCode.groupBy { it.second }.map { (_, value) -> value.map { it.first } }
Logger.i("sameLeavesGroups:")
if (sameLeavesGroups.size > 2) {
// ะฟะพะปััะธะปะธ ะฑะพะปััะต 2ั
ะฟะพะดะพะฑะฝัั
ะปะธัััะตะฒ, ะทะฝะฐัะธั ััะพ ะฝะต ะณัะฐั ั ะบะพะปะธัะตััะฒะพะผ ะฟัะธะฒะตะดะตะฝะฝะพะน ะบะพะปะพะดั 2
return null
}
val graphs = sameLeavesGroups.mapNotNull { leavesGroup ->
Logger.i("sameLeavesGroup $leavesGroup")
// leavesGroup - ะฒะตััะธะฝั, ะฟัะธ ัะดะฐะปะตะฝะธะธ ะบะพัะพััั
ะฟะพะปััะฐัััั ะฟะพะดะพะฑะฝัะต ะณัะฐัั
// ั.ะต. ะฑัะดะตะผ ัะฑะธัะฐัั ะฒัะต ะพััะฐะปัะฝัะต ะปะธัััั, ะฟะพะบะฐ ะฝะต ะฟะพะปััะธะผ ะดะตัะตะฒะพ ั ะบะพะปะธัะตััะฒะพะผ ะฟัะธะฒะตะดะตะฝะฝะพะน ะบะพะปะพะดั 1
var currentGraph = graph.copy()
var otherLeaves = currentGraph.getLeaves().toSet() - leavesGroup.toSet()
var forceStop = false
while (
!(ReducedTreePackEquals1.check(currentGraph) && // ะธัะตะผ ะณัะฐั SC ะธะปะธ SB
currentGraph.getLeaves().toSet() == leavesGroup.toSet()) && // ััะพะฑั ะปะธัััั ะฑัะปะธ ัะพะปัะบะพ ัะต, ััะพ ะฒ ะณััะฟะฟะต
otherLeaves.isNotEmpty() && // ะฟะพะบะฐ ะตััั ััะพ ะพัะบัััะฒะฐัั
!forceStop
) {
val oldGraph = currentGraph
currentGraph = currentGraph.filterVertexes { !otherLeaves.contains(it) }
forceStop = oldGraph == currentGraph // ะพััะฐะฝะพะฒะธะผัั, ะตัะปะธ ะณัะฐั ะฝะต ะฟะพะผะตะฝัะปัั
otherLeaves = currentGraph.getLeaves().toSet() - leavesGroup.toSet()
}
// ะฝะฐัะปะธ ะณัะฐั SC ะธะปะธ SB, (ะตัะปะธ ะฝะตั, ัะพ ะฟะพัะพะผ ัะฐะทะฑะตัะตะผัั ั ััะธะผ ะบะตะนัะพะผ
currentGraph.takeIf { ReducedTreePackEquals1.check(currentGraph) }
}
return graphs
}
fun getPathStartEnd(g: Graph, path: Set<Int>): Pair<Int, Int> {
if (path.isEmpty()) {
error("path is empty")
}
if (path.size == 1) return path.first() to path.first()
val (start, end) = path.filter { vertex -> path.count { g.mapList[vertex]?.contains(it) == true } == 1 }
return start to end
}
fun isPath(g: Graph, path: Set<Int>): Boolean {
if (path.isEmpty()) return false
if (path.size == 1) return true
val mutablePath = path.toMutableSet()
val startVertex = path.find { vertex -> path.count { g.mapList[vertex]?.contains(it) == true } == 1 }
var currentVertex = startVertex
mutablePath.remove(currentVertex)
while (currentVertex != null) {
currentVertex = g.mapList[currentVertex].orEmpty().find { mutablePath.contains(it) }
mutablePath.remove(currentVertex)
}
return mutablePath.isEmpty()
}
private fun isPathConnectedToCenterOfSCB(g: Graph, scb: Graph, path: Set<Int>): Boolean {
val graph1Center = TreeUtil.getTreeCenterVertexes(scb).first()
return getPathStartEnd(g, path).let { (pathStart, pathEnd) ->
g.mapList[graph1Center].orEmpty().let { it.contains(pathStart) || it.contains(pathEnd) }
}
}
private fun getGraphStarType(graph: Graph): String {
if (TreeIsStarCentral.check(graph)) {
return "SC"
} else if (TreeIsStarBicentral.check(graph)) {
return "SB"
} else {
return "ER"
}
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePack2Type.kt | 129165146 |
package ru.dmitriyt.graphtreeanalyser.data
internal class ByteReader6(s6: String) {
private val mBytes: ByteArray
private val mSize: Int
private var mPos: Int
private var mBit = 0
init {
mBytes = s6.toByteArray()
mSize = s6.length
mPos = mBit
}
// ! whether k bits are available
fun haveBits(k: Int): Boolean {
return mPos + (mBit + k - 1) / 6 < mSize
}
// ! return the next integer encoded in graph6
fun getNumber(): Int {
assert(mPos < mSize)
var c = mBytes[mPos]
assert(c >= 63)
c = (c - 63).toByte()
++mPos
if (c < 126) return c.toInt()
assert(false)
return 0
}
// ! return the next bit encoded in graph6
fun getBit(): Int {
assert(mPos < mSize)
var c = mBytes[mPos]
assert(c >= 63)
c = (c - 63).toByte()
c = (c.toInt() shr 5 - mBit).toByte()
mBit++
if (mBit == 6) {
mPos++
mBit = 0
}
return c.toInt() and 0x01
}
// ! return the next bits as an integer
fun getBits(k: Int): Int {
var v = 0
for (i in 0 until k) {
v *= 2
v += getBit()
}
return v
}
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/ByteReader6.kt | 2182366193 |
package ru.dmitriyt.graphtreeanalyser.data
import java.util.concurrent.ConcurrentHashMap
object GraphCache {
private val cache = ConcurrentHashMap<String, Graph>()
operator fun get(graph6: String): Graph {
return cache[graph6] ?: run {
val graph = Graph.fromSparse6(graph6)
cache[graph6] = graph
graph
}
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/GraphCache.kt | 345405774 |
package ru.dmitriyt.graphtreeanalyser.data
import kotlin.math.ceil
import kotlin.math.ln
data class Graph(
val mapList: Map<Int, List<Int>>,
) {
val n: Int = mapList.size
companion object {
fun fromSparse6(codeSparse6: String): Graph {
val code = codeSparse6.substring(1)
val byteReader = ByteReader6(code)
val n = byteReader.getNumber()
val k = ceil(ln(n.toDouble()) / ln(2.0)).toInt()
val map = mutableMapOf<Int, MutableList<Int>>()
repeat(n) {
map[it] = mutableListOf()
}
var v = 0
while (byteReader.haveBits(k + 1)) {
val b = byteReader.getBit()
val x = byteReader.getBits(k)
if (b != 0) {
v++
}
if (v >= n) {
break
}
if (x > v) {
v = x
} else {
map[x]?.add(v)
map[v]?.add(x)
}
}
return Graph(map)
}
}
fun filterVertexes(isAdd: (vertex: Int) -> Boolean): Graph {
return Graph(
mapList.filter { isAdd(it.key) }.map { entry ->
entry.key to entry.value.filter { isAdd(it) }
}.toMap()
)
}
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/Graph.kt | 3938547056 |
package ru.dmitriyt.graphtreeanalyser.domain
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphResult
sealed interface SolveResult {
data class Condition(
val graphs: List<String>,
) : SolveResult
data class Invariant(
val invariants: List<GraphResult>,
) : SolveResult
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/SolveResult.kt | 431668384 |
package ru.dmitriyt.graphtreeanalyser.domain.solver
import ru.dmitriyt.graphtreeanalyser.domain.model.Task
import ru.dmitriyt.graphtreeanalyser.domain.model.TaskResult
interface TaskSolver {
fun run(
inputProvider: () -> Task,
resultHandler: (TaskResult) -> Unit,
onFinish: () -> Unit,
)
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/solver/TaskSolver.kt | 3943302748 |
package ru.dmitriyt.graphtreeanalyser.domain.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.GraphCache
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo
interface GraphCondition {
fun check(graph6: String): Boolean = check(GraphCache[graph6])
fun check(graph: Graph): Boolean
}
fun GraphCondition.toGraphTaskInfo(): GraphTaskInfo {
return GraphTaskInfo.Condition(this)
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/algorithm/GraphCondition.kt | 3623991615 |
package ru.dmitriyt.graphtreeanalyser.domain.algorithm
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.data.GraphCache
import ru.dmitriyt.graphtreeanalyser.domain.Logger
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo
interface GraphInvariant {
fun solve(graph6: String): Int {
Logger.i("\n")
Logger.i(graph6)
return solve(GraphCache[graph6])
}
fun solve(graph: Graph): Int
}
fun GraphInvariant.toGraphTaskInfo(): GraphTaskInfo {
return GraphTaskInfo.Invariant(this)
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/algorithm/GraphInvariant.kt | 254600425 |
package ru.dmitriyt.graphtreeanalyser.domain.model
sealed class TaskResult(
open val taskId: Int,
open val processedGraphs: Int,
) {
data class Invariant(
override val taskId: Int,
override val processedGraphs: Int,
val results: List<GraphResult>,
) : TaskResult(taskId, processedGraphs)
data class Graphs(
override val taskId: Int,
override val processedGraphs: Int,
val graphs: List<String>,
) : TaskResult(taskId, processedGraphs)
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/model/TaskResult.kt | 835593607 |
package ru.dmitriyt.graphtreeanalyser.domain.model
data class GraphResult(
val graph6: String,
val invariant: Int,
) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/model/GraphResult.kt | 2996593651 |
package ru.dmitriyt.graphtreeanalyser.domain.model
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
sealed class GraphTaskInfo {
data class Invariant(
val task: GraphInvariant,
) : GraphTaskInfo()
data class Condition(
val task: GraphCondition,
) : GraphTaskInfo()
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/model/GraphTaskInfo.kt | 1251459235 |
package ru.dmitriyt.graphtreeanalyser.domain.model
data class Task(
val id: Int,
val graphs: List<String>,
) {
companion object {
val EMPTY = Task(-1, emptyList())
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/model/Task.kt | 1074579764 |
package ru.dmitriyt.graphtreeanalyser.domain
private const val IS_DEBUG = true
private const val ANSI_RESET = "\u001B[0m"
private const val ANSI_RED = "\u001B[31m"
object Logger {
fun d(any: Any) {
if (IS_DEBUG) {
println(any)
}
}
fun e(any: Any) {
println(ANSI_RED + any + ANSI_RESET)
}
fun i(any: Any) {
println(any)
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/domain/Logger.kt | 4151012569 |
package ru.dmitriyt.graphtreeanalyser.presentation
import ru.dmitriyt.graphtreeanalyser.data.GraphCache
import java.awt.BasicStroke
import java.awt.Color
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Rectangle
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.cos
import kotlin.math.sin
/**
* ะะปะฐัั ะดะปั ัะพะทะดะฐะฝะธั ะธะทะพะฑัะฐะถะตะฝะธั ะณัะฐัะฐ
*/
class GraphDrawer(
/** ะััั ัะพั
ัะฐะฝะตะฝะธั ะธะทะพะฑัะฐะถะตะฝะธะน */
private val path: String = PATH,
/** ะะพะดะฟะธััะฒะฐัั ะปะธ ะณัะฐั */
private val hasTitle: Boolean = true,
/** ะ ะฐะทะผะตั ะธะทะพะฑัะฐะถะตะฝะธั */
private val imageSize: Int = IMAGE_SIZE,
/** ะ ะฐะดะธัั ะฒะตััะธะฝั */
private val vertexRadius: Int = VERTEX_RADIUS,
/** ะ ะฐะดะธัั ะณัะฐัะฐ */
private val graphRadius: Int = GRAPH_RADIUS,
) {
companion object {
const val IMAGE_SIZE = 300
const val VERTEX_RADIUS = 20
const val GRAPH_RADIUS = 100
const val PATH = "graphs/"
private const val EXTENSION = "png"
}
/**
* ะกะพะทะดะฐัั ะธ ัะพั
ัะฐะฝะธัั ะธะทะพะฑัะฐะถะตะฝะธะต ะณัะฐัะฐ
* @param graph6 - ะณัะฐั ะฒ ัะพัะผะฐัะต graph6
*/
fun drawImage(graph6: String) {
val graph = GraphCache[graph6]
val n = graph.n
val image = BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB)
val graphics = image.createGraphics()
graphics.apply {
paint = Color.WHITE
fillRect(0, 0, imageSize, imageSize)
paint = Color.BLACK
val vertexCount = graph.n
val dAngle = 360 / vertexCount
var angle = 0
if (hasTitle) {
font = Font(null, Font.BOLD, 14)
drawString(graph6, 0, 16)
}
// ัะธัะพะฒะฐะฝะธะต ัะตะฑะตั
repeat(graph.n) { i ->
repeat(graph.n) { j ->
if (graph.mapList[i].orEmpty().contains(j)) {
val (x1, y1) = getVertexCenter(i, dAngle)
val (x2, y2) = getVertexCenter(j, dAngle)
drawEdge(this, x1, y1, x2, y2)
}
}
}
// ัะธัะพะฒะฐะฝะธะต ะฒะตััะธะฝ
font = Font(null, Font.BOLD, 24)
repeat(graph.n) { vertex ->
drawVertex(
this,
vertex,
imageSize / 2 + (graphRadius * sin(Math.toRadians(angle.toDouble()))).toInt(),
imageSize / 2 + (graphRadius * cos(Math.toRadians(angle.toDouble()))).toInt()
)
angle += dAngle
}
dispose()
}
val dir = File(path)
if (!dir.exists()) {
dir.mkdir()
}
val dirByN = File(dir, "n$n")
if (!dirByN.exists()) {
dirByN.mkdir()
}
val number = dirByN.listFiles()?.size
ImageIO.write(image, EXTENSION, File(dirByN, "$number.$EXTENSION"))
}
private fun getVertexCenter(vertex: Int, dAngle: Int): Pair<Int, Int> {
val angle = dAngle * vertex
val x = imageSize / 2 + (graphRadius * sin(Math.toRadians(angle.toDouble()))).toInt()
val y = imageSize / 2 + (graphRadius * cos(Math.toRadians(angle.toDouble()))).toInt()
return x to y
}
private fun drawVertex(graphics: Graphics2D, vertex: Int, centerX: Int, centerY: Int) {
graphics.stroke = BasicStroke(2f)
graphics.paint = Color.LIGHT_GRAY
graphics.fillOval(
centerX - vertexRadius,
centerY - vertexRadius,
2 * vertexRadius,
2 * vertexRadius
)
graphics.paint = Color.BLACK
graphics.drawOval(
centerX - vertexRadius,
centerY - vertexRadius,
2 * vertexRadius,
2 * vertexRadius
)
graphics.drawCenteredString(
vertex.toString(),
Rectangle(
centerX - vertexRadius,
centerY - vertexRadius,
2 * vertexRadius,
2 * vertexRadius
)
)
}
private fun drawEdge(graphics: Graphics2D, v1x: Int, v1y: Int, v2x: Int, v2y: Int) {
graphics.paint = Color.BLACK
graphics.stroke = BasicStroke(4f)
graphics.drawLine(v1x, v1y, v2x, v2y)
}
private fun Graphics.drawCenteredString(text: String, rect: Rectangle) {
val metrics = getFontMetrics(font)
val x = rect.x + (rect.width - metrics.stringWidth(text)) / 2
val y = rect.y + (rect.height - metrics.height) / 2 + metrics.ascent
drawString(text, x, y)
}
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/GraphDrawer.kt | 1959658484 |
package ru.dmitriyt.graphtreeanalyser.presentation.input
import ru.dmitriyt.graphtreeanalyser.presentation.BlockingSolverInput
val input9 = BlockingSolverInput.DataInputProvider(
graphs = """
:H`ESxol^
:H`ESxOl^
:H`ESwol^
:H`ESwTl^
:H`EShQ`^
:H`EShP`^
:H`EShOl^
:H`EShOlZ
:H`EShOlB
:H`ESgt`^
:H`ESgp`^
:H`ESgol^
:H`ESgolZ
:H`ESgolB
:H`ESgTlZ
:H`ESgTlV
:H`ESgTlB
:H`ESgT`^
:H`ESgT`B
:H`ESYP`^
:H`ESYOl^
:H`ESYOlB
:H`ESWp`^
:H`ESWol^
:H`ESWolB
:H`ESWTlV
:H`ESWTlB
:H`ESIT`^
:H`ESIT`B
:H`EKWpbB
:H`EKWp`^
:H`EKWp`B
:H`EKWolZ
:H`EKWolB
:H`EKWo`B
:H`EKWTjV
:H`EKWTjB
:H`EKWT`^
:H`EKWT`B
:H`EKIS`^
:H`EKIS`B
:H`EKIOlB
:H`EKIO`B
:H`ECwT`^
:H`ECwT`B
:H`ECwO`B
:H`ACGO`B
""".trimIndent().split("\n")
) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/input/input9.kt | 2084416584 |
package ru.dmitriyt.graphtreeanalyser.presentation.input
import ru.dmitriyt.graphtreeanalyser.presentation.BlockingSolverInput
val input7 = BlockingSolverInput.DataInputProvider(
graphs = """
:FaYiL
:FaYeL
:FaYbL
:FaXeW
:FaXeL
:FaXeG
:FaXbK
:FaXbG
:FaWmL
:FaWmG
:FaGaG
""".trimIndent().split("\n")
) | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/input/input7.kt | 1573932378 |
package ru.dmitriyt.graphtreeanalyser.presentation
import ru.dmitriyt.graphtreeanalyser.domain.Logger
import ru.dmitriyt.graphtreeanalyser.domain.SolveResult
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.toGraphTaskInfo
suspend fun graphs(n: Int, block: suspend SolveScope.() -> Unit) {
SolveScope(n).block()
}
class SolverQueryScope
class SolveScope(
private val n: Int,
) {
var multiThreadingEnabled = false
fun generate(generator: String): BlockingSolverInput {
return BlockingSolverInput.GengProvider(generator = generator, n = n)
}
suspend fun run(queryProvider: SolverQueryScope.() -> GraphInvariantSelectionWithDataAndFilters) {
val query = SolverQueryScope().queryProvider()
query.inputProvider().filter(query.filter).apply {
query.selection.invariants.forEach {
calculateInvariant(it)
}
}
}
suspend fun BlockingSolverInput.filter(
graphCondition: GraphCondition,
partSize: Int = 1024,
): BlockingSolverInput {
val conditionSolver = BlockingSolver(
isMulti = multiThreadingEnabled,
n = n,
input = this,
graphTaskInfo = graphCondition.toGraphTaskInfo(),
partSize = partSize,
)
val conditionResult = conditionSolver.solve() as SolveResult.Condition
Logger.i("----- N = $n $graphCondition : ${conditionResult.graphs.size} -----")
return BlockingSolverInput.DataInputProvider(conditionResult.graphs)
}
fun BlockingSolverInput.saveImages(path: String = GraphDrawer.PATH) {
val graphDrawer = GraphDrawer(path = path)
read(Int.MAX_VALUE).forEach {
graphDrawer.drawImage(it)
}
}
suspend fun BlockingSolverInput.calculateInvariant(
graphInvariant: GraphInvariant,
partSize: Int = 256
): SolveResult.Invariant {
val invariantSolver = BlockingSolver(
isMulti = multiThreadingEnabled,
n = n,
input = this,
graphTaskInfo = graphInvariant.toGraphTaskInfo(),
partSize = partSize,
)
val invariantResult = invariantSolver.solve() as SolveResult.Invariant
if (invariantResult.invariants.isNotEmpty()) {
Logger.i("----- $graphInvariant value : count -----")
val minInvariant = invariantResult.invariants.minOfOrNull { it.invariant }!!
val maxInvariant = invariantResult.invariants.maxOfOrNull { it.invariant }!!
for (i in minInvariant..maxInvariant) {
Logger.i("$graphInvariant $i\t:\t${invariantResult.invariants.count { it.invariant == i }}")
}
}
return invariantResult
}
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/SolverScope.kt | 1254198620 |
package ru.dmitriyt.graphtreeanalyser.presentation.solver
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo
import ru.dmitriyt.graphtreeanalyser.domain.model.Task
import ru.dmitriyt.graphtreeanalyser.domain.model.TaskResult
import ru.dmitriyt.graphtreeanalyser.domain.solver.TaskSolver
import kotlin.concurrent.thread
/**
* ะะฝะพะณะพะฟะพัะพัะฝัะน ะฒััะธัะปะธัะตะปั
*/
class MultiThreadSolver(private val graphTaskInfo: GraphTaskInfo) : TaskSolver {
override fun run(inputProvider: () -> Task, resultHandler: (TaskResult) -> Unit, onFinish: () -> Unit) {
val nCpu = Runtime.getRuntime().availableProcessors()
val threads = IntRange(0, nCpu).map {
thread {
SingleSolver(graphTaskInfo).run(inputProvider, resultHandler, onFinish)
}
}
threads.map { it.join() }
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/solver/MultiThreadSolver.kt | 4268355926 |
package ru.dmitriyt.graphtreeanalyser.presentation.solver
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphResult
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo
import ru.dmitriyt.graphtreeanalyser.domain.model.Task
import ru.dmitriyt.graphtreeanalyser.domain.model.TaskResult
import ru.dmitriyt.graphtreeanalyser.domain.solver.TaskSolver
/**
* ะะดะฝะพะฟะพัะพัะฝัะน ะฒััะธัะปะธัะตะปั
*/
class SingleSolver(private val graphTaskInfo: GraphTaskInfo) : TaskSolver {
override fun run(inputProvider: () -> Task, resultHandler: (TaskResult) -> Unit, onFinish: () -> Unit) {
var task = inputProvider()
var graphs = getGraphsFromTask(task)
while (task != Task.EMPTY) {
resultHandler(
when (graphTaskInfo) {
is GraphTaskInfo.Invariant -> TaskResult.Invariant(
task.id,
graphs.size,
graphs.map { GraphResult(it, graphTaskInfo.task.solve(it)) },
)
is GraphTaskInfo.Condition -> TaskResult.Graphs(
task.id,
graphs.size,
graphs.filter { graphTaskInfo.task.check(it) },
)
}
)
task = inputProvider()
graphs = getGraphsFromTask(task)
}
onFinish()
}
private fun getGraphsFromTask(task: Task): List<String> {
val list = task.graphs
return list
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/solver/SingleSolver.kt | 158934687 |
package ru.dmitriyt.graphtreeanalyser.presentation
import ru.dmitriyt.graphtreeanalyser.domain.Logger
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import kotlin.math.min
sealed interface BlockingSolverInput {
fun read(partSize: Int): List<String>
class GengProvider(generator: String, n: Int) : BlockingSolverInput {
private val commandList = listOfNotNull(
"./$generator",
n.toString(),
).apply {
Logger.d("generate command: ${this.joinToString(" ")}")
}
private val process = ProcessBuilder(*commandList.toTypedArray())
.directory(File(System.getProperty("user.dir"))).start()
private val reader = BufferedReader(
InputStreamReader(
process.inputStream
)
)
override fun read(partSize: Int): List<String> {
val graphs = mutableListOf<String>()
repeat(partSize) {
val mayBeGraph = synchronized(this) { reader.readLine() }
mayBeGraph?.takeIf { !it.startsWith(">") }?.takeIf { it.isNotEmpty() }?.let { graphs.add(it) } ?: run {
return@repeat
}
}
return graphs
}
}
class DataInputProvider(
private val graphs: List<String>,
) : BlockingSolverInput {
private var currentOffset: Int = 0
@Synchronized
override fun read(partSize: Int): List<String> {
if (currentOffset >= graphs.size) return emptyList()
val taskGraphs = graphs.subList(currentOffset, min(currentOffset + partSize, graphs.size))
currentOffset += partSize
return taskGraphs
}
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/BlockingSolverInput.kt | 4219119318 |
package ru.dmitriyt.graphtreeanalyser.presentation
import ru.dmitriyt.graphtreeanalyser.data.Graph
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition
import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant
fun SolverQueryScope.selectGraphCounts(vararg graphInvariant: GraphInvariant): GraphInvariantSelection {
return GraphInvariantSelection(graphInvariant.toList())
}
data class GraphInvariantSelection(
val invariants: List<GraphInvariant>,
)
data class GraphInvariantSelectionWithData(
val selection: GraphInvariantSelection,
val inputProvider: () -> BlockingSolverInput,
)
data class GraphInvariantSelectionWithDataAndFilters(
val selection: GraphInvariantSelection,
val inputProvider: () -> BlockingSolverInput,
val filter: GraphCondition,
)
fun generator(generator: String, n: Int): () -> BlockingSolverInput {
return {
BlockingSolverInput.GengProvider(generator, n)
}
}
infix fun GraphInvariantSelection.from(inputProvider: () -> BlockingSolverInput): GraphInvariantSelectionWithData {
return GraphInvariantSelectionWithData(this, inputProvider)
}
infix fun GraphInvariantSelectionWithData.where(graphCondition: GraphCondition): GraphInvariantSelectionWithDataAndFilters {
return GraphInvariantSelectionWithDataAndFilters(
selection = selection,
inputProvider = inputProvider,
filter = graphCondition,
)
}
infix fun GraphInvariantSelectionWithDataAndFilters.or(
graphCondition: GraphCondition
): GraphInvariantSelectionWithDataAndFilters {
return copy(
filter = filter or graphCondition,
)
}
infix fun GraphInvariantSelectionWithDataAndFilters.and(
graphCondition: GraphCondition
): GraphInvariantSelectionWithDataAndFilters {
return copy(
filter = filter and graphCondition,
)
}
infix fun GraphCondition.or(graphCondition: GraphCondition) = ComplexOrCondition(this, graphCondition)
infix fun GraphCondition.and(graphCondition: GraphCondition) = ComplexAndCondition(this, graphCondition)
data class ComplexAndCondition(
val graphConditions: List<GraphCondition>
) : GraphCondition {
constructor(vararg condition: GraphCondition) : this(condition.toList())
override fun check(graph: Graph): Boolean {
return graphConditions.all { it.check(graph) }
}
}
data class ComplexOrCondition(
val graphConditions: List<GraphCondition>
) : GraphCondition {
constructor(vararg condition: GraphCondition) : this(condition.toList())
override fun check(graph: Graph): Boolean {
return graphConditions.any { it.check(graph) }
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/GraphQuery.kt | 2978057160 |
package ru.dmitriyt.graphtreeanalyser.presentation
import ru.dmitriyt.graphtreeanalyser.data.repository.SolveRepository
import ru.dmitriyt.graphtreeanalyser.domain.Logger
import ru.dmitriyt.graphtreeanalyser.domain.SolveResult
import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo
import ru.dmitriyt.graphtreeanalyser.domain.model.Task
import ru.dmitriyt.graphtreeanalyser.domain.model.TaskResult
import ru.dmitriyt.graphtreeanalyser.presentation.solver.MultiThreadSolver
import ru.dmitriyt.graphtreeanalyser.presentation.solver.SingleSolver
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.time.Duration.Companion.milliseconds
class BlockingSolver(
private val isMulti: Boolean,
private val n: Int,
private val input: BlockingSolverInput,
private val graphTaskInfo: GraphTaskInfo,
private val partSize: Int,
) {
private val taskId = AtomicInteger(0)
private val total = AtomicInteger(0)
private var isStartFinishing = AtomicBoolean(false)
private val processedGraphs = AtomicInteger(0)
private val lock = Object()
private val taskResults = mutableListOf<TaskResult>()
private var startTime = 0L
private var endTime = 0L
suspend fun solve(): SolveResult = suspendCoroutine {
val cachedResult: SolveResult? = null //SolveRepository.get(graphTaskInfo, n)
if (cachedResult != null) {
it.resume(cachedResult)
return@suspendCoroutine
}
val solver = if (isMulti) {
MultiThreadSolver(graphTaskInfo)
} else {
SingleSolver(graphTaskInfo)
}
startTime = System.currentTimeMillis()
solver.run(
inputProvider = {
val graphs = input.read(partSize)
if (graphs.isNotEmpty()) {
val newTaskId = taskId.incrementAndGet()
total.getAndAdd(graphs.size)
Task(
id = newTaskId,
graphs = graphs,
)
} else {
Task.EMPTY
}
},
resultHandler = { taskResult ->
processedGraphs.getAndAdd(taskResult.processedGraphs)
synchronized(lock) {
taskResults.add(taskResult)
}
},
onFinish = {
if (total.get() == processedGraphs.get() && !isStartFinishing.getAndSet(true)) {
endTime = System.currentTimeMillis()
Logger.d(
"""
----------
Task $graphTaskInfo
Processed graphs: ${total.get()}
Time passed: ${(endTime - startTime).milliseconds}
----------
""".trimIndent()
)
val result = when (graphTaskInfo) {
is GraphTaskInfo.Condition -> {
SolveResult.Condition(
graphs = taskResults.filterIsInstance<TaskResult.Graphs>().flatMap { it.graphs },
)
}
is GraphTaskInfo.Invariant -> {
SolveResult.Invariant(
invariants = taskResults.filterIsInstance<TaskResult.Invariant>().flatMap { it.results },
)
}
}
SolveRepository.set(graphTaskInfo, n, result)
it.resume(result)
}
}
)
}
} | graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/presentation/BlockingSolver.kt | 572509012 |
package ru.dmitriyt.graphtreeanalyser
class ArgsManager(rawArgs: Array<String>) {
private val rawArgsList = rawArgs.toList()
fun parse(): Args {
return Args(
n = n,
isMulti = isMulti,
partSize = partSize,
)
}
private val isMulti: Boolean get() = rawArgsList.contains("-m")
private val partSize: Int get() = getParam("-p")?.toIntOrNull() ?: Args.DEFAULT_PART_SIZE
private val n: Int get() = getParam("-n")?.toIntOrNull() ?: error("-n param is required")
private fun getParam(key: String): String? {
return rawArgsList.indexOf(key).takeIf { it > -1 }?.let { rawArgsList.getOrNull(it + 1) }
}
}
| graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/ArgsManager.kt | 2186299603 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | top-vpn/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | top-vpn/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | top-vpn/app/src/main/java/com/example/myapplication/MainActivity.kt | 665038924 |
package com.example.myapplication
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Window
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.util.logging.Handler
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_splash);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window: Window = this.window
window.statusBarColor = this.resources.getColor(R.color.white)
}
android.os.Handler().postDelayed({
startActivity(Intent(this@SplashActivity, MainActivity::class.java))
}, 2000)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
} | top-vpn/app/src/main/java/com/example/myapplication/SplashActivity.kt | 2795932164 |
package com.example.navigationtutorial
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.navigationtutorial", appContext.packageName)
}
} | Navigation_Tutorial/app/src/androidTest/java/com/example/navigationtutorial/ExampleInstrumentedTest.kt | 2079058632 |
package com.example.navigationtutorial
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Navigation_Tutorial/app/src/test/java/com/example/navigationtutorial/ExampleUnitTest.kt | 2019997500 |
package com.example.navigationtutorial
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.findNavController
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navController = findNavController(androidx.navigation.fragment.R.id.nav_host_fragment_container)
navController.navigate(R.id.action_fragment1_to_fragment2)
}
} | Navigation_Tutorial/app/src/main/java/com/example/navigationtutorial/MainActivity.kt | 4008776129 |
package com.example.navigationtutorial
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Fragment2.newInstance] factory method to
* create an instance of this fragment.
*/
class Fragment2 : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_2, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Fragment2.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Fragment2().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | Navigation_Tutorial/app/src/main/java/com/example/navigationtutorial/Fragment2.kt | 2575689104 |
package com.example.navigationtutorial
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Fragment1.newInstance] factory method to
* create an instance of this fragment.
*/
class Fragment1 : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_1, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Fragment1.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Fragment1().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | Navigation_Tutorial/app/src/main/java/com/example/navigationtutorial/Fragment1.kt | 3639457409 |
package com.example.android.politicalpreparedness.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.android.politicalpreparedness.network.models.Election
@Database(entities = [Election::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class ElectionDatabase : RoomDatabase() {
abstract val electionDao: ElectionDao
companion object {
@Volatile
private var INSTANCE: ElectionDatabase? = null
fun getInstance(context: Context): ElectionDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
ElectionDatabase::class.java,
"election_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
} | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/database/ElectionDatabase.kt | 3123837751 |
package com.example.android.politicalpreparedness.database
import androidx.room.TypeConverter
import java.util.*
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return value?.let { Date(it) }
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time?.toLong()
}
} | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/database/Converters.kt | 2879155721 |
package com.example.android.politicalpreparedness.database
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.android.politicalpreparedness.network.models.Election
@Dao
interface ElectionDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(election: Election)
@Query("SELECT * FROM election_table")
fun getAllElections(): List<Election>
@Query("SELECT * FROM election_table WHERE id= :electionId")
fun getElection(electionId: Int): Election
@Delete
fun deleteElection(election: Election)
@Query("DELETE FROM election_table")
fun clear()
} | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/database/ElectionDao.kt | 1653752191 |
package com.example.android.politicalpreparedness
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/MainActivity.kt | 2797549734 |
package com.example.android.politicalpreparedness.launch
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.android.politicalpreparedness.databinding.FragmentLaunchBinding
class LaunchFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentLaunchBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.representativesBtn.setOnClickListener { navToRepresentatives() }
binding.upcomingElectionsBtn.setOnClickListener { navToElections() }
return binding.root
}
private fun navToElections() {
this.findNavController()
.navigate(LaunchFragmentDirections.actionLaunchFragmentToElectionsFragment())
}
private fun navToRepresentatives() {
this.findNavController()
.navigate(LaunchFragmentDirections.actionLaunchFragmentToRepresentativeFragment())
}
}
| PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/launch/LaunchFragment.kt | 3271487684 |
package com.example.android.politicalpreparedness.network.models
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class ElectionResponse(
val kind: String,
val elections: List<Election>
) | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/ElectionResponse.kt | 1102146445 |
package com.example.android.politicalpreparedness.network.models
data class RepresentativeResponse(
val offices: List<Office>,
val officials: List<Official>
) | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/RepresentativeResponse.kt | 1534191218 |
package com.example.android.politicalpreparedness.network.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Official(
val name: String,
val address: List<Address>? = null,
val party: String? = null,
val phones: List<String>? = null,
val urls: List<String>? = null,
val photoUrl: String? = null,
val channels: List<Channel>? = null
) : Parcelable | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/Official.kt | 1203401614 |
package com.example.android.politicalpreparedness.network.models
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class AdministrationBody(
val name: String? = null,
val electionInfoUrl: String? = null,
val votingLocationFinderUrl: String? = null,
val ballotInfoUrl: String? = null,
val correspondenceAddress: Address? = null
) | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/AdministrationBody.kt | 211770384 |
package com.example.android.politicalpreparedness.network.models
data class State(
val name: String,
val electionAdministrationBody: AdministrationBody
) | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/State.kt | 1438018635 |
package com.example.android.politicalpreparedness.network.models
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class VoterInfoResponse(
val election: Election,
val pollingLocations: String? = null, //Future Use
//val contests: String? = null, //Future Use
val state: List<State>? = null,
val electionElectionOfficials: List<ElectionOfficial>? = null
) | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/VoterInfoResponse.kt | 164377711 |
package com.example.android.politicalpreparedness.network.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Address(
val line1: String,
val line2: String? = null,
val city: String,
val state: String,
val zip: String
) : Parcelable {
fun toFormattedString(): String {
var output = line1.plus("\n")
if (!line2.isNullOrEmpty()) output = output.plus(line2).plus("\n")
output = output.plus("$city, $state $zip")
return output
}
} | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/Address.kt | 2204790827 |
package com.example.android.politicalpreparedness.network.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Division(
val id: String,
val country: String,
val state: String
) : Parcelable | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/Division.kt | 2689940993 |
package com.example.android.politicalpreparedness.network.models
import android.os.Parcelable
import com.example.android.politicalpreparedness.representative.model.Representative
import com.squareup.moshi.Json
import kotlinx.parcelize.Parcelize
@Parcelize
data class Office(
val name: String,
@Json(name = "divisionId") val division: Division,
@Json(name = "officialIndices") val officials: List<Int>
) : Parcelable {
fun getRepresentatives(officials: List<Official>): List<Representative> {
return this.officials.map { index ->
Representative(officials[index], this)
}
}
}
| PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/Office.kt | 1092927827 |
package com.example.android.politicalpreparedness.network.models
import androidx.room.*
import com.squareup.moshi.*
import java.util.*
@Entity(tableName = "election_table")
data class Election(
@PrimaryKey val id: Int,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "electionDay") val electionDay: Date,
@Embedded(prefix = "division_") @Json(name = "ocdDivisionId") val division: Division
) | PoliticalPreparedness-project/app/src/main/java/com/example/android/politicalpreparedness/network/models/Election.kt | 3184329934 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.