Skip to main content

LeifMessinger

User since Oct 28, 2022
65 Posts
JavaScript
Shell
C++
C
Plaintext
Python
HTML
Java
Rust
TypeScript

Recent Posts

makeHeaderTags.sh

0 likes • Feb 5, 2024 • 8 views
Shell
#!/bin/bash
# Recursively find all .svelte files in the current directory and its subdirectories
find . -type f -name "*.svelte" -o -name "*.html" -o -name "*.htm" | while read file; do
# Replace all h1 tags with the specified format
sed -i 's/<h1>\(.*\)<\/h1>/<h1 id="\1">\1<\/h1>/g' "$file"
# Replace all h2 tags with the specified format
sed -i 's/<h2>\(.*\)<\/h2>/<h2 id="\1">\1<\/h2>/g' "$file"
# Remove whitespace from the id attribute value
for i in {0..10} ; do
sed -i 's/\(id="[^"]*\)\W\([^"]*"\)/\1\2/g' "$file"
done
done

List Largest Files Google Drive

0 likes • Nov 16, 2023 • 5 views
JavaScript
function filePath(file){
let folders = file.getParents();
const parents = [];
function makePathString(folderArray){
let path = "";
folderArray.forEach((folder)=>{
path += "/" + folder.getName();
});
return path;
}
while (folders.hasNext()) {
const folder = folders.next(); //This should hopefully remove that folder from the iterator
parents.unshift(folder);
}
return makePathString(parents);
}
function myFunction() {
const myEmail = Session.getEffectiveUser().getEmail();
Logger.log("My email is " + myEmail);
// Log the name of every file in the user's Drive.
var fileIterator = DriveApp.getFiles();
const files = []; //List of [File, size] entries
const filesMaxSize = 10;
while (fileIterator.hasNext()) {
var file = fileIterator.next();
const owner = file.getOwner();
//Only files I own
if((!(owner)) || (!(owner.getEmail)) || owner.getEmail() != myEmail){
continue;
}
const entry = [file, file.getSize()];
function slideUp(arr, index){
//Let's keep sliding it up so we don't have to sort it at the end.
for(let i = index; i > 0; --i){ //Stops at 1
const nextFile = arr[i-1];
if(nextFile[1] > entry[1]){
break;
}else{
//Swap with the next file to slide the file up
const temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
}
if(files.length < filesMaxSize){
files.push(entry);
slideUp(files, files.length - 1);
}else{
if(entry[1] > files[files.length - 1][1]){ //If it's bigger than the smallest file in the list.
files[files.length - 1] = entry; //Replace the smallest file
slideUp(files, files.length - 1); //Slide it up
}
}
}
for(let i = 0; i < filesMaxSize; ++i){
const file = files[i][0];
const size = files[i][1];
Logger.log(size + "\t" + filePath(file) + "/" + file.getName() + "\t" + file.getOwner().getName());
}
}

copyString.js

0 likes • Nov 8, 2023 • 5 views
JavaScript
function copyString(text){
async function navigatorClipboardCopy(text){
if(document.location.protocol != "https:"){
return false;
}
return new Promise((resolve, reject)=>{
navigator.clipboard.writeText(text).then(()=>{resolve(true);}, ()=>{resolve(false);});
});
}
function domCopy(text){
if(!(document.execCommand)){
console.warn("They finally deprecated document.execCommand!");
}
const input = document.createElement('textarea');
input.value = text;
document.body.appendChild(input);
input.select();
const success = document.execCommand('copy');
document.body.removeChild(input);
return success;
}
function promptCopy(){
prompt("Copy failed. Might have ... somewhere. Check console.", text);
console.log(text);
}
function done(){
alert("Copied to clipboard");
}
navigatorClipboardCopy(text).catch(()=>{return false;}).then((success)=>{
if(success){
done();
}else{
if(domCopy(text)){
done();
}else{
promptCopy();
}
}
});
}

checkAndPush.sh

0 likes • Nov 4, 2023 • 6 views
Shell
#!/bin/bash
git status
echo "Do you want to add all changed files?"
select yn in "Yes" "No"; do
case $yn in
Yes ) break;;
No ) exit 1;;
esac
done
git add -u
git status
echo "Does this look right?"
select yn in "Yes" "No"; do
case $yn in
Yes ) break;;
No ) exit 2;;
esac
done
git commit
echo "Do you want to push?"
select yn in "Yes" "No"; do
case $yn in
Yes ) break;;
No ) exit 2;;
esac
done
git push

C++ Range Slicer

0 likes • Oct 31, 2023 • 3 views
C++
//Leif Messinger
//Compile with C++ 20
#include <iostream>
#include <ranges>
#include <vector>
#include <functional>
#include <cctype> //toupper
#include <cxxabi.h>
template <typename T>
void printType(){
std::cout << abi::__cxa_demangle(typeid(T).name(), NULL, NULL, NULL) << std::endl;
}
template <typename T>
class Slicer{
public:
T begin_;
T end_;
T trueEnd;
Slicer(T begin, T end): begin_(begin), end_(begin), trueEnd(end){}
template<typename U>
Slicer(U&& vec) : begin_(vec.begin()), end_(vec.begin()), trueEnd(vec.end()){}
Slicer& finish(){
begin_ = end_;
end_ = trueEnd;
return (*this);
}
Slicer& to(long int index){
begin_ = end_;
if(index > 0){
end_ = (begin_ + index);
}else{
index *= -1;
end_ = (trueEnd - index);
}
return (*this);
}
Slicer& operator[](long int index){
return to(index);
}
T begin(){
return this->begin_;
}
T end(){
return this->end_;
}
Slicer& operator()(std::function<void(decltype(*begin_))> func) {
for(decltype(*begin_) thing : (*this)){
func(thing);
}
return (*this);
}
};
static_assert(std::ranges::range< Slicer<std::vector<int>::const_iterator> >);
int main(){
std::string vec = "abcdefghijklmnopqrstuvwxyz";
Slicer<std::string::const_iterator> bruh(vec);
//printType<decltype(bruh)>();
bruh.to(3)([](char yeet){
std::cout << yeet;
})
.to(-1)([](char yeet){
std::cout << char(std::toupper(yeet));
}).finish()([](char yeet){
std::cout << yeet << yeet << yeet << yeet << yeet;
});
std::cout << std::endl << std::endl;
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
Slicer<int*> arrSlicer(arr, arr + (sizeof(arr)/sizeof(int)));
std::cout << "[";
arrSlicer.to(-1)([](int yeet){
std::cout << yeet << ", ";
}).finish()([](int yeet){
std::cout << yeet << "]" << std::endl;
});
return 0;
}

retryPromise.ts

0 likes • Oct 20, 2023 • 5 views
TypeScript
//Retries maxRetries number of times, meaning that if you have 0, then it'll run the function once.
async function retryPromise<T>(
promiseFn: () => Promise<T>,
maxRetries = 3,
delayOffset = 0,
delayRandomRange = 0
): Promise<T> {
return new Promise<T>((resolve, reject) => {
promiseFn()
.then(resolve, (error: any) => { //On error
if (maxRetries <= 0) {
return reject(error);
} else {
if(delayRandomRange * Math.random() + delayOffset < 1.0){
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolve, reject);
}else{
return new Promise<T>((resolveTwo, rejectTwo) => {
setTimeout(() => {
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolveTwo, rejectTwo);
}, delayRandomRange * Math.random() + delayOffset);
}).then(resolve, reject);
}
}
});
});
}
//Returns a function that will fail numTimes times, then will return aValue
function functionThatReturnsAFunctionThatFailsACoupleTimes(numTimes: number, aValue: any): () => Promise<any> {
return async function(){
if(numTimes == 0){
return aValue;
}
numTimes--;
throw false;
};
}
const SMALL_NUMBER = 10;
function testTest(failNumberOfTimes: number){
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(failNumberOfTimes, true);
//Test my test
for(let i = 0; i < (failNumberOfTimes * 2); ++i){
function evalTest(val: any){
let testTestFailedReason = "";
if(val === undefined){
testTestFailedReason = "Test test returned undefined for some reason.";
}
if((i + 1) > failNumberOfTimes){
if(val === true){
//We're good
}else{
testTestFailedReason = "Test test didn't return true when it should have.";
}
}else{
if(val === false){
//We're good
}else{
testTestFailedReason = "Test test didn't return false when it should have.";
}
}
testTestFailedReason = testTestFailedReason || "Test test passed test case";
console.log(testTestFailedReason, "at index", i, "where the function returned", val);
}
functionThatFailsACoupleTimes().then(evalTest, evalTest)
};
}
testTest(SMALL_NUMBER);
let testCaseCounter = 1;
const throwsNoError = [
(val: any) => {
if(val == true){
console.log("Passed test case " + testCaseCounter++);
}else{
console.error("Unexpected return value", val);
}
},
() => {
console.error("It wasn't supposed to fail!")
}
]
const throwsError = [
(val: any) => {
console.error("It wasn't supposed to succeed!", val);
},
(val: any) => {
if(val == false){
console.log("Passed test case " + testCaseCounter++);
}else{
console.error("Unexpected return value", val);
}
}
];
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2).then(...throwsError)
//Testing the delay. You'll have to wait a bit too.
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1, 500, 500).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2, 500, 500).then(...throwsError)

Post Statistics

Posts

No Posts Found

It looks like LeifMessinger hasn't uploaded a post yet

Likes

Please Log In

You must be authenticated to view a user's likes

Shared

Please Log In

You must be authenticated to view a user's shared posts

Profile Privacy

Multi-Factor Authentication

Multi-Factor Authentication (MFA) is an authentication method that requires you to provide two or more verification factors to gain access to your account. In addition to username and password, MFA requires you to verify your email on every login, which decreases the likelihood of someone stealing your account.

Change Password

Forgot Password?

Identity Color

Changes the color of your profile icon and cursor highlight in the live code editor. You and other users will be able to view this change.

Delete Account

Deleting your account is permanent. All data associated with your account will be lost.