Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
🪐 In 2019, the asteroid 2019 OK startled astronomers when it was detected passing just 70,000 kilometers from Earth—less than a fifth of the distance to the Moon. This city-sized object, about 100 meters wide, slipped by with very little warning, highlighting how some space threats can go undetected until they're nearly upon us, and why vigilance is vital for discovering near-Earth objects in time. ✨
#asteroids⚡#nearEarth⚡#detection⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (2014) AA was discovered on January 1, 2014, just hours before it entered Earth's atmosphere near West Africa and burned up harmlessly. This rare event made 2014 AA only the second asteroid ever detected before impacting Earth, highlighting the importance of sky surveys to spot even small space rocks before they arrive. ✨
#asteroids⚡#impact⚡#detection⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🌟WildDet3D: открытая модель монокулярной 3D-детекции по одному снимку.
Институт Аллена представил модель WildDet3D, которая по одному изображению строит 3D-рамки объектов: оценивает их положение, размер и ориентацию в метрических координатах.
Модель принимает сразу несколько типов промптов: текстовый запрос, клик по точке или готовый 2D-бокс от внешнего детектора.
🟡Архитектура состоит из 3 блоков
2D-детектор построен на SAM3 и обрабатывает все типы запросов.
Геометрическая ветка использует энкодер DINOv2 с обучаемым декодером глубины, учитывающим геометрию обзора: направления лучей камеры зашиваются через сферические гармоники, что снимает необходимость в отдельной калибровке.
Третий компонент, 3D-head, объединяет через кросс-внимание 2D-детекции с признаками глубины и поднимает их в полноценные 3D-боксы.
Если на инференсе доступны данные с LiDAR, ToF или стереокамеры, они подмешиваются в ту же геометрическую ветку без переобучения.
🟡Тесты
На бенчмарке Omni3D модель показывает 34,2 AP с текстовыми промптами (это +5,8 пункта к прежнему лидеру 3D-MOOD).
На zero-shot переносе на Argoverse 2 WildDet3D практически удваивает прежний результат: 40,3 ODS против 23,8.
На редких категориях из собственного бенчмарка WildDet3D-Bench успехи, разумеется, еще лучше - 47,4 AP против 2,4 у 3D-MOOD.
🟡Вместе с моделью вышло демо-приложение для iOS.
Оно использует видеопоток с камеры iPhone и данные LiDAR-сенсора, чтобы в реальном времени отрисовывать 3D-боксы поверх сцены как AR-оверлей.
Это наглядная демонстрация того, как монокулярная модель усиливается, когда устройство умеет отдавать дополнительный сигнал глубины.
🟡Третья часть релиза - датасет WildDet3D-Data.
Более 1 млн. изображений и 3,7 млн. верифицированных 3D-аннотаций, охватывающих свыше 13 тыс. категорий объектов. По сценам распределение получилось такое: 52% помещений, 32% городской среды и 15% природы.
Он собран на основе 2D-наборов (COCO, LVIS, Objects365, V3Det): кандидаты в 3D-боксы генерировались 5 независимыми методами оценки геометрии, затем фильтровались, проверялись VLM и дополнительно отбирались людьми.
🟡Статья
🟡Модель
🟡Техотчет
🟡Demo
🖥GitHub
@ai_machinelearning_big_data
#AI#ML#CV#Detection#WildDet3D#Ai2
#go#attacks_prevention#detection#linux#protection#security
CrowdSec is an open-source security solution that helps protect servers from malicious IP addresses. It uses a community-driven approach, where users share information about threats they've faced, creating a shared blocklist to prevent attacks. CrowdSec's Security Engine can detect bad behaviors by analyzing logs and HTTP requests, and it supports multiple platforms. This system is fast, easy to use, and designed for modern infrastructures, making it a powerful tool for securing your systems against various threats. By using CrowdSec, you benefit from collective protection and can focus on real security issues.
https://github.com/crowdsecurity/crowdsec
Chasing Your Tail (CYT)
https://github.com/ArgeliusLabs/Chasing-Your-Tail-NG
A comprehensive #WiFi probe request analyzer that monitors and tracks wireless devices by analyzing their probe requests. The system integrates with #Kismet for packet capture and WiGLE API for #SSID#geolocation analysis, featuring advanced #surveillance#detection capabilities.
Features
Real-time Wi-Fi monitoring with Kismet integration
Advanced surveillance detection with persistence scoring
Automatic GPS integration - extracts coordinates from Bluetooth GPS via Kismet
GPS correlation and location clustering (100m threshold)
Spectacular KML visualization for Google Earth with professional styling and interactive content
Multi-format reporting - Markdown, HTML (with pandoc), and KML outputs
Time-window tracking (5, 10, 15, 20 minute windows)
WiGLE API integration for SSID geolocation
Multi-location tracking algorithms for detecting following behavior
Enhanced GUI interface with surveillance analysis button
Organized file structure with dedicated output directories
Comprehensive logging and analysis tools
Requirements
Python 3.6+
Kismet wireless packet capture
Wi-Fi adapter supporting monitor mode
Linux-based system
WiGLE API key (optional)
🚀 AI TRENDS | Wall Street Banks Test Anthropic's Mythos Model for Vulnerability Detection
Wall Street banks have begun internal testing of Anthropic's Mythos model, as reported by Bloomberg on X. The initiative comes amid encouragement from U.S. President Donald Trump's administration officials, who are advocating for its use in identifying potential vulnerabilities. The Mythos model, developed by Anthropic, is designed to enhance security measures within financial institutions by leveraging advanced AI capabilities. This move reflects a growing trend among major banks to integrate cutting-edge technology to bolster their defenses against emerging threats.
#AI#trends#WallStreet#banks#Anthropic#Mythos#model#vulnerability#detection#security#financialinstitutions#AItechnology#emergingthreats
#yara#awesome_list#blueteam#blueteam_tools#cti#detection#detection_engineering#dfir#hacktools#incident_response#ioc#iocs#ir#ransomware#redteam#rmm#security#siem#soc#threat_hunting#threat_intelligence
You can access comprehensive security detection lists and threat hunting resources that help identify malicious activity across your infrastructure. These curated collections include indicators like suspicious file hashes, domain names, IP addresses, and behavioral patterns organized by threat type—from ransomware and phishing to command-and-control servers and vulnerable drivers. By integrating these lists into your security tools like SIEM platforms and endpoint detection systems, you gain immediate visibility into known threats while learning detection methodologies through guides and YARA rules. This accelerates your ability to hunt for compromises, validate security controls, and stay current with emerging attack techniques without building detection logic from scratch.
https://github.com/mthcht/awesome-lists