file_load.onsubmit = function(){ var file = this.elements.myfile.files[0]; var xhr = new XMLHttpRequest(); xhr.open("POST", "upload", true); xhr.send(file); return false; }
const server = require('http').createServer();
const fs = require('fs');
const nodeStatic = require('node-static');
const file = new nodeStatic.Server('.', {
cache: 0
});
server.listen(3000, () => console.log("сервер запущен"));
server.on('request', (req, res) => {
if (req.url == '/upload') {
req.pipe(
fs.createWriteStream('file2.jpg')
).on('finish', () => res.end('ok'));
return;
}
file.serve(req, res);
});
function setRandomInterval(cb, minDelay, maxDelay, ...args) {
let timeoutID;
(function next() {
const delay = Math.floor(Math.random() * (maxDelay - minDelay) + minDelay);
timeoutID = setTimeout(() => {
cb(...args);
next();
}, delay);
})();
return function cancel() {
clearTimeout(timeoutID);
};
}
// использование:
setRandomInterval(func, 500, 2500); // просто запускаем с интервалом от 0.5с до 2.5с
const cancelInteraval = setRandomInterval(() => {
console.log('it work');
if(Math.random() > 0.7) {
cancelInteraval(); // таймаут можно отменить если вызвать возвращенную функцию
}
}, 200, 500);
setRandomInterval((arg1, arg2, arg3) => {
console.log(arg1, arg2, arg3);
}, 1000, 3000, 'arg1', 'arg2', 'arg3'); // подобно setTimeout и setInterval можно передать аргументы в колбэк
parent.querySelectorAll('.gallery-uploads-imgs__item').forEach(element => {
var img = new Image;
img.src = element.dataset.src
document.body.append(img)
let canvas = document.createElement('canvas')
let context = canvas.getContext('2d');
canvas.width = img.clientWidth
canvas.height = img.clientHeight
img.onload = function() {
context.drawImage(img, 0,0);
img.remove();
canvas.toBlob(function(blob) {
let uploadImageUrl = URL.createObjectURL(blob);
data.blobs.push( uploadImageUrl )
}, 'image/png');
}
})
И вообще какие еще варианты могут быть решения этой задачи? Кроме цикла for? Несмотря на то что в задании пишет именно с помощью него решить задачу. Просто для себя чтобы знать другие варианты.
document.getElementById('root').appendChild(
document.createTextNode(
Array.from(new Array(401), (_, i) => i).slice(4).join(' ')
)
);
import logBuilder from "./logs/logger";
const log = logBuilder(import.meta);
function deepClone(source) {
return ({
'object': cloneObject,
'function': cloneFunction
}[typeof source] || clonePrimitive)(source)();
}
function cloneObject(source) {
return (Array.isArray(source)
? () => source.map(deepClone)
: clonePrototype(source, cloneFields(source, simpleFunctor({})))
);
}
function cloneFunction(source) {
return cloneFields(source, simpleFunctor(function() {
return source.apply(this, arguments);
}));
}
function clonePrimitive(source) {
return () => source;
}
function simpleFunctor(value) {
return mapper => mapper ? simpleFunctor(mapper(value)) : value;
}
function makeCloneFieldReducer(source) {
return (destinationFunctor, field) => {
const descriptor = Object.getOwnPropertyDescriptor(source, field);
return destinationFunctor(destination => Object.defineProperty(destination, field, 'value' in descriptor ? {
...descriptor,
value: deepClone(descriptor.value)
} : descriptor));
};
}
function cloneFields(source, destinationFunctor) {
return (Object.getOwnPropertyNames(source)
.concat(Object.getOwnPropertySymbols(source))
.reduce(makeCloneFieldReducer(source), destinationFunctor)
);
}
function clonePrototype(source, destinationFunctor) {
return destinationFunctor(destination => Object.setPrototypeOf(destination, Object.getPrototypeOf(source)));
}
var el = document.querySelector("a[href='/products/962112']"); // в селекторе хардкод... не будет ссылки с таким href - все сломается
// тут был цикл, но я его убрал, ибо один элемент берем
var products = document.getElementsByClassName('product'); // тут коллекция, ее надо перебирать циклом
for(var i = 0; i < products.length; i++) {
products[i].style.height = el.style.height;
}
const {sheet} = document.head.appendChild(document.createElement('style'));
const rulesIndexesBySelector = {};
let nextIndex = 0;
function updateRule(selector, declarations) {
const rule = `${selector}{${declarations}}`; // полное правило - селектор + декларации в {}
if(selector in rulesIndexesBySelector) {
// индекс селектора уже известен, обновим правило
const index = rulesIndexesBySelector[selector];
sheet.deleteRule(index); // сначала удалим старое правило освободив индекс и отменив его свойства
sheet.insertRule(rule, index); // и вставим на его место новое
} else {
// новый селектор
const index = nextIndex++; // важен именно постинкримент, чтоб самый первый получил 0, второй 1 и т.д.
rulesIndexesBySelector[selector] = index; // запомним на будущее
sheet.insertRule(rule, index); // и вставим правило в конец
}
}
updateRule('.product', 'height: 40px; width: 50px');
document.addEventListener('DOMContentLoaded', function() {
// здесь спокойно можем делать document.querySelector
});
trait Exp {
fn exp(self) -> Self;
}
impl Exp for f32 {
fn exp(self) -> Self {
<f32>::exp(self)
}
}
impl Exp for f64 {
fn exp(self) -> Self {
<f64>::exp(self)
}
}