Выдаёт ошибку:
Traceback (most recent call last):
line 46, in
for m in n.values():
AttributeError: 'int' object has no attribute 'values'
Подскажите как посчитать сумму элементов в данном словаре
def best_function(d):
sum = 0
for v in d.values():
if isinstance(v, dict):
sum += best_function(v)
else:
sum += v
return sum
print(best_function(dct)) # 3906
iptables -t mangle -N SPISOK
iptables -t mangle -A SPISOK -d 10.9.0.0/24 -j RETURN
iptables -t mangle -A SPISOK -d 10.11.0.0/24 -j RETURN
iptables -t mangle -A SPISOK -d 10.14.0.0/24 -j RETURN
iptables -t mangle -A SPISOK -j MARK --set-mark 4
iptables -t mangle -A PREROUTING -i enp1s0 -s 10.8.0.0/24 -j SPISOK
import subprocess
from time import sleep
class CameraMonitor:
def __init__(self):
self.IP12 = '192.168.0.100'
self.IP13 = '192.168.0.101'
self.RODOS12 = '192.168.1.100'
self.RODOS13 = '192.168.1.101'
self.fail_count = {'Купол 12': 0, 'Купол 13': 0}
self.reboot_count = {'Купол 12': 0, 'Купол 13': 0}
def ping_camera(self, ip):
cmd = f'ping {ip} -n 1 -w 100'
response = subprocess.call(cmd, stdout=subprocess.DEVNULL)
return response == 0
def cameras_checker(self):
r_dict = {'Купол 12': self.IP12, 'Купол 13': self.IP13}
while True:
for camera, ip in r_dict.items():
if self.ping_camera(ip):
print(f'Camera {camera} - OK')
self.fail_count[camera] = 0
else:
self.fail_count[camera] += 1
print(f'Camera {camera} - Died')
if self.fail_count[camera] >= 5:
self.cameras_reboot(camera)
sleep(5)
def cameras_reboot(self, camera):
if camera == 'Купол 12':
ip = self.RODOS12
else:
ip = self.RODOS13
self.reboot_count[camera] += 1
print(f'Rebooting {camera} at IP {ip}')
def info(self):
for camera, count in self.reboot_count.items():
print(f'Перезагрузок {camera}: {count}')
if __name__ == "__main__":
monitor = CameraMonitor()
monitor.cameras_checker()
BytesIO
. def get_contact(ids):
for id in ids:
template = f'https://etender.gov.az/api/events/{id}/contact-persons'
try:
response = requests.get(template, timeout=20)
if response.status_code == 200:
data_list = response.json()
for data in data_list:
main_data['Full_name'].append(data.get('fullName', 'None') if data.get('fullName') else 'None')
main_data['Contact'].append(data.get('contact', 'None') if data.get('contact') else 'None')
main_data['Position'].append(data.get('position', 'None') if data.get('position') else 'None')
main_data['Phone_number'].append(data.get('phoneNumber', 'None') if data.get('phoneNumber') else 'None')
else:
main_data['Full_name'].append('None')
main_data['Contact'].append('None')
main_data['Position'].append('None')
main_data['Phone_number'].append('None')
except requests.Timeout:
main_data['Full_name'].append('None')
main_data['Contact'].append('None')
main_data['Position'].append('None')
main_data['Phone_number'].append('None')
main_data = []
...
def get_contact(ids):
for id in ids:
current_data = {'Full_name': 'None', 'Contact': 'None', 'Position': 'None', 'Phone_number': 'None'}
template = f'https://etender.gov.az/api/events/{id}/contact-persons'
try:
response = requests.get(template, timeout=20)
if response.status_code == 200:
data_list = response.json()
for (elem_to, elem_from) in [
('Full_name', 'fullName'),
('Contact', 'contact'),
('Position', 'position'),
('Phone_number', 'phoneNumber')
]:
current_data[elem_to] = data.get(elem_from, 'None')
except requests.Timeout:
pass
main_data.append(current_data)
# cat /etc/init.d/nfqws
#!/bin/sh /etc/rc.common
USE_PROCD=1
START=91
PROG=/etc/zapret/nfqws/nfqws
start_service() {
procd_open_instance
procd_set_param command "$PROG"
procd_append_param command --dpi-desync=fake
procd_append_param command --dpi-desync-fooling=md5sig,badseq
procd_append_param command --dpi-desync-split-pos=1
procd_append_param command --dpi-desync-repeats=12
procd_append_param command --dpi-desync-ttl=4
procd_append_param command --qnum=200
procd_append_param command --hostlist=/etc/zapret/nfqws/youtube.txt
# procd_append_param command --hostlist=/tmp/domains-export.txt
procd_set_param stdout 1 # forward stdout of the command to logd
procd_set_param stderr 1 # same for stderr
procd_close_instance
}
chain zapret_lan_hook {
type filter hook forward priority mangle;
# iifname {"br-lan"} \
ip daddr != {0.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, 100.64.0.0/10, 169.254.0.0/16, 224.0.0.0/3, 255.255.255.255/32} \
tcp dport {80, 443} ct original packets lt 8 counter queue flags bypass to 200 comment "zapret IPv4 443 tcp"
# iifname {"br-lan"} \
ip6 daddr != {::ffff:0:0/96, fc00::/7, fe80::/10, ff00::/8} \
tcp dport {80, 443} ct original packets lt 8 counter queue flags bypass to 200 comment "zapret IPv6 443 tcp"
# iifname {"br-lan"} \
ip daddr != {0.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, 100.64.0.0/10, 169.254.0.0/16, 224.0.0.0/3, 255.255.255.255/32} \
udp dport 443 ct original packets lt 8 counter queue flags bypass to 200 comment "zapret IPv4 443 udp"
# iifname {"br-lan"} \
ip6 daddr != {::ffff:0:0/96, fc00::/7, fe80::/10, ff00::/8} \
udp dport 443 ct original packets lt 8 counter queue flags bypass to 200 comment "zapret IPv6 443 udp"
}
config include 'zapret'
option type 'nftables'
option path '/etc/zapret/zapret.nft'
option position 'table-post'
option enabled '1'
youtube.com
youtu.be
googlevideo.com
googleapis.com
gvt1.com
ggpht.com
ytimg.com
youtube-nocookie.com
play.google.com
video.google.com
youtube-ui.l.google.com
youtubeeducation.com
youtubekids.com
from collections import Counter
from itertools import chain
data = [
(1, 'old;white'),
(2, 'old;green'),
(3, 'old;brown'),
(4, 'new;green'),
]
# генерирует последовательность ['old', 'white'], ['old', 'green'], ...
split_generator = (item[1].split(';') for item in data)
# генерирует последовательность 'old', 'white', 'old', 'green', ...
property_generator = chain.from_iterable(split_generator)
# исправляет регистр и удаляет пробелы - можно убрать, если не надо
property_fixed_generator = (item.strip().lower() for item in property_generator)
# поглощает данные из генераторов и считает вхождения
count = Counter(property_fixed_generator)
print(count) # Counter({'old': 3, 'green': 2, 'white': 1, 'brown': 1, 'new': 1})
import os
# выходим на верхний уровень
parentdir = os.path.dirname(os.path.dirname(__file__))
# и добавляем его к путям поиска
os.sys.path.insert(0,parentdir)
# после чего можем использовать импорт по вложенному пути
import module_name.module.ModuleFileOne
audiowaveform -i test.mp3 -o test.png -z 10000 --waveform-style bars --bar-width 3 --bar-gap 2 --bar-style rounded --no-axis-labels --amplitude-scale 1.25 --background-color 333333 --waveform-color BFBFBF
from typing import NamedTuple
class Result(NamedTuple):
text: str # текст запроса
success: bool # успешен ли запрос
status: str # статус
async def check_text(text: str) -> Result:
url = f'https://сайт.com/?query={text}'
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status != 200:
return Result(text=text, success=False, status='Не удалось определить результат')
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
status_element = soup.find('div', class_='table-block')
if not status_element:
return Result(text=text, success=False, status='Не удалось определить результат')
status_text = status_element.get_text().strip()
# тебе нужно будет решить, когда запрос был успешен (True), а когда нет (False)
if "ok" in status_text:
return Result(text=text, success=True, status='Можно')
elif "no" in status_text:
return Result(text=text, success=False, status='Данный вариант недоступен')
elif "no1" in status_text:
return Result(text=text, success=True, status='Можно под заказ')
else:
return Result(text=text, success=False, status='Неизвестно')
result = await check_text(text)
if result.success:
... # реагируем на успешный запрос
logger.info('%s: %s', result.text, result.status)
else:
... # реагируем на неудачный запрос
logger.info('%s: %s', result.text, result.status)