Skip to main content

euclidean distance

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

hamming distance

Nov 19, 2022CodeCatch

0 likes • 0 views

const hammingDistance = (num1, num2) =>
((num1 ^ num2).toString(2).match(/1/g) || '').length;
hammingDistance(2, 3); // 1

Tree Traversal

Oct 16, 2023CHS

0 likes • 7 views

class TreeNode {
constructor(data, depth) {
this.data = data;
this.children = [];
this.depth = depth;
}
}
function buildNaryTree(hosts) {
const nodeMap = {};
// Step 1: Create a map of nodes using fqdn as the key
hosts.forEach((host) => {
nodeMap[host.fqdn] = new TreeNode(host, 0); // Initialize depth to 0
});
// Step 2: Iterate through the array and add each node to its parent's list of children
hosts.forEach((host) => {
if (host.displayParent) {
if (nodeMap[host.displayParent]) {
const parent = nodeMap[host.displayParent];
const node = nodeMap[host.fqdn];
node.depth = parent.depth + 1; // Update the depth
parent.children.push(node);
} else {
console.error(`Parent with fqdn ${host.displayParent} not found for ${host.fqdn}`);
}
}
});
// Find the root nodes (nodes with no parent)
const rootNodes = hosts.filter((host) => !host.displayParent).map((host) => nodeMap[host.fqdn]);
return rootNodes;
}
function treeToObjects(node) {
const result = [];
function inOrder(node) {
if (!node) {
return;
}
// Visit the current node and add it to the result
result.push(node.data);
// Visit children nodes first
node.children.forEach((child) => {
inOrder(child);
});
}
inOrder(node);
return result;
}
// Usage example
const hosts = [
{
fqdn: 'fqdn_1',
display_name: 'Host 1',
},
{
fqdn: 'fqdn_2',
display_name: 'Host 2',
displayParent: 'fqdn_1',
},
{
fqdn: 'fqdn_3',
display_name: 'Host 3'
},
{
fqdn: 'fqdn_4',
display_name: 'Host 4',
displayParent: 'fqdn_3',
},
{
fqdn: 'fqdn_5',
display_name: 'Host 5',
displayParent: 'fqdn_1',
},
];
const tree = buildNaryTree(hosts);
// Function to convert the tree to an array of objects
function convertTreeToArray(nodes) {
const result = [];
nodes.forEach((node) => {
result.push(...treeToObjects(node));
});
return result;
}
// Convert the tree back to an array of objects
const arrayFromTree = convertTreeToArray(tree);
console.log(arrayFromTree);

Responsive Bootstrap Card.Img

Jan 25, 2023CHS

0 likes • 8 views

const ResponsiveCardImg = styled(Card.Img)`
// For screens wider than 768px
@media(min-width: 768px) {
// Your responsive styles here.
}
// For screens smaller than 768px
@media(max-width: 768px) {
// Your responsive styles here.
}
`
export default function App() {
return (
<MainContainer>
<Container>
<Card text='white' bg='dark' style={styles.mainCard}>
<ResponsiveCardImg
style={styles.cardImage}
onClick={handleClick}
src={apeImage}
alt='Degenerate Ape Academy'
/>
<Card.Body>
<Card.Title className='text-center' as='h2'>
{apeId}
</Card.Title>
</Card.Body>
</Card>
</Container>
</MainContainer>
);
}

Invert Binary Tree

Oct 15, 2022CodeCatch

2 likes • 6 views

var invertTree = function(root) {
const reverseNode = node => {
if (node == null) {
return null
}
reverseNode(node.left);
reverseNode(node.right);
let holdLeft = node.left;
node.left = node.right;
node.right = holdLeft;
return node;
}
return reverseNode(root);
};

CodeCatchCrasher

Feb 11, 2021LeifMessinger

0 likes • 2 views

function spam(times = 1,log = true){
for(let i = 0; i < times; i++){
$.get("backend-search.php", {term: (" "+Date.now())}).done(function(data){
if(log) console.log(data);
});
}
}
spam(100000);

Scrape twitter

Sep 2, 2023LeifMessinger

0 likes • 9 views

//Allegedly never tested on the twitter website
function scrapeScreen(){
let articles = Array.from(document.getElementsByTagName("article"));
let results = [];
for(let tweet of articles){
const isAnAd = Array.from(tweet.querySelectorAll("span")).map((e)=>e.textContent).includes("Ad");
if(isAnAd){
//console.log(tweet, "is an ad. Skipping...");
continue;
}
const userName = tweet.querySelector("[data-testid='User-Name'] > div:nth-child(2) > div > div")?.textContent;
const tweetContent = tweet.querySelector("[data-testid='tweetText']")?.textContent;
const timeStamp = tweet.querySelector("time")?.getAttribute("datetime");
const tweetLink = tweet.querySelector("time")?.parentElement?.getAttribute("href");
if((!userName) || (!tweetContent)) continue;
results.push({
username: userName,
tweetText: tweetContent,
timeStamp: timeStamp,
tweetLink: tweetLink
});
}
return results;
}
let scraped = scrapeScreen();
setInterval(()=>{
scraped = scraped.concat(
scrapeScreen().filter((tweet)=>{
for(let scrapedTweet of scraped){
if(scrapedTweet.username == tweet.username && scrapedTweet.tweetText == tweet.tweetText) return false;
}
return true;
})
);
}, 500); //Scrape everything on the screen twice a second
window.scrollIntervalId = setInterval(function(){
window.scrollBy(0, 1000);
}, 500); //Scroll for me
//http://bgrins.github.io/devtools-snippets/#console-save
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, '\t')
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
setTimeout(()=>{
clearTimeout(window.scrollIntervalId);
delete window.scrollIntervalId;
console.save(scraped, "TwitterScrape" + Date.now() + ".json");
}, 60 * 1000 * 20); //Twenty minutes