Skip to content

Instantly share code, notes, and snippets.

@billdueber
Last active September 25, 2025 17:23
Show Gist options
  • Save billdueber/27ea655efe5482e7d81f0f823a0257b1 to your computer and use it in GitHub Desktop.
Save billdueber/27ea655efe5482e7d81f0f823a0257b1 to your computer and use it in GitHub Desktop.
//----------- STRINGS ---------------
fun string_stuff() {
// fstring / text blocks
val name = "Alice"
val age = 30
val message = "Hello, $name, you are $age. In ten years you'll be ${age + 10}."
val longer = """
This is a much longer string. It can also do interpolation.
Your name is $name, capitalized to ${name.uppercase()}.
"""
}
//------------ PATHS --------------
fun path_stuff() {
val basePath = Path("path/to/my/file.txt")
val filename = basePath.fileName
val directory = basePath.parent
if (basePath.exists()) {
println("Yup. $basePath exists.")
}
val contents = basePath.readText();
val binaryContents = File(basePath.toString()).readBytes(); // fall into Java
}
//------------- ORM -------------------------
// SQLAlchemy type stuff, using Kotlin `exposed`. Other ORMS are available, of course.
// The ORMS all seem to have "contact the database and generate code" operations.
// And the AI seems good at defining this stuff, which is good to know.
object Users : IntIdTable() {
val name = varchar("name", 255)
val age = integer("age")
}
object Books : IntIdTable() {
val title = varchar("title", 255)
val owner = reference("owner", Users)
}
// Entity classes
class User(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<User>(Users)
var name by Users.name
var age by Users.age
// Reference to books owned by this user
val books by Book referrersOn Books.owner
}
class Book(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Book>(Books)
var title by Books.title
var owner by User referencedOn Books.owner
fun nameplate(): String {
"'$title' is owned by ${owner.name}"
}
}
val user1 = User.new { name = "Bill Dueber", age = 56 }
val book1 = Book.new { title = "Downhill as long as I remember", owner = user1 }
val book = Book.findbyId(1)
println("Found book '${book.title}', owned by ${book.owner.name}")
//---------- PROCESSES -----------
//
// Depending on what we're doing, it might make sense to wrap some of this stuff into
// coroutines as well for easier tracking.
// VERY SIMPLE processes
fun runCommand(command: String): String {
return ProcessBuilder(command.split(" "))
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
.inputStream.bufferedReader().readText()
}
// A little more control...
data class CommandResult(val exitCode: Int, val output: String, val error: String)
fun runCommand(vararg command: String): CommandResult {
val processBuilder = ProcessBuilder(*command)
processBuilder.redirectErrorStream(false)
return try {
val process = processBuilder.start()
val output = process.inputStream.bufferedReader().readText()
val error = process.errorStream.bufferedReader().readText()
val exitCode = process.waitFor()
CommandResult(exitCode, output, error)
} catch (e: Exception) {
CommandResult(1, "", "Command failed: ${e.message}")
}
}
//---------------- Image Scaling ---------------------
// This uses imgscalr, which only does scaling and cropping. There are other 2d and 3d libraries
// for non-scaling things, but you get the gist.
/**
* Scales an image by a given factor and saves it to a new location
*
* @param existingFilePath Path to the existing image file
* @param newFilePath Path where the scaled image will be saved
* @param scalingFactor Factor by which to scale the image (e.g., 0.5 for half size, 2.0 for double size)
* @throws IOException if there's an error reading or writing the image files
* @throws IllegalArgumentException if the scaling factor is not positive
*/
fun scaleImage(existingFilePath: String, newFilePath: String, scalingFactor: Double) {
require(scalingFactor > 0) { "Scaling factor must be positive" }
try {
// Read the existing image
val existingFile = File(existingFilePath)
val originalImage: BufferedImage = ImageIO.read(existingFile)
?: throw IOException("Could not read image from $existingFilePath")
// Calculate new dimensions
val newWidth = (originalImage.width * scalingFactor).toInt()
val newHeight = (originalImage.height * scalingFactor).toInt()
// Scale the image using imgscalr
val scaledImage: BufferedImage = Scalr.resize(
originalImage,
Scalr.Method.QUALITY, // Use high-quality scaling
newWidth,
newHeight
)
// Determine output format from file extension
val newFile = File(newFilePath)
val outputFormat = newFile.extension.lowercase().ifEmpty { "png" }
// Create parent directories if they don't exist
newFile.parentFile?.mkdirs()
// Write the scaled image to the new location
ImageIO.write(scaledImage, outputFormat, newFile)
println("Image successfully scaled and saved to: $newFilePath")
} catch (e: IOException) {
throw IOException("Error processing image: ${e.message}", e)
}
}
// Example usage:
fun main() {
try {
scaleImage(
existingFilePath = "/path/to/original/image.jpg",
newFilePath = "/path/to/scaled/image.jpg",
scalingFactor = 0.5 // Scale to half size
)
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment