AI 资讯
Introduction to Python Module Four Part Three: Slicing
Sololearn’s Introduction to Python course is wrapping up today with a brand new topic. Today’s post is wrapping up module four by introducing. You’ll learn what slicing is and how to slice a list in Python. Sequences like lists and strings are ordered content. Ordered content is great for indexing and slicing. In addition to learning about slicing, Sololearn shares some advanced slicing and indexing tips to help you with your code. Slicing Slicing lets developers take portions from a list that they need. You’ll be slicing lists all the time in your Python code. At Coding with Kids, the students were slicing lists as they were building games. To slice a list, put the variable name of list followed by an opening square bracket. Put the index you want to start slicing at. Place a colon (:) after this. Put the index when you want to stop slicing at then place the closing square brackets. Here’s an example of slicing in action. I created a variable called pizza_toppings with a list of strings assigned to them. The starting index is inclusive while the stopping index is exclusive. pizza_toppings = [ " pepperoni " , " mushrooms " , " onions " , " peppers " , " broccoli " , " sausage " ] print ( pizza_toppings [ 0 : 3 ]) # print pepperoni, mushrooms, and onions The line underneath the list is slicing the first 3 toppings from the list. I’m printing them to the console to make sure these three are displaying. If you see the wrong toppings or too many items, double check the index you are starting and ending with. Slicing a String Strings can be sliced to in the same way we did the example above. Here’s a variable with a string assigned to it. If I want to slice certain letters in the string, I will put the indexes where I should start and stop at. pizza = " pepperoni " print ( pizza [ 0 : 6 ]) # print pepper When I sliced this string, I was able to move data from a sequence. In this example, I’m able to create a brand new string. If you look at the the pizza topping example
AI 资讯
Generating 10,000 certificates from one HTML template
The day your first cohort completes a course is the day certificates stop being a design job and become an engineering problem. One certificate is a Canva export. Ten thousand is a rendering pipeline with a database table, a queue and a verification page. This post walks through the three ways teams actually build that pipeline, with working Python for each, then covers the two parts most certificate tutorials skip: batching at volume and verification. It is a condensed version of our full guide, How to generate signed digital certificates at scale , which also covers storage, retention and revocation. One scope note up front. Most platform certificates do not need cryptographic signing in the PKI sense. The trust model that 95% of platforms ship is simpler: a unique ID printed on the certificate resolves to a verification page on the issuer's domain. An employer types the ID, the page confirms it. That is the model this post builds. If you need true PKI signing for regulated credentials, the stack is different (Adobe Sign, DocuSign, in-house HSM workflows) and this post is not it. What every certificate needs Whichever approach you pick, the output is the same: Component Detail Layout Landscape A4, 2480x1754 at 200 DPI for print Personal Recipient name with full Unicode support Course Course title and completion date Issuer Issuer name plus a signature image ID Unique certificate ID (UUID or short slug) Verify A URL under the ID pointing to your /verify route The signature image communicates authority but provides zero tamper resistance. The certificate ID plus the verification page is the practical trust layer. Keep both in mind as you read the code. The three approaches at a glance Approach Setup Render time Maintenance PDF library (ReportLab, PDFKit) 1 day 200 to 400 ms Fonts, layout drift, library updates HTML plus headless Chrome 2 hours 1 to 3 sec Chromium, memory, queue workers Template API 5 minutes 1 to 2 sec None Approach 1: a PDF library Python with Repo
AI 资讯
I have been Vibecoding Evals (works better than I thought)
I’ve been building AI apps with coding agents for a while. Lately, I’ve been experimenting with evals too. The app in this example mostly worked. That was the problem. The bug I built a small support-triage app for a fictional shipment-tracking company. A customer sends a support ticket, and the app decides what it is about, how urgent it is, and whether a human needs to respond. A real outage should be escalated. But this ticket was different: “URGENT need key rotation now” The customer was asking how to rotate their own API key before a security review. The app classified it as a security incident and escalated it to a human. That was wrong. The policy said normal key rotation was a self-service how-to request. Nothing crashed. The app returned valid JSON. The fields all contained allowed values. The behavior was still wrong. Why clicking around wasn’t enough I could test a few tickets manually and convince myself the app worked. But after changing the prompt, what would I actually know? Would the outage case still escalate? Would normal how-to questions stay in the normal queue? Would another API-key question behave differently? I didn’t want to change the prompt and simply hope for the best. I wanted a set of cases I could run again. Adding DeepEval with Cursor I installed the DeepEval agent skill: npx skills add confident-ai/deepeval --skill "deepeval" Then I asked Cursor to add evals to the app: This app sometimes treats normal support questions like emergencies and sends them to a human. Add DeepEval so I can test this using the tickets and policy already in the repo. I am new to evals, so use the simplest setup DeepEval already provides, explain what you create, and ask me anything you need. Run the app as it is first and show me what fails. Do not fix it yet. Cursor already had the app, tickets, and policy, so it went straight to creating the baseline. Goldens are the checklist The first useful artifact was a JSON dataset. Each golden contained: the custome
AI 资讯
Building a security posture scanner with Next.js and Python
I wanted to learn cloud security the way it actually sticks: by building something real. So I built PostureGuard, a web application that scans a domain and returns a security posture report covering TLS, HTTP security headers and open ports, with a 0-100 score and an A-F grade. This post walks through the architecture and the decisions I found most interesting. Update: Phase 1 is done. PostureGuard now runs on Azure Container Apps and is live at app.samdossou.com . The write-up is the next post in this series. The shape of the system PostureGuard has three moving parts: A Next.js web app (App Router, TypeScript) where users sign up, add a domain, and request scans. A PostgreSQL database that stores users, domains and scans. A Python worker that runs the actual scans in the background. The web app never runs a scan itself. When a user clicks "Scan", the app just inserts a row into a scans table with the status queued and returns immediately. The worker picks the job up a moment later. This keeps the request fast and the two halves of the system decoupled. Using PostgreSQL as a job queue The part I like most is that there is no separate message broker. The scans table doubles as the queue. The worker claims one job at a time with a single query: SELECT s . id , d . name FROM scans s JOIN domains d ON d . id = s . domain_id WHERE s . status = 'queued' ORDER BY s . requested_at FOR UPDATE OF s SKIP LOCKED LIMIT 1 FOR UPDATE locks the row so no one else can grab it, and SKIP LOCKED tells other workers to ignore locked rows and move on to the next job. That means I can run several workers in parallel and they will never process the same scan twice, without any extra infrastructure. For a project at this scale, a table plus SKIP LOCKED is simpler and more than enough. The scanners The worker runs three checks, all built on the Python standard library to keep dependencies light: TLS: it opens a TLS connection, reads the certificate expiry and the negotiated protocol version
AI 资讯
100 城时区页给跨区调度当速查,DST 自动算
100 城时区页给跨区调度当速查,DST 自动算 作者是 数据管道 / 跨时区调度 方向的开发者。这篇不是广告,是踩坑记录 + 顺手做的工具。 背景 做 数据管道 / 跨时区调度 时,时间戳转换是最常被低估的雷区。16 个时间戳工具(Unix 转换/时区/ISO8601/Cron/Duration…) 已覆盖日常;但每个语言/框架的坑都不一样,所以又补了 30 个语言/框架时间戳页(python/javascript/java/sql/…),每页含 6 个真实坑。 我踩过的坑(举几个) 秒 vs 毫秒:前端 Date.now() 是毫秒,后端常存秒,混用差 1000 倍。 时区不是字符串:存 UTC、展示本地,别把本地时间当 UTC 落库。 2038 问题:32 位系统 time_t 在 2038-01-19 溢出,老系统要提前查。 夏令时:一年有两次重复/缺失的本地时间,跨区调度尤其坑。 我顺手做的东西 转换速查页: https://gotimestamp.com/timezone/new-york 相关语言页: https://gotimestamp.com/timezone/london 开源 MCP: https://github.com/caresotin/tsforge-mcp —— 把时间戳转换/校验直接接进 LLM 工作流,不用手算。 小结 时间戳没那么简单,但工具到位就省心。上面都是免费、开源、可直接用的,希望对同样踩坑的人有帮助。
AI 资讯
It refused to run a dangerous option. I wrote it one character shorter, and it ran
GitPython ships a guard against dangerous git options. If your code builds a clone command out of anything that arrived from outside, the library will not let --upload-pack or --config through by default, because both of them execute an arbitrary command. The guard is on out of the box and turns off only with an explicit allow_unsafe_options=True . I handed it --upload-pack=/srv/lab/helper.sh . It refused. I handed it the same thing written differently, -u/srv/lab/helper.sh , and it let it through. The script ran. This is CVE-2026-67324, published on 1 August 2026, scored 9.8 on CVSS 3.1 and 9.3 on CVSS 4.0. Those numbers still come from the CNA that filed it: NVD has not run its own analysis yet, the record sits in status Received, so the score may move. Version 3.1.50 is vulnerable, 3.1.51 is fixed. Below, step by step: the lab, both attempts with real output, the code of the check and why it missed, and what the attack looks like from the outside. Plus the part I find more interesting than the hole itself. This is the third bypass of the same barrier within one year, and all three share a root cause. Why this deserves your attention Almost nobody installs GitPython on purpose. It gets 254 million downloads a month from PyPI against five thousand stars on GitHub, and a two-order gap like that means one thing: it arrives as a passenger. With MLflow, with DVC, with bandit, with semgrep, with half the homegrown scripts that touch repositories in CI. Let me draw the boundary right away, so nobody panics for nothing. Having it installed is harmless on its own. The hole fires only when two conditions hold at the same time: your code calls Repo.clone_from(..., multi_options=[...]) , something an outsider influences ends up inside multi_options . The second one happens more often than it sounds. A repository URL from a web form, build parameters from a config another team edits, a field in a CI job, arguments from a webhook. And if you are leaning on allow_unsafe_options=
AI 资讯
Tokens por Segundo: Cómo medir y optimizar la velocidad en modelos de IA
Cuando llevamos modelos de lenguaje o IA a producción, la latencia es nuestro principal enemigo. Evaluar un modelo únicamente por su precisión ignora un factor crítico: el rendimiento computacional. En este post analizamos por qué la velocidad (medida en tokens por segundo) se ha convertido en una métrica clave de arquitectura y cómo puedes empezar a medirla. ¿Por qué importa la velocidad? Reducción de Latencia: Aplicaciones críticas (finanzas, salud, automatizaciones) no pueden esperar segundos por una respuesta. Eficiencia de Recursos: Optimizar el rendimiento disminuye el uso prolongado de GPUs, reduciendo directamente la factura cloud. Técnicas Clave: El uso de arquitecturas ligeras, cuantización y batch processing permite mantener la precisión mientras se incrementa el rendimiento. Ejemplo Práctico: Midiendo el rendimiento en Python Un enfoque inicial para medir la tasa de procesamiento de datos/tokens en tus pruebas de rendimiento: import time def medir_velocidad ( modelo , datos ): inicio = time . time () # Procesamiento del conjunto de datos o tokens respuesta = modelo . procesar ( datos ) fin = time . time () tiempo_total = fin - inicio tokens_procesados = len ( datos ) # O conteo exacto de tokens generados/procesados velocidad = tokens_procesados / tiempo_total print ( f " Tiempo total: { tiempo_total : . 2 f } s " ) print ( f " Rendimiento: { velocidad : . 2 f } tokens/segundo " ) return velocidad Tip de Arquitectura: Un objetivo de ~100 tokens/seg es una excelente referencia para sistemas que requieren interacción humana en tiempo real. Pasos sugeridos para optimizar: Benchmark inicial: Establece tu baseline de tokens/seg. Batch Processing: Agrupa solicitudes para maximizar el paralelismo. Modelos Destilados/Cuantizados: Evalúa si un modelo más pequeño satisface el caso de uso con una fracción de la latencia. 💬 Comunidad Pivelcode: ¿Qué herramientas o librerías utilizas para hacer profiling y benchmarking de tus modelos de IA? ¡Déjalo en los comentarios!
开源项目
🔥 razzant / ouroboros - Ouroboros — self-creating AI agent. Born Feb 16, 2026.
GitHub热门项目 | Ouroboros — self-creating AI agent. Born Feb 16, 2026. | Stars: 905 | 171 stars this week | 语言: Python
开源项目
🔥 comet-ml / opik - Debug, evaluate, and monitor your LLM applications, RAG syst
GitHub热门项目 | Debug, evaluate, and monitor your LLM applications, RAG systems, and agentic workflows with comprehensive tracing, automated evaluations, and production-ready dashboards. | Stars: 21,085 | 37 stars today | 语言: Python
开源项目
🔥 vitali87 / code-graph-rag - The ultimate RAG for your monorepo. Query, understand, and e
GitHub热门项目 | The ultimate RAG for your monorepo. Query, understand, and edit multi-language codebases with the power of AI and knowledge graphs | Stars: 2,492 | 42 stars today | 语言: Python
开源项目
🔥 livekit / agents - A framework for building realtime voice AI agents 🤖🎙️📹
GitHub热门项目 | A framework for building realtime voice AI agents 🤖🎙️📹 | Stars: 11,803 | 129 stars today | 语言: Python
开源项目
🔥 donnemartin / system-design-primer - Learn how to design large-scale systems. Prep for the system
GitHub热门项目 | Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards. | Stars: 360,291 | 138 stars today | 语言: Python
AI 资讯
Stop Waiting for the Full AI Response: Stream Tokens in Python
Most AI applications wait for the model to generate the complete answer before showing anything to the user. For short answers, that may be acceptable. For longer responses, it can make the application feel slow—even when the model is already generating tokens. Streaming solves this by displaying each part of the response as soon as it arrives. The non-streaming version A standard OpenAI-compatible request may look like this: import os from openai import OpenAI client = OpenAI ( api_key = os . environ [ " AI_API_KEY " ], base_url = os . environ [ " AI_BASE_URL " ], ) response = client . chat . completions . create ( model = os . environ [ " AI_MODEL " ], messages = [ { " role " : " user " , " content " : " Explain API gateways in three sentences. " , } ], ) print ( response . choices [ 0 ]. message . content ) This works, but nothing is printed until the complete response has arrived. Stream the response Enable streaming by adding stream=True : stream = client . chat . completions . create ( model = os . environ [ " AI_MODEL " ], messages = [ { " role " : " user " , " content " : " Explain API gateways in three sentences. " , } ], stream = True , ) The request now returns a sequence of chunks instead of one completed response. Loop through those chunks and print the available content: for chunk in stream : content = chunk . choices [ 0 ]. delta . content if content : print ( content , end = "" , flush = True ) print () The user can now see the answer while it is being generated. Complete example import os from openai import OpenAI client = OpenAI ( api_key = os . environ [ " AI_API_KEY " ], base_url = os . environ [ " AI_BASE_URL " ], ) stream = client . chat . completions . create ( model = os . environ [ " AI_MODEL " ], messages = [ { " role " : " user " , " content " : " Explain API gateways in three sentences. " , } ], stream = True , ) for chunk in stream : content = chunk . choices [ 0 ]. delta . content if content : print ( content , end = "" , flush = True )
AI 资讯
RAG Retrieval Accuracy: 38%. After the Fix: 87%. The Model Was Never Touched.
That's a rebuild I shipped. The system: a RAG assistant for fraud analysts — ask it "how do we handle card testing followed by a successful auth?" and it should answer from the team's own SOPs and case history. The complaint: the answers were wrong, therefore the model must be dumb, therefore procurement should buy a bigger model. The model was fine. It was answering perfectly — from garbage context. Walk the forensic trail with me, because every step is checkable on your own system this week. Exhibit A: the chunking was destroying meaning before anything was embedded The ingestion split SOP documents every N characters, mid-sentence. Which means half the vectors in the index encoded fragments like this: chunk_147 = " ...ing to a freight forwarder. In these cases, do NOT " chunk_148 = " cancel the order immediately. First verify the customer via " The policy — don't cancel, verify first — exists in no single chunk. An embedding can't encode a meaning that isn't in its input. Retrieval was being asked to find semantics the pipeline had already shredded. Fix one: chunk on structure (sections, paragraphs), never on character counts, with enough overlap that no rule straddles a boundary. Exhibit B: dense-only retrieval, bimodal queries Fraud analyst queries split into two populations: pattern questions ("high-value order, new account, rushed shipping") and identifier questions ("what's the SOP for decline code 4863?", "rule VEL-013 rationale"). The system was dense-only — and embeddings treat a rare token like 4863 as noise, so identifier queries retrieved similar-feeling chunks instead of the literal match. Half the query population was structurally doomed regardless of model quality. Fix two: hybrid retrieval — BM25 for the identifiers, embeddings for the patterns, reciprocal rank fusion to merge. Exhibit C: nobody could see any of this, because quality was a rumor No golden dataset. No retrieval metric. The system's accuracy was whatever the loudest anecdote said it
开发者
5 Most Important Programming Languages to Learn in 2026 (Based on Real Industry Demand)
Every year, developers ask the same question: "Which programming language should I learn next?" And...
开发者
PyTorch `permute` vs `transpose`: What's the Difference (and the `reshape` Bug That Scrambles Your Images)
You loaded an image, got a tensor shaped (batch, height, width, channels) , and your convolution wants (batch, channels, height, width) . Stack Overflow says permute . Someone else says transpose . And reshape(2, 3, 28, 28) gives you the right shape too — so why is everyone making this complicated? Because two of those three are the same tool, and the third one silently destroys your data. The short answer transpose(dim0, dim1) swaps exactly two dimensions. permute(...) reorders all of them in one call, and you must list every dimension. transpose is a special case of permute . Both return a view — no data is copied, only the strides change — which also means both leave you with a non-contiguous tensor. reshape is not in this family at all. It reinterprets the flat memory under a new shape without moving anything, so it can produce the shape you asked for while completely scrambling what the numbers mean. import torch t = torch . arange ( 24 ). reshape ( 2 , 3 , 4 ) print ( t . transpose ( 0 , 1 ). shape ) # torch.Size([3, 2, 4]) — swapped dims 0 and 1 print ( t . permute ( 2 , 0 , 1 ). shape ) # torch.Size([4, 2, 3]) — full reorder transpose — swap two axes transpose(dim0, dim1) takes two dimension indices and swaps them. Everything else stays put. t = torch . arange ( 24 ). reshape ( 2 , 3 , 4 ) print ( t . shape ) # torch.Size([2, 3, 4]) print ( t . transpose ( 0 , 1 ). shape ) # torch.Size([3, 2, 4]) print ( t . transpose ( 1 , 2 ). shape ) # torch.Size([2, 4, 3]) The order of the two arguments doesn't matter — t.transpose(0, 1) and t.transpose(1, 0) are the same thing. A swap is a swap. On a 2-D tensor this is the matrix transpose you already know, and .T is the shorthand: m = torch . arange ( 6 ). reshape ( 2 , 3 ) print ( m . T . shape ) # torch.Size([3, 2]) print ( m . transpose ( 0 , 1 ). shape ) # torch.Size([3, 2]) — identical One caution on .T : on tensors with more than two dimensions, .T reverses every dimension, and modern PyTorch has deprecated that
AI 资讯
Why I created PyBotchi (v4.1.4)?
Hello Everyone, I'm the creator of PyBotchi, an intent-based AI Agent Orchestrator. In this post, I will discuss some key concepts why I created it. A little bit of background first. I'm a solutions architect with 10 years of experience as a software engineer. Most of my work are high throughput, high reliability, low cost and low latency services. This is while making it simple and readable to improve it's maintainabality. When I'm designing a system, I usually prioritize these concerns. You may assume this is my bias in relates to AI Agent building. I'm also Claude Certified Architect (Foundation) and I found that PyBotchi aligns almost identical to Anthropic's core agent recommendations. TL;DR: PyBotchi is an lightweight, async-first Python framework that uses nested Pydantic models and OOP inheritance to turn LLM intent detection into clean, deterministic business logic without the overhead of complex graph orchestration. Why I created PyBotchi? I really believed that traditional coding can already solved what client's need. The only limitations we have is how we read the input and how we show the output. In most cases in web services, your API use JSON, XML, etc with their respective specification/structure. Input Analogy Assume you have created a Books CRUD endpoints (FastAPI with Pydantic). Your create endpoint will have a define specifications for book creation to have a validation and avoid user errors. Most of the time you will also validates sessions and permissions which also included in the request. If you want your chat bot to support those, you just need add those endpoint as intent (tools). If your model tool selection are able to detect intents. You are more "close" to being deterministic. "Your services will have 50 endpoints or more. You will flood your tool selection call" In your frontend UI, you segregate panels/forms/inputs in their respective pages. You don't usually join multiple intent in a same page. Cluttered UI will make your UX confusin
开源项目
🔥 Emily2040 / seedance-2.0 - Comprehensive production pipeline for quad-modal AI filmmaki
GitHub热门项目 | Comprehensive production pipeline for quad-modal AI filmmaking with Seedance 2.0 | Stars: 5,846 | 101 stars today | 语言: Python
开源项目
🔥 ccxt / ccxt - A unified trading API with more than 100 crypto exchanges an
GitHub热门项目 | A unified trading API with more than 100 crypto exchanges and prediction markets in JavaScript / TypeScript / Python / C# / PHP / Go / Java | Stars: 43,480 | 17 stars today | 语言: Python
开源项目
🔥 Huanshere / VideoLingo - Netflix-level subtitle cutting, translation, alignment, and
GitHub热门项目 | Netflix-level subtitle cutting, translation, alignment, and even dubbing - one-click fully automated AI video subtitle team | Netflix级字幕切割、翻译、对齐、甚至加上配音,一键全自动视频搬运AI字幕组 | Stars: 18,012 | 48 stars today | 语言: Python