from telethon import TelegramClient, utils
# config
api_id = 'id'
api_hash = 'hash'
phone = 'phone'
client = TelegramClient('session_name', api_id, api_hash)
async def main():
# authentication
await client.start(phone)
# get group and channel list
dialogs = await client.get_dialogs()
# print group and channel data
for dialog in dialogs:
if dialog.is_group or dialog.is_channel:
print(f"{dialog.name}: {dialog.id}")
# start
client.loop.run_until_complete(main())
foreach($matches[1] as $index => $video_id) {
$replacement = '<lite-youtube videoid="' . $video_id . '" params="controls=1"></lite-youtube>';
$content = str_replace($matches[0][$index], $replacement, $content);
}
if(!empty($matches[0]))
'/<iframe[^>]*src=\"https:\/\/www\.youtube\.com\/embed\/([^\?"]+)(\?[^\"]*)?\"[^>]*><\/iframe>/';
node_modules
, они устанавливаются на основе файла проекта package.json (инициализация).<?php
/**
* Plugin Name: Чумовой плагин
* Description: Это плагин, твердо и четко!
*/
if(!defined('ABSPATH')) {
exit;
}
class Best_Plugin {
protected $menu_slug = 'best-plugin';
public function __construct() {
// добавление страницы с пунктом меню
add_action('admin_menu', [$this, 'add_admin_page']);
// добавление ссылки на настройки плагина в списке плагинов
add_filter(
'plugin_action_links_' . plugin_basename(__FILE__),
[$this, 'add_settings_link']
);
}
// страница, любое содержимое страницы, обычно это винегрет из html/js/php
public function add_page() {}
// добавление страницы с пунктом меню
public function add_admin_page() {
add_options_page(
'Страница чумового плагина',
'Чумовой плагин',
'manage_options',
$this->menu_slug,
[$this, 'add_page'],
1
);
}
// добавление ссылки на настройки в списке плагинов
public function add_settings_link($links) {
$settings_link = "<a href=\"options-general.php?page={$this->menu_slug}\">Настройки чумового плагина</a>";
array_unshift($links, $settings_link);
return $links;
}
}
new Best_Plugin();
Да и по остальным моментам опыта и знаний 0
import requests
TOKEN = 'token'
OWNER_ID = 'user_or_group_id'
POST_ID = 'post_id'
res = requests.get(
'https://api.vk.com/method/wall.getComments',
params = {
'owner_id': OWNER_ID,
'post_id': POST_ID,
'access_token': TOKEN,
'v': '5.130'
}
)
comments = res.json()
спарсить комментарии со всех постов
сложить в один файл, преобразовав в вид ссылки
удалить дубликаты
рандомно выбрать 1 победителя, среди комментариев
парсить по ключевому слову "участвую"
что бы программа сама открыла ссылку победителя и отправила сообщение мол "вы победили"
Got error selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable: Element is not currently visible and may not be manipulated
Как можно поправить? На экране он виден
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("example.com")
# находим и кликаем на элемент .SumoSelect
dropdown_container = driver.find_element(By.CSS_SELECTOR, ".SumoSelect")
dropdown_container.click()
# ждем появления элемента li.opt label, но не более 10 сек
option_to_select = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "li.opt label"))
)
# итерируемся по всем option и кликаем, если текст option равен AB
for option in options:
if "AB" == option.text.strip():
option.click()
break
else:
print("Не удалось найти нужную опцию.")
driver.quit()
export const getServerSideProps = async (context) => {
const page = context.query.page || 1;
try {
const res = await axios.get(`tracks?page=${page}`);
return {
props: {
tracks: res.data.items,
},
}
} catch (e) {
return {
notFound: true,
}
}
}
export const getStaticProps = async (context) => {
const page = context.params.page;
// code
}
Почему когда я указываю большие разбиваемого и количества слогаемых,вылетает ошибка:
print(partition(1024,5))
import sys
sys.setrecursionlimit(5000)
def partition(n, k):
stack = [(n, k, [])]
while stack:
current_n, current_k, current_partition = stack.pop()
if current_n == 0 and current_k == 0:
print(" + ".join(map(str, current_partition)))
elif current_n == 0 or current_k == 0:
continue
elif current_n < 0:
continue
else:
for i in range(1, current_n+1):
new_n = current_n - i
new_k = current_k - 1
new_partition = current_partition + [i]
stack.append((new_n, new_k, new_partition))
partition(5, 3)
x = 5
y = 555
print(f"{x:1}") # "5", минимальная ширина поля вывода переменной x = 1 (вывести значение x, удостоверившись, что оно занимает по меньшей мере один символ)
print(f"{x:3}") # " 5"
print(f"{y:3}") # "555"
# Округление Pi до десятичного значения
pi = 3.141592653589793
print(f"Pi: {pi:.1f}") # Pi: 3.1
import winreg
# Добавляем в автозагрузку
def add_to_startup(program_name, executable_path):
# Реестр
registry_path = winreg.HKEY_CURRENT_USER
key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
try:
# Открываем ключ реестра для записи
with winreg.OpenKeyEx(registry_path, key_path, 0, winreg.KEY_WRITE) as registry_key:
# Создание или обновление реестра
winreg.SetValueEx(registry_key, program_name, 0, winreg.REG_SZ, executable_path)
print(f"{program_name} добавлена в автозагрузку.")
except PermissionError:
print("Нужны админские права.")
# Проверка программы в автозагрузке
def check_startup_entry(program_name):
registry_path = winreg.HKEY_CURRENT_USER
key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
try:
# Открываем ключ реестра для чтения
with winreg.OpenKeyEx(registry_path, key_path, 0, winreg.KEY_READ) as registry_key:
program_path, regtype = winreg.QueryValueEx(registry_key, program_name)
print(f"{program_name} уже добавлена в автозагрузку с путем: {program_path}")
except FileNotFoundError:
print(f"{program_name} не найдена в автозагрузке.")
if __name__ == "__main__":
program_name = "GodzillaSoft"
program_path = r"C:\path\GodzillaSoft.exe"
check_startup_entry(program_name)
add_to_startup(program_name, program_path)
$breakpoint_sm: 300px;
$breakpoint_md: 700px;
$breakpoint_xl: 1000px;
@import "breakpoints";
@media screen and (max-width: $breakpoint_md) {
// ...
}
@import "fonts";
@import "breakpoints";
import { FC } from "react";
import { AppProps } from "next/app";
import "./styles/index.scss";
const App: FC<AppProps> = ({ Component, pageProps }) => (
<Component {...pageProps} />
);
export default App;
Но тут видите, мы все равно подключаем
Dmitrijs Balcers "breakpoints"; в BestComponent, а надо без импорта, сразу
:root {
--breakpoint-sm: 300px;
--breakpoint-md: 700px;
--breakpoint-xl: 1000px;
}
@media screen and (max-width: var(--breakpoint-md)) {}
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
additionalData: `@import "path/breakpoints.scss";`
}
}
]
}
Как верстать правильно и по "феншую"?
$query_args = array(
'showposts' => 5,
'post_status' => 'publish',
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
);
$r = new WP_Query( $query_args );
if ( $r->have_posts() ) {
while ( $r->have_posts() ) {
$r->the_post();
// Вывод
}
}
wp_reset_postdata();