row_id int64 0 48.4k | init_message stringlengths 1 342k | conversation_hash stringlengths 32 32 | scores dict |
|---|---|---|---|
19,393 | How can extend models of huggingface and adding custom value? | a62de7fc73b9f6d86a9446690e68ec95 | {
"intermediate": 0.22183622419834137,
"beginner": 0.10752794146537781,
"expert": 0.6706358790397644
} |
19,394 | something wrong here. the images got recieved from backend are not properly aligned. the "<canvas id='imageCanvas' class='image-canvas'></canvas>" is for the main current output, while gallery should contain only previous images properly and endlessly aligned and auto-fitted strictly only withing gallery container, not the main canvas output. now everything is mixed there. don't know what to do. only show what need to modify or add.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const ctx = canvas.getContext('2d');
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i=0; i<galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if(xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
});
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(galleryCanvas);
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | e30fc5b02c9daac46788b3fec87e3192 | {
"intermediate": 0.30727675557136536,
"beginner": 0.48973992466926575,
"expert": 0.2029832899570465
} |
19,395 | something wrong here. the images got recieved from backend are not properly aligned. the "<canvas id='imageCanvas' class='image-canvas'></canvas>" is for the main current output, while gallery should contain only previous images properly and endlessly aligned and auto-fitted strictly only withing gallery container, not the main canvas output. now everything is mixed there. don't know what to do. only show what need to modify or add.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const ctx = canvas.getContext('2d');
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i=0; i<galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if(xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
});
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(galleryCanvas);
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | a89520cfb836c6aff342d7dc2ad8c34e | {
"intermediate": 0.30727675557136536,
"beginner": 0.48973992466926575,
"expert": 0.2029832899570465
} |
19,396 | something wrong here. the images got recieved from backend are not properly aligned. the "<canvas id='imageCanvas' class='image-canvas'></canvas>" is for the main current output, while gallery should contain only previous images properly and endlessly aligned and auto-fitted strictly only withing gallery container, not the main canvas output. now everything is mixed there. don't know what to do. only show what need to modify or add.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const ctx = canvas.getContext('2d');
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i=0; i<galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if(xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
});
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(galleryCanvas);
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | 0087dd28995e490bf99662cf0087de7b | {
"intermediate": 0.30727675557136536,
"beginner": 0.48973992466926575,
"expert": 0.2029832899570465
} |
19,397 | Hey there, I need you to do this, first think of a business idea (it is not going to be real, only for school), then give me the code for a website for the business idea (with multiple pages, professionally) and mention in the code where I need to put images. Thank you | 97d2970f3a8e289e73f88c863ed0e452 | {
"intermediate": 0.3947972059249878,
"beginner": 0.35265496373176575,
"expert": 0.25254783034324646
} |
19,398 | public static void main(String[] args) explain what this means | 120e96a5f2fa92e1a2925f0ba2756662 | {
"intermediate": 0.36865249276161194,
"beginner": 0.4811995029449463,
"expert": 0.15014800429344177
} |
19,399 | Specification
Create a new class in your Unit 1 project call CastingOverloading
Write each of the methods listed below
You may only use Math.random(), math ops, and casting for this assignment. You may not use conditionals.
(14) public static int oneOrZero()
//return a 0 or 1 at random
(15) public static int zeroTo99I()
//return a random integer from 0 to 99
(16) public static double zeroTo99D()
//return a random double from 0 to 99
(17) public static int zeroToN(int n)
//return a random integer from 0 to n
(18) public static double zeroToN(double n)
//return a random double from 0.0 to n
(19) public static int minToMax(int min, int max)
// return a random integer from min to max (exclusive)
(20) public static double minToMax(double min, double max)
// return a random double from min to max (exclusive) | d4dd2b9f38da5bbdd804b922b5835919 | {
"intermediate": 0.19663606584072113,
"beginner": 0.6257636547088623,
"expert": 0.17760030925273895
} |
19,400 | web scrape google map review by review link with python in single file | cb24e897b48d90cd2202e056c855955d | {
"intermediate": 0.3349335491657257,
"beginner": 0.28503772616386414,
"expert": 0.38002872467041016
} |
19,401 | Power BI: New Column extracting Month, week number | dbfe800ab79c46837e47bb5f50ec4aab | {
"intermediate": 0.22616036236286163,
"beginner": 0.2706215977668762,
"expert": 0.5032179951667786
} |
19,402 | web scrape a google maps review with the link by using python | 4410b20fb7202792a85d3d84dc32f135 | {
"intermediate": 0.36697515845298767,
"beginner": 0.28575387597084045,
"expert": 0.3472709357738495
} |
19,403 | 请你作为nanogpt的大师级别人物,修改一下下面的程序,程序运行结果是: File "D:\NanoGPT-修仙小说-1\data\shakespeare_char\prepare.py", line 6
input_file_path = os.path.join(os.path.dirname(file), 'input.txt’)
^
SyntaxError: unterminated string literal (detected at line 6),,,程序是:import os
import pickle
import requests
# 下载中文网络小说数据集
input_file_path = os.path.join(os.path.dirname(file), 'input.txt’)
if not os.path.exists(input_file_path):
data_url = 'https://path_to_chinese_web_novel_dataset.txt’
with open(input_file_path, 'w’, encoding='utf-8’) as f:
f.write(requests.get(data_url).text)
with open(input_file_path, 'r’, encoding='utf-8’) as f:
data = f.read()
print(f"dataset length in characters: {len(data):,}")
# 创建训练集和验证集的拆分
n = len(data)
train_data = data[:int(n * 0.9)]
val_data = data[int(n * 0.9):]
# 导出文本文件
with open(os.path.join(os.path.dirname(file), 'train.txt’), 'w’, encoding='utf-8’) as f:
f.write(train_data)
with open(os.path.join(os.path.dirname(file), 'val.txt’), 'w’, encoding='utf-8’) as f:
f.write(val_data)
# 保存元数据信息,以便后续编码/解码
vocab = list(set(data))
vocab_size = len(vocab)
meta = {
'vocab_size’: vocab_size,
'vocab’: vocab,
}
with open(os.path.join(os.path.dirname(file), 'meta.pkl’), 'wb’) as f:
pickle.dump(meta, f)
print(“数据预处理和保存完毕!”) | 08f91b4c5ad2a1a0e278a9e289d3015f | {
"intermediate": 0.21275778114795685,
"beginner": 0.640382707118988,
"expert": 0.1468595713376999
} |
19,404 | button.addEventListener('click', () => {
exportPlugin.downloadFile('csv', {
bom: false,
columnDelimiter: ',',
columnHeaders: false,
exportHiddenColumns: true,
exportHiddenRows: true,
fileExtension: 'csv',
filename: 'Handsontable-CSV-file_[YYYY]-[MM]-[DD]',
mimeType: 'text/csv',
rowDelimiter: '\r\n',
rowHeaders: true
});
});这个下载下来后的csv文件是中文乱码,vue3+Handsontable | aa6fd1033c4b4718507256fc588b8135 | {
"intermediate": 0.40219083428382874,
"beginner": 0.23281832039356232,
"expert": 0.36499089002609253
} |
19,405 | Sometimes when I run this code, it places the values in the correct cell.
Othertimes it places the values in the wrong position.
Does it have something to do with the variable stored in memory?
Private activeCellRange As Range
Private Sub UserForm_Initialize()
' Assign the active cell to the property variable
Set activeCellRange = activeCell
End Sub
Private Sub StartEndButton1_Click()
' Update the start and end times in columns AD and AE using the stored active cell
activeCellRange.Offset(0, 28).Value = StartTime.Value
activeCellRange.Offset(0, 29).Value = EndTime.Value
' Hide the form
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
' Cancel the close event to avoid closing the form unintentionally
If CloseMode = 0 Then
Cancel = True
Me.Hide
End If
End Sub | d53ffaddee8e5ab27e7de60639c31149 | {
"intermediate": 0.5568932890892029,
"beginner": 0.27911341190338135,
"expert": 0.16399329900741577
} |
19,406 | Provide me with the html and the css of a newsletter subscription form for a travel site. The requested fields are: nick name, email address, multi select checkbox for topics: new blog articles, discounted offer. In addition to this there is a gdpr radio button. If it is not checked the form can not be submitted. In this case a modal dialog should pop up saying | de6dcd747785e0600e550e40f1a22775 | {
"intermediate": 0.2629873752593994,
"beginner": 0.26120296120643616,
"expert": 0.47580966353416443
} |
19,407 | I have a table with columns Month, Customer, SKU. How to create a measure using DAX to calculate the number of unique pairs Customer and SKU? I would like to visualize such pairs for each month | 40c4b3dbb2f54b1e61a7f0f69f918605 | {
"intermediate": 0.36244192719459534,
"beginner": 0.19921953976154327,
"expert": 0.4383385181427002
} |
19,408 | SyntaxError: The requested module 'aws-sdk' does not provide an export named 'CognitoIdentityServiceProvider'
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:190:5) | 1bcf61e6bd45809ed4231b088eb2c80e | {
"intermediate": 0.3265213370323181,
"beginner": 0.5671848654747009,
"expert": 0.10629380494356155
} |
19,409 | make a python function to print the first 1000 primal numbers | 41740afa1d4a8d8a8286c971e6cfa29e | {
"intermediate": 0.30751410126686096,
"beginner": 0.4625997245311737,
"expert": 0.22988617420196533
} |
19,410 | get first 3 page pdf file and create pdf with them python | 82415186f72ef84ff4321c9e96c2d379 | {
"intermediate": 0.39768657088279724,
"beginner": 0.24736815690994263,
"expert": 0.35494527220726013
} |
19,411 | What's more secure? scp or sftp? Be concise. | b1708baaf295f9f3959f29daaa0a0851 | {
"intermediate": 0.3076838254928589,
"beginner": 0.3595719635486603,
"expert": 0.33274415135383606
} |
19,412 | write a unittest to download the file, python | baeb49a95b10598bf70cd39d451831d4 | {
"intermediate": 0.5256356596946716,
"beginner": 0.18172332644462585,
"expert": 0.2926409840583801
} |
19,413 | File "C:\Python27\ArcGIS10.7\lib\site-packages\pandas\core\internals.py", line 3290, in get
loc = self.items.get_loc(item)
File "C:\Python27\ArcGIS10.7\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
File "pandas/hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
File "pandas/hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: '\xe5\x9c\xb0\xe5\x9d\x97\xe5\x90\x8d\xe7\xa7\xb0/ID'
# -- coding: utf-8 --
import pandas as pd
import os
df = pd.read_excel(r'F:\GEE\wurenlongchang\\1.xlsx')
filtered_df = df[df['地块名称/ID'] == 8023]
another_value = filtered_df['种植作物'].iloc[0]
print(another_value)如何结局 | dad3e9066f1e1da8a907efd0fe3b4320 | {
"intermediate": 0.3334828317165375,
"beginner": 0.4760659337043762,
"expert": 0.19045127928256989
} |
19,414 | create a system for control employees using array in c programing. | aa0a633e04bd99fda908ca2d4ced14d9 | {
"intermediate": 0.21807861328125,
"beginner": 0.18003204464912415,
"expert": 0.6018893718719482
} |
19,415 | Can Firejail disable USB access? If so, how? | eb8d1c4d4bf888ed7440bd0c17fc62c5 | {
"intermediate": 0.5177753567695618,
"beginner": 0.18818512558937073,
"expert": 0.29403945803642273
} |
19,416 | Write tests for this function | c5500a5e27e3ed5c3ae5b426b25f4807 | {
"intermediate": 0.4157879650592804,
"beginner": 0.22148525714874268,
"expert": 0.36272674798965454
} |
19,417 | Write a unittest for this function python | 14a5bcc87d24feb388cf74981000a56c | {
"intermediate": 0.46018078923225403,
"beginner": 0.27280738949775696,
"expert": 0.2670117914676666
} |
19,418 | I have a at-mega32 micro controller and a 3pin 10K potentiameter, this controller have to program to turn on and off 6 white led this leds have to light based on potentiometer value from 0 to 10 - when potentiometer is at max all the leds are turned on and when and when it at the lowest all leds are turned off, what would be the instruction and circuit map to do this task , my power supply is 12vDc which I want to connect to my 10K potentiometer and I also have 5VDC in my board, | e20c4b5165577fdab8f5420bf986f73f | {
"intermediate": 0.4383702576160431,
"beginner": 0.20248478651046753,
"expert": 0.35914498567581177
} |
19,419 | Make a dll in c++ that uses imgui and injects into a unity game and spawns an imgui window | 7c9abc1b5650f67dfa2ee8e3482d7af4 | {
"intermediate": 0.5294157862663269,
"beginner": 0.21013857424259186,
"expert": 0.26044556498527527
} |
19,420 | I have a light circuit board to power a white light LED in this circuit I have a 10 k SMD potentiometer wich is embedded in the board; i want to use a external 10k potentiometer to achive this 2 purposes; 1- to control light intensity by changing value of potentiometer and 2- join and read the value of potentiometer with a AT-Mega32 and based on value of potentiometer light up 6 LEDs( at-mega32 micro controller and a 3pin 10K potentiameter, this controller have to program to turn on and off 6 white leds; this leds have to light based on potentiometer value from 0 to 10 - when potentiometer is at max all the leds are turned on and when and when it at the lowest all leds are turned off, what would be the instruction and circuit map to do this task , my power supply is 12vDc which is connect to my 10K potentiometer and I also have 5VDC in my board, | 7816438ed67bd83c3a59bbac5ad9f7b9 | {
"intermediate": 0.4870077669620514,
"beginner": 0.1790265440940857,
"expert": 0.3339656889438629
} |
19,421 | # -- coding: utf-8 --
import arcpy
import os
import glob
import re
import datetime
import pandas as pd
from arcpy.sa import *
arcpy.CheckOutExtension('Spatial')
arcpy.env.overwriteOutput = True
class BatchClip:
def __init__(self, inws, outws, mask):
self.inws = inws
self.outws = outws
self.mask = mask
print(self.inws)
def clip(self):
if not os.path.exists(self.outws):
os.mkdir(self.outws)
rasters = glob.glob(os.path.join(self.inws, "*.tif"))
shps = glob.glob(os.path.join(self.mask, "*.shp"))
inwsname = self.inws[-5:]
for shp in shps:
shp_name = os.path.basename(shp)
# print(shp_name)
for ras in rasters:
ras_name = os.path.basename(ras)
shpname = shp_name[-8:-4]
rastername = ras_name[:8]
nameT = inwsname + shpname+"_"+ rastername + ".tif"
outname = os.path.join(self.outws, nameT)
out_extract = arcpy.sa.ExtractByMask(ras, shp)
out_extract.save(outname)
print(" ----Batchclip down ----")
class RasterReclassify:
def __init__(self, workspace):
# Set workspace
self.workspace = workspace
arcpy.env.workspace = self.workspace
def reclassify_rasters(self, index):
folder = arcpy.env.workspace[-4:]
# print(folder)
folder_name = "reclassify" + folder
folder_path = os.path.join(arcpy.env.workspace) #dirname
raclassify_output_path = os.path.join(folder_path, folder_name)
# print(raclassify_output_path)
if not os.path.exists(raclassify_output_path):
os.mkdir(raclassify_output_path)
rasterlist = arcpy.ListRasters("*", "tif")
# print("raster:",rasterlist)
if rasterlist is not None:
for raster in rasterlist:
inRaster = arcpy.Raster(raster)
# print(inRaster)
time = inRaster.name[5:18]
# print(time)
out = os.path.join(raclassify_output_path, time + ".tif")
# print(out)
# if index == "ndvi":
# # NDVI
outCon = arcpy.sa.Con(inRaster <= 0.19, 1,
arcpy.sa.Con((inRaster > 0.19) & (inRaster <= 0.39), 2,
arcpy.sa.Con((inRaster > 0.39) & (inRaster <= 0.55), 3,
arcpy.sa.Con((inRaster > 0.55) & (inRaster <= 0.75), 4,
arcpy.sa.Con((inRaster > 0.75), 5)))))
# elif index == "gndvi":
# # GNDVI
# outCon = arcpy.sa.Con(inRaster <= 0.2, 1,
# arcpy.sa.Con((inRaster > 0.2) & (inRaster <= 0.4), 2,
# arcpy.sa.Con((inRaster > 0.4) & (inRaster <= 0.6), 3,
# arcpy.sa.Con((inRaster > 0.6) & (inRaster <= 0.8), 4,
# arcpy.sa.Con((inRaster > 0.8), 5)))))
# elif index == "vci":
# # VCI
# outCon = arcpy.sa.Con(inRaster <= 0.15, 1,
# arcpy.sa.Con((inRaster > 0.15) & (inRaster <= 0.3), 2,
# arcpy.sa.Con((inRaster > 0.3) & (inRaster <= 0.45), 3,
# arcpy.sa.Con((inRaster > 0.45) & (inRaster <= 0.6), 4,
# arcpy.sa.Con((inRaster > 0.6), 5)))))
# elif index == "chlor":
# # Chlor
outCon = arcpy.sa.Con(inRaster <= 12, 1,
arcpy.sa.Con((inRaster > 12) & (inRaster <= 21), 2,
arcpy.sa.Con((inRaster > 21) & (inRaster <= 32), 3,
arcpy.sa.Con((inRaster > 32) & (inRaster <= 43), 4,
arcpy.sa.Con((inRaster > 43), 5)))))
outCon.save(out)
print("---raclassify down---")
class RasterToPolygonConverter:
def __init__(self, input_raster_path, output_shp_path):
self.input_raster_path = input_raster_path
self.output_shp_path = output_shp_path
def convert_raster_to_polygon(self):
# Set workspace
arcpy.env.workspace = self.input_raster_path
# print(arcpy.env.workspace)
# Create output folder if it doesn’t exist
if not os.path.exists(self.output_shp_path):
os.mkdir(self.output_shp_path)
# List raster files
rasters = arcpy.ListRasters("*", "tif")
# print("rasterstopolygon:",rasters)
for raster in rasters:
# Extract catchment name from raster filename
catchment_name = raster[:13]
# print(catchment_name)
# Set output shapefile path
shp_out_name = os.path.join(self.output_shp_path, catchment_name)
# print(shp_out_name)
# Convert raster to polygon
arcpy.RasterToPolygon_conversion(raster, shp_out_name, "true", "Value")
# print("finished")
print("---polygon down---")
class Dissolve:
def __init__(self, input_workspace, output_workspace):
self.input_workspace = input_workspace
self.output_workspace = output_workspace
def dissolve_shapefiles(self):
arcpy.env.workspace = self.input_workspace
shps = arcpy.ListFiles("*.shp")
if shps is not None:
for shp in shps:
catchment_name = shp[:13]
print(catchment_name)
disslove_out_name = os.path.join(self.output_workspace,catchment_name)
# print(disslove_out_name)
arcpy.Dissolve_management(shp, disslove_out_name, "gridcode")
# print("Finished dissolving")
class FieldCalculator:
def __init__(self, input_polygon, df):
self.input_polygon = input_polygon
self.df = df
def calculate_fields(self):
current_year = datetime.datetime.now().year
# if not os.path.exists(self.input_polygon):
# return
# path_list = os.listdir(self.input_polygon)
# for i in range(len(path_list)):
# landid = path_list[i][:4]
# print(landid)
# # path = os.path.join(self.input_polygon, path_list[i])
shps = glob.glob(os.path.join(self.input_polygon, "*.shp"))
for shp in shps:
catchment_name = shp[-12:-4]
landid= shp[-17:-13]
print(landid)
if landid is not None:
filtered_df = self.df[self.df['ID'] == landid]
crop = filtered_df[u'种植作物'].iloc[0]
print('crop:',crop)
date = int(catchment_name)
arcpy.DeleteField_management(shp, ["id"])
field_names = [f.name for f in arcpy.ListFields(shp)]
if 'date' not in field_names:
arcpy.AddField_management(shp, 'date', 'Long')
arcpy.CalculateField_management(shp, 'date', expression=date, expression_type="python", code_block="")
if 'landId' not in field_names:
arcpy.AddField_management(shp, 'landId', 'Short')
arcpy.CalculateField_management(shp, 'landId', landid, expression_type="python")
if 'landName' not in field_names:
arcpy.AddField_management(shp, 'landName', 'TEXT')
if 'crop' not in field_names:
arcpy.AddField_management(shp, 'crop', 'TEXT')
arcpy.CalculateField_management(shp, 'Area', crop, expression_type="python")
if 'Area' not in field_names:
arcpy.AddField_management(shp, 'Area', 'Double')
arcpy.CalculateField_management(shp, 'Area', "!SHAPE.area!", expression_type="python")
if 'Area_mu' not in field_names:
arcpy.AddField_management(shp, 'Area_mu', 'Double')
if 'year' not in field_names:
arcpy.AddField_management(shp, 'year', 'Double')
arcpy.CalculateField_management(shp, 'year', current_year, expression_type="python")
print("---dbf down---")
def main():
# Set input and output paths
inws = r"F:\GEE\wurenlongchang\tif\wurenlongchangCHLOR"
outws = r"F:\GEE\wurenlongchang\chor"
mask = r"F:\GEE\wurenlongchang\1_shp"
# Batch clip rasters
batch_clip = BatchClip(inws, outws, mask)
batch_clip.clip()
# Reclassify rasters
reclassify_workspace = os.path.join(outws)
rr = RasterReclassify(reclassify_workspace)
# rr.reclassify_rasters("ndvi")
rr.reclassify_rasters("gndvi")
# rr.reclassify_rasters("vci")
# rr.reclassify_rasters("chlor")
# Convert rasters to polygons
polygon_workspace = os.path.join(outws)
folder = polygon_workspace[-4:]
folder_name = "polygon" + folder
output_polygon_path = os.path.join(outws, folder_name)
raclassify_output_path = os.path.join(outws, "reclassify" + folder) # 定义 raclassify_output_path 变量
converter = RasterToPolygonConverter(raclassify_output_path, output_polygon_path)
converter.convert_raster_to_polygon()
# Dissolve polygons
dissolve_workspace = os.path.join(outws)
folder = dissolve_workspace[-4:]
folder_name = "dissolve" + folder
output_dissolve_path = os.path.join(outws, folder_name)
if not os.path.exists(output_dissolve_path):
os.mkdir(output_dissolve_path)
dissolve = Dissolve(output_polygon_path, output_dissolve_path)
dissolve.dissolve_shapefiles()
# Calculate fields
df = pd.read_excel(ur'F:\GEE\wurenlongchang\\遥感地块信息.xlsx')
field_calculator = FieldCalculator(output_dissolve_path,df)
field_calculator.calculate_fields()
arcpy.ClearWorkspaceCache_management()
if __name__ == "__main__":
main()
Traceback (most recent call last):
File "f:/GEE/wurenlongchang/3.py", line 272, in <module>
main()
File "f:/GEE/wurenlongchang/3.py", line 267, in main
field_calculator.calculate_fields()
File "f:/GEE/wurenlongchang/3.py", line 187, in calculate_fields
filtered_df = self.df[self.df['ID'] == landid]
File "C:\Python27\ArcGIS10.7\lib\site-packages\pandas\core\ops.py", line 763, in wrapper
res = na_op(values, other)
File "C:\Python27\ArcGIS10.7\lib\site-packages\pandas\core\ops.py", line 718, in na_op
raise TypeError("invalid type comparison")
TypeError: invalid type comparison如何解决 | b06a1da417eca89a42a03f7e56050619 | {
"intermediate": 0.30591341853141785,
"beginner": 0.5453974008560181,
"expert": 0.14868910610675812
} |
19,422 | const BigOrders = ({workerRef, symbol}: BigOrdersProps) => {
const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio));
const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0});
const containerRef = useRef<HTMLDivElement|null>(null);
const canvasRef = useRef<HTMLCanvasElement|null>(null);
const precision = useSelector((state: AppState) => state.binancePrecision.futures);
const {symbols} = useBinanceSymbols();
const cupSubscribe = useCallback(async(symbol: string, precision: {[key: string]: Precision}, symbols: string[]) => {
workerRef.current?.postMessage(JSON.stringify({type: "subscribe", symbol, precision, symbols}));
}, []);
const cupUnsubscribe = useCallback(async(pair: string) => {
workerRef.current?.postMessage(JSON.stringify({type: "unsubscribe", symbol}));
}, []);
const wheelHandler = (e: WheelEvent) => {
e.preventDefault();
workerRef.current?.postMessage(JSON.stringify({type: e.deltaY < 0 ? "camera_up" : "camera_down"}));
};
useEffect(() => {
workerRef.current = new Worker(new URL("/workers/big-order-builder.ts", import.meta.url));
canvasRef.current?.addEventListener("wheel", wheelHandler, {passive: false});
return () => {
workerRef.current?.terminate();
canvasRef.current?.removeEventListener("wheel", wheelHandler);
};
}, []);
useEffect(() => {
if (!workerRef.current) return;
let animationFrameId: number|null = null;
interface UpdateBigOrderEvent {
type: “update_big_order”,
id: number,
symbol: string,
price: number,
quantity: number,
pricePrecision: number,
quantityPrecision: number,
}
workerRef.current.onmessage = (event: MessageEvent<UpdateBigOrderEvent>) => {
// console.log(event?.data?.id);
if (event?.data?.type === “update_big_order”) {
if (null !== animationFrameId) {
// console.log(animationFrameId);
cancelAnimationFrame(animationFrameId);
}
animationFrameId = requestAnimationFrame(() => {
const data = event.data as UpdateBigOrderEvent;
// console.log(data);
const context = canvasRef.current?.getContext(“2d”);
if (context) {
// cupDrawer.clear(context, canvasSize);
const rowsOnScreenCount = cupTools.getRowsCountOnScreen(
canvasSize.height,
bigOrdersOptions(darkMode).cell.defaultHeight * dpiScale,
);
const realCellHeight = parseInt((canvasSize.height / rowsOnScreenCount).toFixed(0));
if (data.price !== 0) {
bigOrdersDrawer.draw(
context,
canvasSize,
dpiScale,
data.id,
data.symbol,
data.price,
data.quantity,
data.pricePrecision,
data.quantityPrecision,
realCellHeight,
);
}
}
});
}
};
return () => {
if (null !== animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}, [workerRef.current, canvasSize, darkMode, dpiScale, isLoaded]);
return <div ref={containerRef} className={styles.canvasWrapper}>
<canvas
ref={canvasRef}
className={styles.canvas}
width={canvasSize?.width}
height={canvasSize?.height}
/>
</div>;
};
const bigOrdersDrawer = {
clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => {
ctx.clearRect(0, 0, size.width, size.height);
},
draw: (
ctx: CanvasRenderingContext2D,
size: CanvasSize,
dpiScale: number,
id: number,
symbol: string,
price: number,
quantity: number,
pricePrecision: number,
quantityPrecision: number,
cellHeight: number,
) => {
const quantityDivider = Math.pow(10, quantityPrecision);
const priceDivider = Math.pow(10, pricePrecision);
const yPosition = cellHeight * id;
bigOrdersDrawer.drawSymbol(
ctx,
symbol,
yPosition,
cellHeight,
size.width,
dpiScale,
true
);
bigOrdersDrawer.drawPrice(
ctx,
price / priceDivider,
yPosition,
cellHeight,
size.width,
dpiScale,
true
);
bigOrdersDrawer.drawQuantity(
ctx,
quantity / quantityDivider,
yPosition,
cellHeight,
size.width,
dpiScale,
true
);
drawSymbol: (
ctx: CanvasRenderingContext2D,
symbol: string,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
symbol,
0,
yPosition + cellHeight / 2,
);
},
drawPrice: (
ctx: CanvasRenderingContext2D,
price: number,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
price.toString(),
(fullWidth / 2) - (bigOrdersOptions().cell.paddingX * dpiScale),
yPosition + cellHeight / 2,
);
},
drawQuantity: (
ctx: CanvasRenderingContext2D,
quantity: number,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
const {width: textWidth} = ctx.measureText(quantity.toString());
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
quantity.toString(),
fullWidth - bigOrdersOptions().cell.paddingX * dpiScale - textWidth,
yPosition + cellHeight / 2,
);
},
};
export default bigOrdersDrawer;
у нас отрисовываются bigOrdersDrawer.draw, умножается на id и этим высчитывает высоту, получается столбик с данными.
Нужно, чтобы когда они отрисовываются в самом низу, то канвас начинал скроллиться и показывать внизу последние добавленные, так же нужно, чтобы можно было скроллить вверх и вниз | 634ec84a331efa246953ca45a13fa9b3 | {
"intermediate": 0.34134015440940857,
"beginner": 0.48685893416404724,
"expert": 0.1718008667230606
} |
19,423 | const BigOrders = ({workerRef, symbol}: BigOrdersProps) => {
const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio));
const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0});
const containerRef = useRef<HTMLDivElement|null>(null);
const canvasRef = useRef<HTMLCanvasElement|null>(null);
const precision = useSelector((state: AppState) => state.binancePrecision.futures);
const {symbols} = useBinanceSymbols();
const cupSubscribe = useCallback(async(symbol: string, precision: {[key: string]: Precision}, symbols: string[]) => {
workerRef.current?.postMessage(JSON.stringify({type: "subscribe", symbol, precision, symbols}));
}, []);
const cupUnsubscribe = useCallback(async(pair: string) => {
workerRef.current?.postMessage(JSON.stringify({type: "unsubscribe", symbol}));
}, []);
const wheelHandler = (e: WheelEvent) => {
e.preventDefault();
workerRef.current?.postMessage(JSON.stringify({type: e.deltaY < 0 ? "camera_up" : "camera_down"}));
};
useEffect(() => {
workerRef.current = new Worker(new URL("/workers/big-order-builder.ts", import.meta.url));
canvasRef.current?.addEventListener("wheel", wheelHandler, {passive: false});
return () => {
workerRef.current?.terminate();
canvasRef.current?.removeEventListener("wheel", wheelHandler);
};
}, []);
useEffect(() => {
if (!workerRef.current) return;
let animationFrameId: number|null = null;
interface UpdateBigOrderEvent {
type: “update_big_order”,
id: number,
symbol: string,
price: number,
quantity: number,
pricePrecision: number,
quantityPrecision: number,
}
workerRef.current.onmessage = (event: MessageEvent<UpdateBigOrderEvent>) => {
// console.log(event?.data?.id);
if (event?.data?.type === “update_big_order”) {
if (null !== animationFrameId) {
// console.log(animationFrameId);
cancelAnimationFrame(animationFrameId);
}
animationFrameId = requestAnimationFrame(() => {
const data = event.data as UpdateBigOrderEvent;
// console.log(data);
const context = canvasRef.current?.getContext(“2d”);
if (context) {
// cupDrawer.clear(context, canvasSize);
const rowsOnScreenCount = cupTools.getRowsCountOnScreen(
canvasSize.height,
bigOrdersOptions(darkMode).cell.defaultHeight * dpiScale,
);
const realCellHeight = parseInt((canvasSize.height / rowsOnScreenCount).toFixed(0));
if (data.price !== 0) {
bigOrdersDrawer.draw(
context,
canvasSize,
dpiScale,
data.id,
data.symbol,
data.price,
data.quantity,
data.pricePrecision,
data.quantityPrecision,
realCellHeight,
);
}
}
});
}
};
return () => {
if (null !== animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}, [workerRef.current, canvasSize, darkMode, dpiScale, isLoaded]);
return <div ref={containerRef} className={styles.canvasWrapper}>
<canvas
ref={canvasRef}
className={styles.canvas}
width={canvasSize?.width}
height={canvasSize?.height}
/>
</div>;
};
const bigOrdersDrawer = {
clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => {
ctx.clearRect(0, 0, size.width, size.height);
},
draw: (
ctx: CanvasRenderingContext2D,
size: CanvasSize,
dpiScale: number,
id: number,
symbol: string,
price: number,
quantity: number,
pricePrecision: number,
quantityPrecision: number,
cellHeight: number,
) => {
const quantityDivider = Math.pow(10, quantityPrecision);
const priceDivider = Math.pow(10, pricePrecision);
const yPosition = cellHeight * id;
bigOrdersDrawer.drawSymbol(
ctx,
symbol,
yPosition,
cellHeight,
size.width,
dpiScale,
true
);
bigOrdersDrawer.drawPrice(
ctx,
price / priceDivider,
yPosition,
cellHeight,
size.width,
dpiScale,
true
);
bigOrdersDrawer.drawQuantity(
ctx,
quantity / quantityDivider,
yPosition,
cellHeight,
size.width,
dpiScale,
true
);
drawSymbol: (
ctx: CanvasRenderingContext2D,
symbol: string,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
symbol,
0,
yPosition + cellHeight / 2,
);
},
drawPrice: (
ctx: CanvasRenderingContext2D,
price: number,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
price.toString(),
(fullWidth / 2) - (bigOrdersOptions().cell.paddingX * dpiScale),
yPosition + cellHeight / 2,
);
},
drawQuantity: (
ctx: CanvasRenderingContext2D,
quantity: number,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
const {width: textWidth} = ctx.measureText(quantity.toString());
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
quantity.toString(),
fullWidth - bigOrdersOptions().cell.paddingX * dpiScale - textWidth,
yPosition + cellHeight / 2,
);
},
};
export default bigOrdersDrawer;
у нас отрисовываются bigOrdersDrawer.draw, умножается на id и этим высчитывает высоту, получается столбик с данными.
Нужно, чтобы когда они отрисовываются в самом низу, то канвас начинал скроллиться и показывать внизу последние добавленные, так же нужно, чтобы можно было скроллить вверх и вниз
Напиши код, чтобы работало по условию | 7fd6801e234705a603c48efb33a6b14e | {
"intermediate": 0.34134015440940857,
"beginner": 0.48685893416404724,
"expert": 0.1718008667230606
} |
19,424 | interface ListPayload {
osvendor?: string
glibcver?: string
page: number
pagesize: number
type: 'ramdisk' | 'driver'
}
export const fetchList = (payload: ListPayload): Promise<ListResponse> =>
request({
url: '/admin/driver/list',
method: 'post',
data: payload
})
error
:
"failed to get form file by key 'updrvbndl': http: no such file
как исправить ошибку? | 675f1003fc2e4ef8b19829bb86bebb27 | {
"intermediate": 0.4990191161632538,
"beginner": 0.2770492434501648,
"expert": 0.22393164038658142
} |
19,425 | write to me an HTTP code for a website template good for all devices such as pcs laptops mobile phones... the website will be for articles | 58303914c1ad2490049cbdd6dab102b4 | {
"intermediate": 0.42064169049263,
"beginner": 0.30542296171188354,
"expert": 0.27393534779548645
} |
19,426 | make a program in GCBasic for PIC16F819 to control IC SI4012 rf transmitter | 30e516f6060b106451e618746594707e | {
"intermediate": 0.332570344209671,
"beginner": 0.2761653661727905,
"expert": 0.39126425981521606
} |
19,427 | When I click OK on the Form Button, it will occassionaly place the values in the right location.
activeCellRange.Offset(0, 28).Value = StartTime.Value
activeCellRange.Offset(0, 29).Value = EndTime.Value
However most of the time, it does not put the values in the right location.
I also noticed that when I put values into the text boxes in the form and click OK, the form closes, but when I activate the form again the previous values entered in the text boxes are still there.
Is there a variable memory issue that needs to be cleared that may also be affecting the correct location placement of values.
Below is the Form code.
Private activeCellRange As Range
Private Sub UserForm_Initialize()
' Assign the initial active cell to the property variable
Set activeCellRange = ActiveCell
End Sub
Private Sub StartEndButton1_Click()
' Update the start and end times in columns AD and AE using the stored active cell
activeCellRange.Offset(0, 28).Value = StartTime.Value
activeCellRange.Offset(0, 29).Value = EndTime.Value
' Hide the form
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
' Cancel the close event to avoid closing the form unintentionally
If CloseMode = 0 Then
Cancel = True
Me.Hide
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Update the active cell whenever the user selects a different cell
Set activeCellRange = Target
End Sub | 8ec6c4e13201e33dadb4410170a4c558 | {
"intermediate": 0.41780877113342285,
"beginner": 0.33615243434906006,
"expert": 0.24603886902332306
} |
19,428 | make a program in great cow basic for pic18f16q41 to control SI4012 via mssp | 573d6b897e4ede1c4a4f829e8817d31c | {
"intermediate": 0.3290928900241852,
"beginner": 0.24653783440589905,
"expert": 0.4243692457675934
} |
19,429 | simple signup form bootstrap 5 | daa24251a3f4d6b08a103137b795312b | {
"intermediate": 0.3976130783557892,
"beginner": 0.2968144416809082,
"expert": 0.305572509765625
} |
19,430 | Method to upload csv file in to lamda function | d9b6ed88fbff69b0a5dc1b40cfb85bb5 | {
"intermediate": 0.40561386942863464,
"beginner": 0.24538670480251312,
"expert": 0.3489994704723358
} |
19,431 | what is openai | 686750bf090c2dd39ec92ebe43b77b2e | {
"intermediate": 0.3115822970867157,
"beginner": 0.10707437247037888,
"expert": 0.5813433527946472
} |
19,432 | program in GCBasic for PIC16F88 using spi or ssp port | 1782ea831971f47c1884dcc4f808f5e8 | {
"intermediate": 0.25110137462615967,
"beginner": 0.47713932394981384,
"expert": 0.2717593014240265
} |
19,433 | define pic model in gcbasic program like 16f88 how to | e3c2c1bf81ca4aedd00fd5c501935510 | {
"intermediate": 0.2618762254714966,
"beginner": 0.35020244121551514,
"expert": 0.38792139291763306
} |
19,434 | #include "allinclude.h" //DO NOT edit this line
void Descend(int &a, int &b, int &c) // 通过交换,令 a >= b >= c
{ // Add your code here
void swap(int* m, int* n) {
int t = *m;
m = n;
n = t;
}
void Descend(int& a, int& b, int& c) {
int pa = &a;
int pb = &b;
int pc = &c;
if (*pa < *pb) {
swap(pa, pb);
}
if (*pa < *pc) {
swap(pa, pc);
}
if (*pb < *pc) {
swap(pb, pc);
}
}
} In function ‘void Descend(int&, int&, int&)’:
6:31: error: a function-definition is not allowed here before ‘{’ token
void swap(int* m, int* n) {
^
12:42: error: a function-definition is not allowed here before ‘{’ token
void Descend(int& a, int& b, int& c) {
^ | 881eb17c1662f9f53b551a7a1090037a | {
"intermediate": 0.34146642684936523,
"beginner": 0.4377259612083435,
"expert": 0.22080758213996887
} |
19,435 | T1- Write a C# program to create a text file and write the following Text in it, then open the file automatically with coding (Mimicking double-clicking on it). | bd4a5ab6455c8087879af0681a2a9cd6 | {
"intermediate": 0.4214893877506256,
"beginner": 0.2649029493331909,
"expert": 0.31360772252082825
} |
19,436 | how to query sql to display rows that are repeated more than 2 times\ | 73c5de7717548b577ec1e3ddf0bc49dc | {
"intermediate": 0.39632055163383484,
"beginner": 0.35488736629486084,
"expert": 0.24879203736782074
} |
19,437 | const BigOrders = ({workerRef, symbol}: BigOrdersProps) => {
const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio));
const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0});
const containerRef = useRef<HTMLDivElement|null>(null);
const canvasRef = useRef<HTMLCanvasElement|null>(null);
const size = useComponentResizeListener(canvasRef);
const draw = (bigOrders: BigOrder[]) => {
if (null === canvasRef || !Array.isArray(bigOrders)) return;
const context = canvasRef.current?.getContext(“2d”);
const rowsOnScreenCount = cupTools.getRowsCountOnScreen(
canvasSize.height,
bigOrdersOptions(darkMode).cell.defaultHeight * dpiScale,
);
const realCellHeight = parseInt((canvasSize.height / rowsOnScreenCount).toFixed(0));
if (context) {
bigOrdersDrawer.clear(context, canvasSize);
bigOrdersDrawer.drawChain(
context,
canvasSize,
bigOrders,
realCellHeight,
dpiScale,
);
}
};
useEffect(() => {
if (!workerRef.current) return;
let animationFrameId: number|null = null;
interface UpdateBigOrderEvent {
type: “update_big_order”,
bigOrders: BigOrder[],
}
workerRef.current.onmessage = (event: MessageEvent<UpdateBigOrderEvent>) => {
if (event?.data?.type === “update_big_order”) {
if (null !== animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
animationFrameId = requestAnimationFrame(() => draw(event.data.bigOrders));
}
};
return () => {
if (null !== animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}, [workerRef.current, canvasSize, darkMode, dpiScale]);
useEffect(() => {
if (!size) {
return;
}
setCanvasSize({
width: Math.floor(size.width) * dpiScale,
height: Math.floor(size.height) * dpiScale,
});
}, [dpiScale, size]);
return <div ref={containerRef} className={styles.canvasWrapper}>
<canvas
ref={canvasRef}
className={styles.canvas}
width={canvasSize?.width}
height={canvasSize?.height}
/>
</div>;
};
export default BigOrders;
import {BigOrder} from “…/…/…/workers/big-order-builder”;
import {CanvasSize} from “./BigOrders”;
import bigOrdersOptions from “./BigOrders.options”;
const bigOrdersDrawer = {
clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => {
ctx.clearRect(0, 0, size.width, size.height);
},
drawChain: (
ctx: CanvasRenderingContext2D,
canvasSize: CanvasSize,
bigOrders: BigOrder[],
cellHeight: number,
dpiScale: number,
) => {
bigOrders.forEach((order: BigOrder, index: number) => {
const yPosition = cellHeight * index;
bigOrdersDrawer.drawSymbol(
ctx,
order.symbol,
yPosition,
cellHeight,
canvasSize.width,
dpiScale,
true
);
drawSymbol: (
ctx: CanvasRenderingContext2D,
symbol: string,
yPosition: number,
cellHeight: number,
fullWidth: number,
dpiScale: number,
darkMode: boolean,
) => {
ctx.textBaseline = “middle”;
ctx.font = ${bigOrdersOptions().font.weight} ${bigOrdersOptions().font.sizePx * dpiScale}px ${bigOrdersOptions().font.family};
ctx.fillStyle = ${bigOrdersOptions().font.color};
ctx.fillText(
symbol,
0,
yPosition + cellHeight / 2,
);
},
export default bigOrdersDrawer;
высота канвас 200px,
cellHeight // 20px,
// bigOrders.length 100-350
const yPosition = cellHeight * index;
получается на каждый раз когда пробегаемся по массиву через forEach, то yPosition увеличивается // сначала будет равно 0, потом 20, потом 40, потом 60, потом 80 и т.д. Если bigOrders длина 200, то последний элемент будет отображен на оси Y 4000, а canvas всего 200.
Нужно, чтобы canvas можно было скроллить мышкой от самого первого, до самого последнего | e615af4862b9cf9fca6fb1d94a7f4c28 | {
"intermediate": 0.2928033471107483,
"beginner": 0.5604181289672852,
"expert": 0.14677847921848297
} |
19,438 | write a hotel reservation program in python and explain to me | d14212b77e15dae8d1cadb022951b6fe | {
"intermediate": 0.36798155307769775,
"beginner": 0.17639605700969696,
"expert": 0.4556223452091217
} |
19,439 | Create a csv upload endpoint in lamda node js. I want to accept the uploaded CSV file | 44f4950798d3316f288c7e16e940afad | {
"intermediate": 0.5117829442024231,
"beginner": 0.17234455049037933,
"expert": 0.3158726096153259
} |
19,440 | Translator | 998c666d956fdaf90131e89bf2c99cfb | {
"intermediate": 0.3765448033809662,
"beginner": 0.3403303027153015,
"expert": 0.2831248641014099
} |
19,441 | Create a drafting system for a sport, using python code, with teams each with some budget, and a pool of available players | 8dd0d769dbb7c0e7c509958be5f6b15b | {
"intermediate": 0.30854055285453796,
"beginner": 0.21321573853492737,
"expert": 0.47824373841285706
} |
19,442 | how to write python file to get the path of. all the files inside a folder, the path should include the folder | 59c262343a6aed275da5a4168e024c93 | {
"intermediate": 0.4299430847167969,
"beginner": 0.19028271734714508,
"expert": 0.37977421283721924
} |
19,443 | next js how create interactive friend search by nickname | 6e47b4925aa9dd7efeeb60ac90db83d3 | {
"intermediate": 0.34686002135276794,
"beginner": 0.1609032303094864,
"expert": 0.4922367334365845
} |
19,444 | I am having some issues with the following:
In my sheet 'Overtime' a form 'TimeForm1' is activated.
When the form opens, I insert a StartTime value and an EndTime value.
When I click OK on the form button, it is supposed to writre the values I entered into
the ActiveCell.Offset(-1, 28), and to the ActiveCell.Offset(-1, 29) of the 'Overtime' sheet.
Sometimes, it will write the values to the exact location, but most of the time it does not.
Also sometimes when I reactivate the form, the previous values entered in the text boxes are still there.
Can you please help me to solve this problem.
I have included below, the VBA code from the sheet 'Overtime' and the code from 'TimeForm1'.
Overtime Code:
Option Explicit
Private Sub Worksheet_Activate()
Dim activeCellRange As Range
Set activeCellRange = Nothing
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 And IsNumeric(Target.Value) Then
ShowTimeForm Target.Address
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not TimeForm1 Is Nothing Then
TimeForm1.Hide
End If
End Sub
Sub ShowTimeForm(ByVal rngAddress As String)
TimeForm1.ActiveCellRange = Me.Range(rngAddress)
TimeForm1.Show vbModal
End Sub
TimeForm1 - Code:
Public Property Let ActiveCellRange(rng As Range)
Set newActiveCellRange = rng
End Property
Public Property Get ActiveCellRange() As Range
Set ActiveCellRange = ActiveCellRange
End Property
Private Sub UserForm_Initialize()
Me.ActiveCellRange = ActiveCell
End Sub
Private Sub StartEndButton1_Click()
ActiveCell.Offset(-1, 28).Value = StartTime.Value
ActiveCell.Offset(-1, 29).Value = EndTime.Value
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
Cancel = True
Me.Hide
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set ActiveCellRange = Target
End Sub | d9c6bfb94e70f06d2a7b1748154b837f | {
"intermediate": 0.47755351662635803,
"beginner": 0.26876431703567505,
"expert": 0.25368213653564453
} |
19,445 | Я в андроид студио работаю... Так, а если у меня есть загруженный шрифт exo_2 в .ttf, можно ли использовать буквы этого шрифта в drawable .xml? допустим я хочу написать "DC" и еще добавить рамку... | a277a19bcca013ec98d9b8b91ec02dbf | {
"intermediate": 0.3750608563423157,
"beginner": 0.3180009722709656,
"expert": 0.30693820118904114
} |
19,446 | Generate the program code that asynchronously decompresses files from the program resources in C# | 161047a2e21ada161cf72c39345f4df3 | {
"intermediate": 0.419064462184906,
"beginner": 0.17666283249855042,
"expert": 0.40427276492118835
} |
19,447 | return <Box ref={containerRef} className={`${styles.canvasWrapper} scroll-block`}>
<canvas
ref={canvasRef}
className={styles.canvas}
width={canvasSize?.width}
height={canvasSize?.height}
/>
</Box>;
};
нужно скрыть скролл, чтобы скроллилось без полоски прокрутки | 6ce13c36e2d12f5ad547a10bb287168b | {
"intermediate": 0.36955466866493225,
"beginner": 0.3313433527946472,
"expert": 0.2991020083427429
} |
19,448 | const processUpload = (event: any): Promise<any> => {
return new Promise((resolve, reject) => {
const fileData = event.isBase64Encoded ? event.body : Buffer.from(event.body, "base64").toString("utf-8");
if (!fileData) {
reject(new Error("No file uploaded"));
}
const fileBuffer = Buffer.from(fileData, "base64");
const file: any = {
fieldname: "file",
originalname: "upload.csv",
encoding: "base64",
mimetype: "text/csv",
buffer: fileBuffer,
size: fileBuffer.length
};
resolve(file);
});
};
I am using this to upload to a lamda function. But the returned result is empty and not the csv data | c372f2cbec246605abece101321f78fa | {
"intermediate": 0.5474750995635986,
"beginner": 0.2852420210838318,
"expert": 0.16728290915489197
} |
19,449 | make a c++ program that will detect whenever a dll is being injected | 321098bec5aff871ec5b6185ee9d1c30 | {
"intermediate": 0.43176549673080444,
"beginner": 0.12758924067020416,
"expert": 0.440645307302475
} |
19,450 | need to align normally these previously recieved images from api backend from gallery array and place them and arrange normally as in normal gallery inside that gallery html structure (you can remodify it if need and implement something differently new in concept.). the main "<canvas id='imageCanvas' class='image-canvas'></canvas>" should stay untouched at all by that gallery functions and should display only the currently recieved or requested image from that api endpoint backend. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
});
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i = 0; i < galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if (xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(document.getElementById('galleryCanvas'));
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | 6190313b8f32c8922f79fe4013b10197 | {
"intermediate": 0.3369571566581726,
"beginner": 0.41145408153533936,
"expert": 0.25158876180648804
} |
19,451 | Can you please write me a VBA code that will work with the form code below. What I want the new code to do is;
when the values have been written to AD & AE, force AF on the same row to calculate, then
check if the value in column B of the same row is the same value as that in AF of the same row.
If the values are the same then Pop up a message "Overtime hours have been recorded"
If the values are not the same pop up a critical message like this:
"Incorrect Hours recorded", line break
"Hours calculated" & column AF value, line break
"Hours Entered" & column B value, line break
"Please check your entry"
Here is the current Form code:
Private newActiveCellRange As Range
Public Property Let activeCellRange(rng As Range)
Set newActiveCellRange = rng
End Property
Public Property Get activeCellRange() As Range
Set activeCellRange = newActiveCellRange
End Property
Private Sub UserForm_Initialize()
Me.activeCellRange = ActiveCell
End Sub
Private Sub StartEndButton1_Click()
newActiveCellRange.Offset(0, 28).Value = StartTime.Value
newActiveCellRange.Offset(0, 29).Value = EndTime.Value
Me.Hide
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set activeCellRange = Target
End Sub | 962f78224c77ae73f818f00b834de799 | {
"intermediate": 0.3815702497959137,
"beginner": 0.36807671189308167,
"expert": 0.25035300850868225
} |
19,452 | Create a one dimensional integer array of size 6, int win[6], where each element of the array represents one window of the odometer. win[5] represents the right-most window and win[0] the left-most. Create six for loops one inside the other and call the indices of the loops i0 through i5, where i0 is the index of the outermost loop, and i5 the index of the innermost loop. You can use the index values to populate the array win. At each iteration win will represent a new configuration of the odometer. So, each time a new configuration is generated, print it out to the screen. | 57f2e4936c5561512560d4ddf56bba11 | {
"intermediate": 0.23392173647880554,
"beginner": 0.49405086040496826,
"expert": 0.2720273733139038
} |
19,453 | need to align normally these previously recieved images from api backend from gallery array and place them and arrange normally as in normal gallery inside that gallery html structure (you can remodify it if need and implement something differently new in concept.). the main "<canvas id='imageCanvas' class='image-canvas'></canvas>" should stay untouched at all by that gallery functions and should display only the currently recieved or requested image from that api endpoint backend. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
});
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i = 0; i < galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if (xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(document.getElementById('galleryCanvas'));
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | 682ccef3bd922aba38bb2b0d91859d72 | {
"intermediate": 0.3369571566581726,
"beginner": 0.41145408153533936,
"expert": 0.25158876180648804
} |
19,454 | need to align normally these previously recieved images from api backend from gallery array and place them and arrange normally as in normal gallery inside that gallery html structure (you can remodify it if need and implement something differently new in concept.). the main "<canvas id='imageCanvas' class='image-canvas'></canvas>" should stay untouched at all by that gallery functions and should display only the currently recieved or requested image from that api endpoint backend. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
});
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i = 0; i < galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if (xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(document.getElementById('galleryCanvas'));
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | 731c64aa8ef5eff608f2003d63a71345 | {
"intermediate": 0.3369571566581726,
"beginner": 0.41145408153533936,
"expert": 0.25158876180648804
} |
19,455 | need to align normally these previously recieved images from api backend from gallery array and place them and arrange normally as in normal gallery inside that gallery html structure (you can remodify it if need and implement something differently new in concept.). the main "<canvas id='imageCanvas' class='image-canvas'></canvas>" should stay untouched at all by that gallery functions and should display only the currently recieved or requested image from that api endpoint backend. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
});
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i = 0; i < galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if (xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(document.getElementById('galleryCanvas'));
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | e3ed52d47eeae3d450ab96f24f861661 | {
"intermediate": 0.3369571566581726,
"beginner": 0.41145408153533936,
"expert": 0.25158876180648804
} |
19,456 | need to align normally these previously recieved images from api backend from gallery array and place them and arrange normally as in normal gallery inside that gallery html structure (you can remodify it if need and implement something differently new in concept.). the main "<canvas id='imageCanvas' class='image-canvas'></canvas>" should stay untouched at all by that gallery functions and should display only the currently recieved or requested image from that api endpoint backend. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
});
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i = 0; i < galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if (xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(document.getElementById('galleryCanvas'));
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | cc67f0f9dde715ba38cb77e0d349280b | {
"intermediate": 0.3369571566581726,
"beginner": 0.41145408153533936,
"expert": 0.25158876180648804
} |
19,457 | Should I create a new DOMParser every time I wanna parse something, or can I just reuse the same one however many times I need? | 89a7f1b68f6677485b824d7b2e8bac6e | {
"intermediate": 0.7814335227012634,
"beginner": 0.10999342054128647,
"expert": 0.10857304185628891
} |
19,458 | need to align normally these previously recieved images from api backend from gallery array and place them and arrange normally as in normal gallery inside that gallery html structure (you can remodify it if need and implement something differently new in concept.). the main "<canvas id='imageCanvas' class='image-canvas'></canvas>" should stay untouched at all by that gallery functions and should display only the currently recieved or requested image from that api endpoint backend. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.modal-content {
display: flex;
flex-wrap: wrap;
}
.gallery-canvas-container {
position: relative;
width: 100%;
display:inline-grid;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
flex-grow: 1;
margin-right: 10px;
}
#galleryCanvas {
width: 100%;
height: 100%;
}
.gallery-image {
margin: 5px;
max-height: 100px;
max-width: 100px;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<button onclick='openGallery()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Open Gallery</button>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div id='galleryModal' class='modal'>
<span class='close' onclick='closeGallery()'>×</span>
<div class='modal-content'>
<div class='gallery-canvas-container'>
<canvas id='galleryCanvas' class='image-canvas'></canvas>
</div>
<div class='gallery-images-container'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const galleryArray = [];
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
let generateInterval;
let isResizing = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(() => {
generateImage();
}, timeout);
generateInterval = setInterval(() => {
generateImage();
}, interval);
}
}
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(() => {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
drawGalleryImages(imageCanvas);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGalleryImages(canvas);
isResizing = false;
});
}
function drawGalleryImages(canvas) {
const galleryImagesContainer = document.querySelector('.gallery-images-container');
galleryImagesContainer.innerHTML = ''; // Clear previous images
galleryArray.forEach((image) => {
const img = document.createElement('img');
img.src = image.src;
img.classList.add('gallery-image');
galleryImagesContainer.appendChild(img);
});
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let xPos = 0;
let yPos = 0;
for(let i = 0; i < galleryArray.length; i++) {
const image = galleryArray[i];
const aspectRatio = image.width / image.height;
let canvasWidth = canvas.width / 2;
let canvasHeight = canvas.width / (2 * aspectRatio);
if (canvasHeight > canvas.height) {
canvasHeight = canvas.height / 2;
canvasWidth = canvas.height / (2 * aspectRatio);
}
ctx.drawImage(image, xPos, yPos, canvasWidth, canvasHeight);
xPos += canvasWidth;
if (xPos >= canvas.width) {
yPos += canvasHeight;
xPos = 0;
}
}
}
function openGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'block';
drawGalleryImages(document.getElementById('galleryCanvas'));
}
function closeGallery() {
const galleryModal = document.getElementById('galleryModal');
galleryModal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
window.addEventListener('resize', handleResize);
</script>
</body>
</html> | a3a698c1a5fa707aab430ce952235c38 | {
"intermediate": 0.3369571566581726,
"beginner": 0.41145408153533936,
"expert": 0.25158876180648804
} |
19,459 | let's do a gallery kinda storage horizontal reel slider in microsized buffer of images beneath the image canvas, that will store all previously recieved images from that api backend? now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | f489039e621e88ae7311d3724523de37 | {
"intermediate": 0.37595969438552856,
"beginner": 0.36785298585891724,
"expert": 0.2561872601509094
} |
19,460 | let's do a gallery kinda storage horizontal reel slider in microsized buffer of images beneath the image canvas, that will store all previously recieved images from that api backend? now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | a16666ca3bbeb094847c608d93c2fb41 | {
"intermediate": 0.37595969438552856,
"beginner": 0.36785298585891724,
"expert": 0.2561872601509094
} |
19,461 | Ты же лучший кодер , переделай мне функцию Resolver для чита что бы она работала лучше
#include "AimbotFunctions.h"
#include "Animations.h"
#include "Resolver.h"
#include "../Logger.h"
#include "../SDK/GameEvent.h"
std::deque<Resolver::SnapShot> snapshots;
bool resolver = false;
void Resolver::reset() noexcept
{
snapshots.clear();
}
void Resolver::saveRecord(int playerIndex, float playerSimulationTime) noexcept
{
const auto entity = interfaces->entityList->getEntity(playerIndex);
const auto player = Animations::getPlayer(playerIndex);
if (!player.gotMatrix || !entity)
return;
SnapShot snapshot;
snapshot.player = player;
snapshot.playerIndex = playerIndex;
snapshot.eyePosition = localPlayer->getEyePosition();
snapshot.model = entity->getModel();
if (player.simulationTime >= playerSimulationTime - 0.001f && player.simulationTime <= playerSimulationTime + 0.001f)
{
snapshots.push_back(snapshot);
return;
}
for (int i = 0; i < static_cast<int>(player.backtrackRecords.size()); i++)
{
if (player.backtrackRecords.at(i).simulationTime >= playerSimulationTime - 0.001f && player.backtrackRecords.at(i).simulationTime <= playerSimulationTime + 0.001f)
{
snapshot.backtrackRecord = i;
snapshots.push_back(snapshot);
return;
}
}
}
void Resolver::getEvent(GameEvent* event) noexcept
{
if (!event || !localPlayer || interfaces->engine->isHLTV())
return;
switch (fnv::hashRuntime(event->getName()))
{
case fnv::hash("round_start"):
{
// Reset all
auto players = Animations::setPlayers();
if (players->empty())
break;
for (int i = 0; i < static_cast<int>(players->size()); i++)
{
players->at(i).misses = 0;
}
snapshots.clear();
break;
}
case fnv::hash("player_death"):
{
// Reset player
const auto playerId = event->getInt(("userid"));
if (playerId == localPlayer->getUserId())
break;
const auto index = interfaces->engine->getPlayerForUserID(playerId);
Animations::setPlayer(index)->misses = 0;
break;
}
case fnv::hash("player_hurt"):
{
if (snapshots.empty())
break;
if (event->getInt(("attacker")) != localPlayer->getUserId())
break;
const auto hitgroup = event->getInt("hitgroup");
if (hitgroup < HitGroup::Generic || hitgroup > HitGroup::RightLeg)
break;
snapshots.pop_front(); // Hit somebody so dont calculate
break;
}
case fnv::hash("bullet_impact"):
{
if (snapshots.empty())
break;
if (event->getInt("userid") != localPlayer->getUserId())
break;
auto& snapshot = snapshots.front();
if (!snapshot.gotImpact)
{
snapshot.time = memory->globalVars->serverTime();
snapshot.bulletImpact = Vector{ event->getFloat("x"), event->getFloat("y"), event->getFloat("z") };
snapshot.gotImpact = true;
}
break;
}
default:
break;
}
if (!resolver)
snapshots.clear();
} | df02010d1a58f0d39650be0ed8d7666c | {
"intermediate": 0.29809531569480896,
"beginner": 0.48236599564552307,
"expert": 0.21953867375850677
} |
19,462 | let’s do a gallery kinda storage horizontal reel slider in microsized buffer of images beneath the image canvas, that will store all previously recieved images from that api backend? now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.:
<head>
<title>Text2Image AI</title>
<style>
is for babies
</style>
</head>
<body>
<div class=‘container’>
<div class=‘control-container’>
<div class=‘input-field-container’>
<h1 class=‘title’ style=‘margin-left: 10px;margin-right: 10px;margin-top: 10px;’>T2I AI UI</h1>
<input id=‘inputText’ type=‘text’ value=‘armoured girl riding an armored cock’ class=‘input-field’ style=‘flex: 1;margin-top: -6px;’>
<div class=‘gen-button-container’>
<button onclick=‘generateImage()’ class=‘gen-button’ style=‘border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;’>Gen Img</button>
</div>
</div>
</div>
<div class=‘independent-container’>
<label for=‘autoQueueCheckbox’ style=‘margin-left: 10px;margin-right: 5px;’>Auto Queue:</label>
<input type=‘checkbox’ id=‘autoQueueCheckbox’ onchange=‘autoQueueChanged()’>
<label for=‘numAttemptsInput’ style=‘margin-left: 10px;margin-right: 5px;’>Retry Attempts:</label>
<input type=‘number’ id=‘numAttemptsInput’ value=‘50’ min=‘2’ max=‘1000’ style=‘width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;’>
<label for=‘intervalInput’ style=‘margin-left: 10px;margin-right: 5px;’>Interval (sec):</label>
<input type=‘number’ id=‘intervalInput’ value=‘25’ min=‘1’ max=‘300’ style=‘width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;’>
<label for=‘timeoutInput’ style=‘margin-left: 10px;margin-right: 5px;’>Timeout (sec):</label>
<input type=‘number’ id=‘timeoutInput’ value=‘120’ min=‘12’ max=‘600’ style=‘width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;’>
</div>
<div class=‘canvas-container’>
<canvas id=‘imageCanvas’ class=‘image-canvas’></canvas>
<div class=‘progress-bar’>
<div class=‘progress-bar-filled’></div>
</div>
</div>
<script>
const modelUrl = ‘https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited’;
const modelToken = ‘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’;
const progressBarFilled = document.querySelector(‘.progress-bar-filled’);
const imageCanvas = document.getElementById(‘imageCanvas’);
const ctx = imageCanvas.getContext(‘2d’);
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: ‘POST’,
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get(‘estimated_time’);
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById(‘autoQueueCheckbox’).checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById(‘timeoutInput’).value) * 1000;
const interval = parseInt(document.getElementById(‘intervalInput’).value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById(‘inputText’).value;
const numAttempts = parseInt(document.getElementById(‘numAttemptsInput’).value);
progressBarFilled.style.width = ‘0%’;
progressBarFilled.style.backgroundColor = ‘green’;
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + ‘%’;
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById(‘imageCanvas’);
const ctx = canvas.getContext(‘2d’);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = ‘100%’;
progressBarFilled.style.backgroundColor = ‘darkmagenta’;
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById(‘autoQueueCheckbox’).checked;
}
progressBarFilled.style.width = ‘100%’;
progressBarFilled.style.height = ‘2px’;
progressBarFilled.style.backgroundColor = ‘green’;
isGenerating = false;
}
window.addEventListener(‘resize’, handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector(‘.canvas-container’);
const canvas = document.getElementById(‘imageCanvas’);
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener(‘DOMContentLoaded’, function() {
handleResize();
generateImage();
});
</script>
</body>
</html>
To achieve a gallery-like storage horizontal reel slider in a microsized buffer of images beneath the image canvas, you need to modify the following parts of the code:
1. Add a new container below the image canvas to hold the buffer of images:
<div class=“buffer-container”></div>
2. Add the styling for the buffer container:
.buffer-container {
display: flex;
overflow-x: scroll;
margin-top: 10px;
}
.buffer-container::-webkit-scrollbar {
width: 10px;
}
.buffer-container::-webkit-scrollbar-thumb {
background-color: darkmagenta;
border-radius: 5px;
}
.buffer-container::-webkit-scrollbar-track {
background-color: midnightblue;
}
3. Modify the generateImage() function to store the received image in the buffer container:
async function generateImage() {
// Rest of the code…
const img = new Image();
img.onload = function() {
galleryArray.push(img);
// Add the image to the buffer container
const bufferContainer = document.querySelector(‘.buffer-container’);
bufferContainer.appendChild(img);
// Rest of the code…
};
// Rest of the code…
}
4. Modify the handleResize() function to resize and reposition the images in the buffer container:
function handleResize() {
// Rest of the code…
// Resize and reposition the images in the buffer container
const bufferContainer = document.querySelector(‘.buffer-container’);
bufferContainer.style.width = ${canvasWidth}px;
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = ${canvasImageWidth}px;
image.style.height = ${canvasImageHeight}px;
});
// Rest of the code…
}
That’s it! With these modifications, you should have a gallery-like storage horizontal reel slider in the microsized buffer of images beneath the image canvas.
output that fully implemented “handleResize” function.
Certainly! Here’s the fully implemented handleResize() function with the modifications for the buffer container:
anazlyze indentation problems and errors before output! | cff2ad1345743432bc1305546caa01b6 | {
"intermediate": 0.3108518719673157,
"beginner": 0.4788986146450043,
"expert": 0.21024948358535767
} |
19,463 | Can you explain to me how a program like dragonbones works? | 08c3832e712ab423865edb8b74bde5ed | {
"intermediate": 0.30690181255340576,
"beginner": 0.1885722279548645,
"expert": 0.5045259594917297
} |
19,464 | now need to align that buffer container normally on full width but with fixed height for gallery reel-like preview under the main imagecanvas element. the images that appears and stores in that buffercontainer should be auto-fitted inside in and align horizontal manner arrangement. I think that need to make an independent style for actual image appearing inside that buffer container to be able to auto-fit inside in proper thumbnail dimension but at the same time should be in original quality. also, it will be cool to make a click on image and fit it on full window (not full screen) and then simply close it with left click again. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:6px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.progress-bar {
position: relative;
width: calc(100% - 100px);
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
background-color: black;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;
}
.buffer-container {
display: flex;
overflow-x: scroll;
margin-top: 10px;
width:100%;
height: 20px;
}
.buffer-container::-webkit-scrollbar {
width: 10px;
}
.buffer-container::-webkit-scrollbar-thumb {
background-color: darkmagenta;
border-radius: 5px;
}
.buffer-container::-webkit-scrollbar-track {
background-color: midnightblue;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border:1px solid darkmagenta;
border-radius:6px;'>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
</div>
<div class='buffer-container'></div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.onload = function() {
galleryArray.push(img);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.backgroundColor = 'darkmagenta';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
progressBarFilled.style.width = '100%';
progressBarFilled.style.height = '2px';
progressBarFilled.style.backgroundColor = 'green';
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 846dd5e2df315c08594333bc37b5a476 | {
"intermediate": 0.3221522271633148,
"beginner": 0.37677431106567383,
"expert": 0.30107346177101135
} |
19,465 | I want a VBA code that will do the following:
If Today is Mon copy sheet PA A3:P3 to Sheet Daily A3:P3
If Today is Tue copy sheet PA A4:P4 to Sheet Daily A3:P3
If Today is Wed copy sheet PA A5:P5 to Sheet Daily A3:P3
If Today is Thu copy sheet PA A6:P6 to Sheet Daily A3:P3
If Today is Fri copy sheet PA A7:P7 to Sheet Daily A3:P3
Copy must include cell format. | 6e3522c4ce0890f37fb4260490536fe2 | {
"intermediate": 0.36434128880500793,
"beginner": 0.2954643964767456,
"expert": 0.3401942849159241
} |
19,466 | fullWindowDiv.style.zindex = '2'; | 5aef730f34fd19693f4205fdb27de3ea | {
"intermediate": 0.35274234414100647,
"beginner": 0.29291465878486633,
"expert": 0.3543430268764496
} |
19,467 | read the folowing code and find whats worng (<script type="text/javascript" src="https://udbaa.com/bnr.php?section=General&pub=321278&format=300x250&ga=g"></script>
<noscript><a href="https://yllix.com/publishers/321278" target="_blank"><img src="//ylx-aff.advertica-cdn.com/pub/300x250.png" style="border:none;margin:0;padding:0;vertical-align:baseline;" alt="ylliX - Online Advertising Network" /></a></noscript>) | fe2dac8775a7aab49715f6945b68966e | {
"intermediate": 0.37638434767723083,
"beginner": 0.4070115387439728,
"expert": 0.2166040539741516
} |
19,468 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. now show only these parts in code that I need to modify in order to achieve suitable performance and functionalities.: const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
}); | 8d79dcf2402dd94ea42ea74144dc90e3 | {
"intermediate": 0.39242619276046753,
"beginner": 0.38605400919914246,
"expert": 0.2215198427438736
} |
19,469 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update, but it should not endlessly circulate while auto-queue is unchecked now output full modified javascript code, and also fix handling resize function to handle progressbar resize as well as "image-preview" to fit within "buffer-container on resize.: const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
}); | 77be7a63d6a70ca418903588b837d19b | {
"intermediate": 0.3881061375141144,
"beginner": 0.38379406929016113,
"expert": 0.2280997931957245
} |
19,470 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output full modified javascript code, and also fix handling resize function to handle progressbar resize as well as "image-preview" to fit within "buffer-container on resize.: <html>
<head>
<title>Text2Image AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 5a626083e26e70aa596cd024f61e99bc | {
"intermediate": 0.41074055433273315,
"beginner": 0.42190074920654297,
"expert": 0.16735874116420746
} |
19,471 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as "image-preview" to fit within "buffer-container on resize.: <html>
<head>
<title>Text2Image AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 560578e6babb1c7b067b03c0dea8383d | {
"intermediate": 0.38946622610092163,
"beginner": 0.446195125579834,
"expert": 0.16433864831924438
} |
19,472 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as "image-preview" to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 5f524b740fcd63c12d94ed06ce080423 | {
"intermediate": 0.43690308928489685,
"beginner": 0.4169846773147583,
"expert": 0.1461123377084732
} |
19,473 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as "image-preview" to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 100);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
// Update progress bar
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
};
img.src = url;
clearInterval(interval);
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 6685174279a2cc54d66f8076bfeb26fb | {
"intermediate": 0.4083418846130371,
"beginner": 0.4618588984012604,
"expert": 0.12979929149150848
} |
19,474 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as "image-preview" to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 100);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
// Update progress bar
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
};
img.src = url;
clearInterval(interval);
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 84d893a9c4b9a4f7fc654503e21df1c5 | {
"intermediate": 0.4083418846130371,
"beginner": 0.4618588984012604,
"expert": 0.12979929149150848
} |
19,475 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when “progressBarFilled.style.background” easingly smoothly filling through the right size? like: we are showing some text “Loading…” at the center of progress bar when it’s in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as “image-preview” to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 51d1b6082a4b25500e5ada7b03d0047b | {
"intermediate": 0.47950032353401184,
"beginner": 0.390058308839798,
"expert": 0.1304413378238678
} |
19,476 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when “progressBarFilled.style.background” easingly smoothly filling through the right size? like: we are showing some text “Loading…” at the center of progress bar when it’s in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as “image-preview” to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | a3e734c2f42c2f04b8918bb6af461852 | {
"intermediate": 0.47950032353401184,
"beginner": 0.390058308839798,
"expert": 0.1304413378238678
} |
19,477 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when “progressBarFilled.style.background” easingly smoothly filling through the right size? like: we are showing some text “Loading…” at the center of progress bar when it’s in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as “image-preview” to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 687c5f2ddfd6bfc5acaec9e1226e3032 | {
"intermediate": 0.47950032353401184,
"beginner": 0.390058308839798,
"expert": 0.1304413378238678
} |
19,478 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when “progressBarFilled.style.background” easingly smoothly filling through the right size? like: we are showing some text “Loading…” at the center of progress bar when it’s in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar resize as well as “image-preview” to fit within "buffer-container on resize.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
document.body.removeChild(fullWindowImg);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | a96e9c4170efd8905e00bb44100790ab | {
"intermediate": 0.47950032353401184,
"beginner": 0.390058308839798,
"expert": 0.1304413378238678
} |
19,479 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 332cf73eea4ebad657b13f8eb6e85010 | {
"intermediate": 0.4030350148677826,
"beginner": 0.4530407190322876,
"expert": 0.1439242959022522
} |
19,480 | You need code in C#. So that the code changes the screen resolution.
I want to make a button on WPF that will change screen resolutions | 8f3a0204d3e5e46c73286ddb4ea15f3c | {
"intermediate": 0.39823174476623535,
"beginner": 0.33228930830955505,
"expert": 0.2694789171218872
} |
19,481 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click. ((this is just stupid. there’s no any “estimated_time” in headers need. everything could be done purely on previous recorded evaluation, timeout, estimations etc… it all can be done inside the code by not relying on external sources or something, fucking stupid.)). also, recombine and optimize code to save lines of actual javascript code.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | dac455060365e582f5a2b2d857e91e62 | {
"intermediate": 0.4050672650337219,
"beginner": 0.4302125573158264,
"expert": 0.16472019255161285
} |
19,482 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click. ((this is just stupid. there’s no any “estimated_time” in headers need. everything could be done purely on previous recorded evaluation, timeout, estimations etc… it all can be done inside the code by not relying on external sources or something, fucking stupid.)). also, recombine and optimize code to save lines of actual javascript code.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 5b26fbe913dbddb0ffbe147ae6299e9a | {
"intermediate": 0.4050672650337219,
"beginner": 0.4302125573158264,
"expert": 0.16472019255161285
} |
19,483 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click. ((this is just stupid. there’s no any “estimated_time” in headers need. everything could be done purely on previous recorded evaluation, timeout, estimations etc… it all can be done inside the code by not relying on external sources or something, fucking stupid.)). also, recombine and optimize code to save lines of actual javascript code.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | cfa34e974378f51918e988df2ab35eb6 | {
"intermediate": 0.4050672650337219,
"beginner": 0.4302125573158264,
"expert": 0.16472019255161285
} |
19,484 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click. ((this is just stupid. there’s no any “estimated_time” in headers need. everything could be done purely on previous recorded evaluation, timeout, estimations etc… it all can be done inside the code by not relying on external sources or something, fucking stupid.)). also, recombine and optimize code to save lines of actual javascript code.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | b8b08b5ce6c07da1b63ad7bcb30c3ed7 | {
"intermediate": 0.4050672650337219,
"beginner": 0.4302125573158264,
"expert": 0.16472019255161285
} |
19,485 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click. ((this is just stupid. there’s no any “estimated_time” in headers need. everything could be done purely on previous recorded evaluation, timeout, estimations etc… it all can be done inside the code by not relying on external sources or something, fucking stupid.)). also, recombine and optimize code to save lines of actual javascript code.: <html>
<head>
<title>AI</title>
<style>
...
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' >T2I AI UI</h1>
<input id='inputText' type='text' value='text' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' >Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' >
<label for='intervalInput' >Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300'>
<label for='timeoutInput'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | 6323a1cf9b6224e1267fa723a1999ea4 | {
"intermediate": 0.4050672650337219,
"beginner": 0.4302125573158264,
"expert": 0.16472019255161285
} |
19,486 | is there a way to estimate an initial response from api backend (text2image AI model) when we get an image and use it in progressbar evaluation for further estimation and smooth progressing animation effect when "progressBarFilled.style.background" easingly smoothly filling through the right size? like: we are showing some text "Loading..." at the center of progress bar when it's in estimation and evaluation mode of predicting the next hypothetical image load from API backend. so, the progress bar should predict and expand within appropriate value set for the next hypothetical load based on time passed in the previous estimation. also, need need to consider the fact that we have a manual update button, so when auto-queue is pressed it should perform this estimation and keep value for manual update as well, but it should not endlessly circulate while auto-queue is unchecked now output only full modified javascript code, and also fix handling resize function to handle progressbar on window resize resize as well as "image-preview" to fit within "buffer-container on resize as well as closing of image curtain preview on click. ((this is just stupid. there’s no any “estimated_time” in headers need. everything could be done purely on previous recorded evaluation, timeout, estimations etc… it all can be done inside the code by not relying on external sources or something, fucking stupid.)). also, recombine and optimize code to save lines of actual javascript code.: const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
}); | 0cc5e9d23e10600609b677ab7a9c0618 | {
"intermediate": 0.27501198649406433,
"beginner": 0.4163103699684143,
"expert": 0.3086775541305542
} |
19,487 | Is there a way to estimate the response time of an API backend (using a text-to-image AI model) for a given image? This estimation will be used to create a smooth progressing animation effect for a progress bar. The progress bar should fill gradually and predictively based on previous evaluation times. Additionally, we need to handle manual updates and prevent endless cycling when the auto-queue is unchecked. The code provided fetches the model, generates images, handles resizing, and enables the closing of image curtain previews. We need to optimize and recombine the code, ensuring accurate estimations and smooth functionality for the progress bar and image resizing. now output only full modified javascript code.: const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
}); | 7bd82089e1f034c4799b016e162c36ca | {
"intermediate": 0.38167962431907654,
"beginner": 0.403634637594223,
"expert": 0.21468576788902283
} |
19,488 | create table employee(id int identity, name varchar(10), salary int, departmentid int)
insert into employee values
('r',301,3),('x',302,3),('y',303,3),('t',302,3),
('a',100,1),('b',101,1),('c',102,1),('d',103,1),
('f',200,2),('j',201,2),('h',202,2),('i',203,2),
('k',300,3),('m',301,3),('n',302,3),('k',303,3)
select name, salary, departmentid from employee order by departmentid, salary desc
--Q: Find employees who get second highest salary in each department using row_number,dense_rank and rank which one is the easiest way to get answer on tsql | d73b09f65001c327d94531eb7fdeec96 | {
"intermediate": 0.474465548992157,
"beginner": 0.1399192214012146,
"expert": 0.3856152594089508
} |
19,489 | need to align and auto-resize that image or image-preview thumbnail appearing inside buffercontainer to be auto-fitted within it and not being restored to original size on window resizings or viewport. also need to fix that closing of image preview, because you need to press multiple times to close it. show only these parts in code to add or modify.: <html>
<head>
<title>Text2Image AI</title>
<style>
html, body {
margin: 0;
padding: 0;
background-color:midnightblue;
color:white;
}
.title{
background: radial-gradient(circle at top center, #929, #519);
color: brightblue;
border-radius: 2px;
padding: 2px;
font-size: var(–font-size, 22px);
font-family: var(–font-family, monospace);
font-weight: var(–font-weight, bold);
-webkit-text-stroke: 1px darkmagenta;
text-stroke: 1px darkmagenta;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: top;
min-height: 0;
}
.control-container {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
margin: 0;
}
.input-field-container {
position: absolute;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
}
.input-field {
display:flex;
width: 100%;
height: 32px;
box-sizing: border-box;
background-color:#010130;
color:#aa50ff;
border:1px solid darkmagenta;
border-radius:2px;
padding:5px;
align-items: center;
justify-content: center;
font-size: var(--font-size, 16px);
font-family: var(--font-family, monospace);
font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
}
.gen-button-container {
position: relative;
}
.gen-button {
margin: 0;
background: radial-gradient(circle at top center, #929, #519);
color: white;
border-radius: 6px;
padding: 2px;
font-size: var(--font-size, 16px);
--font-family: var(--font-family, monospace);
--font-weight: var(--font-weight, bold);
-webkit-text-stroke: 1px rgba(139, 0, 139, 0.5);
text-stroke: 1px rgba(139, 0, 139, 1);
text-shadow: 0px 0px 0.1px rgba(255, 255, 255, 1);
}
.image-canvas {
display: flex;
align-items: center;
position: relative;
width: 100%;
background: linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to right, darkmagenta 1px, transparent 1px) 0 100%,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 0 0,
linear-gradient(to top, darkmagenta 1px, transparent 1px) 100% 0;
background-size: 25% 100%, 25% 200px, 100% 25%, 100% 25%;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-position: top left, bottom left, top left, top right;
background-color: #010130;
border-style: double dashed;
border-width: 2px;
border-color: darkmagenta;
z-index: 1;
}
.image-canvas:before {
content: '';
position: relative;
top: 2px;
left: 2px;
width: calc(100% - 4px);
height: calc(100% - 4px);
background-color: #010130;
z-index: -1;
}
.canvas-container {
position: relative;
width: 100%;
max-width: 100vh;
height: calc(5px / 0vh);
max-height: calc(5px / 0vh);
margin: 0 auto;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
z-index: 2;
}
.progress-bar {
margin-top: 0px;
margin-bottom: 5px;
position: relative;
width:100%;
height: 10px;
display: flex;
border-bottom:1px inset darkmagenta;
border-radius:2px;
align-items: center;
justify-content: center;
background-color: #010130;
}
.progress-bar-filled {
width: 0%;
height: 10px;
background-color: green;
}
.independent-container {
width: 100%;
position:relative;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
margin-top: 60px;
background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:1px;
}
.buffer-container {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: flex-start;
align-items: center;
overflow-x: scroll;
margin-top: 10px;
width:100%;
height: 50px;
background-color:#010130;
object-fit: scale-down;
}
.image-preview {
position:relative;
display:flex;
width: 50px;
height: 50px;
object-fit: scale-down;
margin: auto;
}
.buffer-container::-webkit-scrollbar {
width: 10px;
}
.buffer-container::-webkit-scrollbar-thumb {
background-color: darkmagenta;
border-radius: 5px;
}
.buffer-container::-webkit-scrollbar-track {
background-color: midnightblue;
}
</style>
</head>
<body>
<div class='container'>
<div class='control-container'>
<div class='input-field-container'>
<h1 class='title' style='margin-left: 10px;margin-right: 10px;margin-top: 10px;'>T2I AI UI</h1>
<input id='inputText' type='text' value='armoured girl riding an armored cock' class='input-field' style='flex: 1;margin-top: -6px;'>
<div class='gen-button-container'>
<button onclick='generateImage()' class='gen-button' style='border-style:none;height: 32px;margin-left: 10px;margin-right: 10px;margin-top: -6px;'>Gen Img</button>
</div>
</div>
</div>
<div class='independent-container'>
<label for='autoQueueCheckbox' style='margin-left: 10px;margin-right: 5px;'>Auto Queue:</label>
<input type='checkbox' id='autoQueueCheckbox' onchange='autoQueueChanged()'>
<label for='numAttemptsInput' style='margin-left: 10px;margin-right: 5px;'>Retry Attempts:</label>
<input type='number' id='numAttemptsInput' value='50' min='2' max='1000' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
<label for='intervalInput' style='margin-left: 10px;margin-right: 5px;'>Interval (sec):</label>
<input type='number' id='intervalInput' value='25' min='1' max='300' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
<label for='timeoutInput' style='margin-left: 10px;margin-right: 5px;'>Timeout (sec):</label>
<input type='number' id='timeoutInput' value='120' min='12' max='600' style='width: 64px;height: 16px; background-color:#010130;
color:#aabbee;
border-top:1px solid darkmagenta;
border-radius:6px;'>
</div>
<div class='progress-bar'>
<div class='progress-bar-filled'></div>
</div>
<div class='canvas-container'>
<canvas id='imageCanvas' class='image-canvas'></canvas>
<div class='buffer-container'></div>
</div>
<script>
const modelUrl = 'https://api-inference.huggingface.co/models/hogiahien/counterfeit-v30-edited';
const modelToken = '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';
const progressBarFilled = document.querySelector('.progress-bar-filled');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let estimatedTime = 0;
let isGenerating = false;
async function query(data) {
const response = await fetch(modelUrl, {
headers: {
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: JSON.stringify(data)
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
const result = await response.blob();
return result;
}
let generateInterval;
function autoQueueChanged() {
clearInterval(generateInterval);
const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
if (autoQueueActive) {
const timeout = parseInt(document.getElementById('timeoutInput').value) * 1000;
const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
setTimeout(function() {
generateImage();
}, timeout);
generateInterval = setInterval(function() {
generateImage();
}, interval);
}
}
const galleryArray = [];
async function generateImage() {
if (isGenerating) {
return;
}
isGenerating = true;
const inputText = document.getElementById('inputText').value;
const numAttempts = parseInt(document.getElementById('numAttemptsInput').value);
progressBarFilled.style.width = '0%';
progressBarFilled.style.backgroundColor = 'green';
await new Promise(resolve => setTimeout(resolve, 1000));
let retryAttempts = 0;
const maxRetryAttempts = numAttempts;
let autoQueueActive = false;
while (retryAttempts < maxRetryAttempts) {
try {
const startTime = Date.now();
const timeLeft = Math.floor(estimatedTime / 1000);
const interval = setInterval(function () {
if (isGenerating) {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
const progress = Math.floor((elapsedTime / timeLeft) * 1000);
progressBarFilled.style.width = progress + '%';
}
}, 1000);
const cacheBuster = new Date().getTime();
const response = await query({ inputs: inputText, cacheBuster });
const url = URL.createObjectURL(response);
const bufferContainer = document.querySelector('.buffer-container');
bufferContainer.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'IMG') {
const fullWindowDiv = document.createElement('div');
const fullWindowImg = document.createElement('img');
fullWindowDiv.style.position = 'fixed';
fullWindowDiv.style.top = '0';
fullWindowDiv.style.left = '0';
fullWindowDiv.style.width = '100%';
fullWindowDiv.style.height = '100%';
fullWindowDiv.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
fullWindowDiv.style.display = 'flex';
fullWindowDiv.style.zIndex = '2';
fullWindowDiv.style.justifyContent = 'center';
fullWindowDiv.style.alignItems = 'center';
fullWindowImg.style.maxHeight = '90vh';
fullWindowImg.style.maxWidth = '90vw';
fullWindowImg.src = target.src;
fullWindowDiv.appendChild(fullWindowImg);
document.body.appendChild(fullWindowDiv);
fullWindowDiv.addEventListener('click', function() {
document.body.removeChild(fullWindowDiv);
});
}
});
let img = new Image();
img.classList.add('image-preview');
img.src = url;
img.onload = function() {
galleryArray.push(img);
bufferContainer.appendChild(img);
const imageWidth = img.naturalWidth;
const imageHeight = img.naturalHeight;
const aspectRatio = img.width / img.height;
const containerWidth = imageCanvas.parentElement.clientWidth; // Get the width of the container
const containerHeight = imageCanvas.parentElement.clientHeight; // Get the height of the container
const minAvailableWidth = containerWidth;
const maxAvailableHeight = containerHeight;
let canvasWidth = containerWidth;
let canvasHeight = maxAvailableHeight;
if (aspectRatio > 1) {
// Landscape image, fit width
canvasWidth = containerWidth;
canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > maxAvailableHeight) {
canvasHeight = maxAvailableHeight;
canvasWidth = canvasHeight * aspectRatio;
}
} else {
// Portrait or square image, fit height
canvasWidth = maxAvailableHeight * aspectRatio;
canvasHeight = maxAvailableHeight;
if (canvasWidth > containerWidth) {
canvasWidth = containerWidth;
canvasHeight = canvasWidth / aspectRatio;
}
}
imageCanvas.width = canvasWidth;
imageCanvas.height = canvasHeight;
// Clear canvas before starting the animation loop
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each image in the gallery array
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
galleryArray.push(img);
};
img.src = url;
clearInterval(interval);
progressBarFilled.style.width = '100%';
progressBarFilled.style.background = 'linear-gradient(to bottom right, rgba(39, 0, 39, 0.5), rgb(155, 0, 155))';
break;
} catch (error) {
console.error(error);
retryAttempts++;
}
if (autoQueueActive) {
const timeout = estimatedTime + 2000;
await new Promise(resolve => setTimeout(resolve, timeout));
}
autoQueueActive = document.getElementById('autoQueueCheckbox').checked;
}
isGenerating = false;
}
window.addEventListener('resize', handleResize);
let isResizing = false;
function handleResize() {
if (isResizing) return;
isResizing = true;
requestAnimationFrame(() => {
handleResize();
generateImage();
const container = document.querySelector('.canvas-container');
const canvas = document.getElementById('imageCanvas');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const aspectRatio = canvas.width / canvas.height;
let canvasWidth = containerWidth;
let canvasHeight = containerWidth / aspectRatio;
if (canvasHeight > containerHeight) {
canvasHeight = containerHeight;
canvasWidth = canvasHeight * aspectRatio;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var bufferContainer = document.querySelector('.buffer-container');
bufferContainer.style.width = '' + canvasWidth + 'px';
galleryArray.forEach(function(image) {
var imageWidth = image.naturalWidth;
var imageHeight = image.naturalHeight;
var aspectRatio = imageWidth / imageHeight;
var canvasImageWidth = canvasWidth;
var canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
image.style.width = '' + canvasImageWidth + 'px';
image.style.height = '' + canvasImageHeight + 'px';
});
galleryArray.forEach((image) => {
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const aspectRatio = imageWidth / imageHeight;
let canvasImageWidth = canvasWidth;
let canvasImageHeight = canvasWidth / aspectRatio;
if (canvasImageHeight > canvasHeight) {
canvasImageHeight = canvasHeight;
canvasImageWidth = canvasHeight * aspectRatio;
}
const x = (canvas.width - canvasImageWidth) / 2;
const y = (canvas.height - canvasImageHeight) / 2;
ctx.drawImage(image, x, y, canvasImageWidth, canvasImageHeight);
});
isResizing = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
handleResize();
generateImage();
});
</script>
</body>
</html> | ca415b6cde629bcc0488fe66b697a370 | {
"intermediate": 0.3707606792449951,
"beginner": 0.36994484066963196,
"expert": 0.2592945098876953
} |
19,490 | C#datagridview设置背景透明 | 276147a028a3093fc64410eb18aa98be | {
"intermediate": 0.45869961380958557,
"beginner": 0.24580465257167816,
"expert": 0.2954957187175751
} |
19,491 | Write a Java program where it contains the following:
A class to define a kind of objects in our daily life (i.e. cars, chairs)
A main class (main program) to create an instance of your class and prints the results of all the methods of your class except the setters
Basic Requirement:
An executable program with all the classes in a single file
No inner classes (e.g. a class declared in the main class)
Explicitly define 1 constructor to the class
Define 3 to 5 variables to the class
Define a getter and a setter per each variable, and 1 to 2 methods for some other behavior to the class (e.g. a class with 3 variables should have 3 x 2 + 1 = 7 methods at least, except the constructor)
All the variables must be initialized with a value within the constructor (i.e. do not just left Java assign the default value a variable)
Example input & Output:
A circle class has 3 variables: x, y and radius
3 getters, 3 setters and 2 methods, getArea() and contains(), are defined | 3ff92b9e4cbced123bc17fcb7f1c18c1 | {
"intermediate": 0.11047833412885666,
"beginner": 0.8252150416374207,
"expert": 0.06430662423372269
} |
19,492 | на каком языке программирования написана эта программа:
/*программа управления холодильником */
start: do;
$include(reg812.dcl)
/* объявление основных переменных и флагов */
(t_1,t_2) word, /*температура в камерах установленная*/
(tr_1,tr_2) word, /* измеряемая температура */
ind(4) byte,
(i,j,nreg) byte, /* переменные для работы */
(flag, fl_razm,fl_moroz) byte, /*флаги определения режима работы */
ok byte, /*номера нажатой и пред клавиш */
adc_H,adc_L byte,_p word,
nind byte, /*номер отображаемого индикатора*/
per_t0 word; /*число циклов переполнения таймера0*/
adc:procedure interrupt 6; /*считываем данные с АЦП*/
adccon2=0;
adc_h=adcdatah;
adc_l=adcdatal;=1;eadc=1; adc;
/*____Обработчик прерывания таймера____*/
timer_int: procedure interrupt 1; /* прерывание t0 */
/*установка сканируемого столбца*/nind=0 then P2=00010000b or ind(nind);nind=1 then P2=00100000b or ind(nind);nind=2 then P2=01000000b or ind(nind);nind=3 then P2=10000000b or ind(nind);=nind+1; if nind=4 then nind=0;
/*определение нажатых клавиш и реакции по ним*/
if (p3.4=0b) and (ok<>1) then /*приращение установленной температуры*/
do;ok=1;nreg=0 then do;_1=t_1-1;if t_10<0 then t_1=0;(0)=t_1/10;ind(1)=t_1 mod 10;;nreg=1 then do;_2=t_2+1;if t_2>10 then t_2=10;(2)=t_2/10;ind(3)=t_2 mod 10;;
end;
if (p3.5=0b) and (ok<>2) then /*уменьшение установленной температуры*/
do;ok=2;nreg=0 then do;_1=t_1+1;if t_1>22 then t_1=22;(0)=t_1/10;ind(1)=t_1 mod 10;;nreg=1 then do;_2=t_2-1;if t_2<3 then t_2=3;(2)=t_2/10;ind(3)=t_2 mod 10;;
end;
if (p3.6=0b) and (ok<>3) then/*переключение режимов по кругу */
do; ok=3; nreg=nreg+1;if nreg>=4 then nreg=0;;
if (P3 and 01110000b)=70h then ok=0; /*проверка на отпускание клавиш */
if per_t0>960 then do; /*если прошла мин увеличен счетчик*/
per_t0=0;tim_ptim_p+1; nreg<2 then do;/*включение периодической разморозки*/
if (fl_razm=0)and(tim_p>4320) then do;fl_razm=1;tim_p=0;end; /*24ч*/(fl_razm=1)and(tim_p>180) then do;fl_razm=0; tim_p=0;end; /*2ч*/;nreg=2 then do;(fl_moroz=1)and(tim_p>240) then do;fl_moroz=0;tim_p=0;nreg=0;end; /*3ч*/;
do; /*ежеминутное обновление показаний температуры*/
ind(0)=tr_1/10;ind(1)=tr_1 mod 10;(2)=tr_2/10;ind(3)=tr_2 mod 10; tr_1<>0 then P3.0=0;/*зажигаем минус на индикаторе температуры морозилки*/
end;
end;_t0=per_t0+1; /* увеличиваем счетчик переполнений */
tf0=0; /* сброс флага переполнения */
end timer_int;
init: procedure; /******пpоцедуpа инициализации******/
tmod=00000001b;/*пеpвый pежим для таймеpа */=1;/*пpеpывание по фpонту сигнала пеpеполнения*/,tl0=0;tr0=1; /*обнул счетчики и pазpешаем pаботу 0-го Таймеpa*/=1;/*запускаем таймеp 0 */=1; /*pазpешаем пpеpывания Таймера=0 */
ea=1;/*pазpешаем все пpеpывания*/
/*Инициализация АЦП*/
ADCCON1=60h;/*настраиваем режим AЦП*/
ADCCON2=0h;/*настраиваем канал 0*/
nreg=0;fl_moroz=0;fl_razm=0;ok=0;
/*устаналиваем значения по умолчанию*/
t_1=6;t_2=6;
p3=01111011;/*линии 4-6 на ввод и включаем компрессоры на холод*/
end init;
/*____основнaя программа _____*/init;
/******Исполнительный блок программы******/
do while 1; /*основной цикл работы холодильника*/
chan=0; sconv=1; flag=0;while flag=0; end;/*измеряем температуру t1*/_1=22-(adc_h*255+adc_l)*50/4096;/* перевод результатов АЦП в температуру*/
chan=1; sconv=1; flag=0;while flag=0; end;/*измеряем температуру t2*/_2=((adc_h and 0fh)*255+adc_l)*50/4096;/*перевод результатов АЦП в температуру*/
if nreg=2 then do; fl_moroz=1;time_p=0;end;(nreg<2)and(tr_1>t_1+1) THEN p3.1=1;(nreg<2)and(tr_2>t_2+1) THEN p3.3=1;(nreg<2)and(tr_1<t_1-2) THEN p3.1=0;(nreg<2)and(tr_2<t_2-2) THEN p3.3=0;(fl_razm=1)and(tr_1>-1) then p3.1=0;nreg=3 then do p3.1=0;p3.3=0;end;/*полная разморозка*/(nreg=2)and(tr_1<22) THEN p3.1=1;/*быстрая заморозка*/(nreg=2)and(tr_1=22) THEN p3.1=0;/*;
end start; | 482ffdb88b9141cea45cd022900f2e45 | {
"intermediate": 0.3147995173931122,
"beginner": 0.45305436849594116,
"expert": 0.23214605450630188
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.