const https = require('https');
const fs = require('fs');
const path = require('path');
const { URL } = require('url');
async function downloadFile(url, outputPath) {
// Парсим URL для получения компонентов
const parsedUrl = new URL(url);
// Если путь для сохранения не указан, используем имя файла из URL
if (!outputPath) {
outputPath = path.basename(parsedUrl.pathname);
}
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(outputPath);
https.get(url, (response) => {
// Проверяем статус код ответа
if (response.statusCode !== 200) {
reject(new Error(`Ошибка загрузки: ${response.statusCode}`));
return;
}
// Получаем общий размер файла для прогресса
const totalSize = parseInt(response.headers['content-length'], 10);
let downloadedSize = 0;
response.pipe(file);
// Опционально: отслеживание прогресса загрузки
response.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize) {
const percent = (downloadedSize / totalSize * 100).toFixed(2);
console.log(`Загружено: ${percent}%`);
}
});
file.on('finish', () => {
file.close();
resolve({ path: outputPath, size: downloadedSize });
});
}).on('error', (err) => {
fs.unlink(outputPath, () => reject(err));
});
file.on('error', (err) => {
fs.unlink(outputPath, () => reject(err));
});
});
}
// Пример использования
downloadFile('https://example.com/file.zip', './downloaded-file.zip')
.then((result) => console.log(`Файл сохранен: ${result.path} (${result.size} байт)`))
.catch((err) => console.error('Ошибка загрузки:', err));
const reader = new FileReader();
reader.onload = (e) => {
formPreview.innerHTML = `<img src="${e.target.result}" alt="Обложка книги">`
//
const base64String = reader.result;
console.log(base64String); // Вывод base64-строки, можно сохранить ее в LS
};
reader.onerror = (e) => alert('Ошибка!');
reader.readAsDataURL(file);
}
imgPreview.src = base64String; // показываем изображение, imgPreview - id тега с img
server {
listen 80;
server_name localhost;
location / {
root /var/www/html;
index index.php;
}
location /metrics {
stub_status;
allow 127.0.0.1;
deny all;
}
location ~ \.php$ {
root /var/www/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;
include fastcgi_params;
}
}
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>
const changed = require('gulp-changed');
function html() {
return src(['app/pages/**/*.html'])
.pipe(changed('app/', {extension: '.html'}))
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
}))
.pipe(dest('app/'))
.pipe(browserSync.stream());
}
import customtkinter as ctk
app = ctk.CTk()
def resize_frame(event):
# Растягиваем frame на всю площадь canvas
canvas.itemconfig(frame_id, width=event.width-2*padx)
# Ширина и высота отступов
padx =20
pady = 20
# Canvas
canvas = ctk.CTkCanvas(app, bg="blue", highlightthickness=0)
canvas.pack(fill='both', expand=True, padx=padx, pady=pady)
# Функция привязки изменения размера Canvas
canvas.bind('<Configure>', resize_frame)
main_frame = ctk.CTkFrame(app, bg_color='white')
frame_id = canvas.create_window((20, 20), window=main_frame, anchor='nw')
scrollbar = ctk.CTkScrollbar(app, command=canvas.yview)
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.place(relx=1, rely=0, relheight=1, anchor='ne')
# наполнение
for i in range(40):
ctk.CTkButton(main_frame, text='Click Me').pack(pady=10)
canvas.update_idletasks()
canvas.configure(scrollregion=canvas.bbox("all"))
app.mainloop()
function restartTimer(
originalFunc: (...args: any[]) => void,
newDelay: number,
...args: any[]
): number {
clearTimeout(timerId); // timerId должен быть доступен в области видимости
return setTimeout(originalFunc, newDelay, ...args);
}
// Используйте так:
let timerId: number; // Храните timerId в доступном месте
function testFunc(param1: string, param2: string) {
console.log(param1);
console.log(param2);
}
// Запуск таймера
timerId = setTimeout(testFunc, 5000, 'asd', 'qwe');
// В нужный момент перезапустить таймер с новым временем. Например, с 10000 мс.
timerId = restartTimer(testFunc, 10000, 'asd', 'qwe');
const data = await this._db.collection('counters').findOne(
{ "objectId": { $exists: true } },
{ projection: { _id: 0, objectId: 1 } }
);
// Теперь data уже будет содержать только 'objectId',
// и вы можете обращаться так: data.objectId.last
await this._db.collection('counters').updateOne(
{ "objectId": { $exists : true } },
{ $inc: { "objectId.last": 1 } } // инкрементируем поле 'last' объекта 'objectId' на 1
);
function shortPathWithDistances(graph, start, end) {
const distances = {};
const visited = new Set();
const path = {};
const edgeWeights = {}; // Новый объект для хранения весов ребер
for (const key in graph) {
if (key !== start) {
distances[key] = Infinity;
} else {
distances[start] = 0;
}
}
while (!visited.has(end)) {
let lowestDistance = Infinity;
let node = null;
for (const key in distances) {
if (lowestDistance > distances[key] && !visited.has(key)) {
lowestDistance = distances[key];
node = key;
}
}
const neighbors = graph[node];
for (const key in neighbors) {
const newDistance = distances[node] + neighbors[key];
if (newDistance < distances[key]) {
distances[key] = newDistance;
path[key] = node;
edgeWeights[key] = neighbors[key]; // Сохраняем вес ребра
}
}
visited.add(node);
}
const shortPath = [];
let current = end;
while (current !== start) {
const currentWithDistance = { node: current, edgeWeight: edgeWeights[current] };
shortPath.unshift(currentWithDistance);
current = path[current];
}
shortPath.unshift({ node: start, edgeWeight: 0 });
return shortPath;
}