2026 5

Proving Code Works with Z3

At the PyCon SG Education Summit today, Melvin’s lighting talk on “Writing Proofs in Python” began with a subtle bug in this mid-point calculation (often used in binary search or sort) in languages like Java, C/C++, Go, etc. low = ... high = ... mid = (low + high) / 2 Since the integers are fixed-width, this triggers an overflow when low + high exceeds the maximum integer value. Even popular libraries like Pandas had this bug until 2019. In fact, even Python’s native list.sort() had this sort of bug until 2015! Read the details. ...

Sambar Styles

My wife’s sambar tastes different from my mother’s. And mine, too. When I cooked as a bachelor, my neighbour would pop by, taste the sambar, and exclaim, “Rasam super!” Surbhi’s Day 5 of the 30-day challenge was about Sambar which inspired me to take her dataset and create a decision tree for which state a sambar recipe is from based on its ingredients. ChatGPT started with 68 recipes and built a tree at 41% accuracy. As we added more recipes: ...

Things I Learned - 18 Jan 2026

This week, I learned: Vulture is a neat library that funds unused Python code. uvx vulture script.py works fairly well, out-of-box. This helps when cleaning up AI-edited scripts that often have left-over code or imports. One of the lightest alternatives to Google Analytics is GoatCounter. If you just want page views, referrers, browsers, OSes, countries, and devices, it’s great. It’s privacy-friendly (no cookies), open source, easy to self-host, free for small sites, and the data is exportable. The number of countries that allow visa-free entries to Indian passports is gently growing in Asia (Kazakhstan, Thailand, Sri Lanka, Malaysia, Iran, and Philippines). Lessons from performance books. Claude # # Summary: In early days, explore, sample. Then narrow based on interest & fit. Practice hard and persist. ⭐⭐⭐⭐ Range (David Epstein): In changing environments (rules shift, feedback is noisy/late), sample broadly, i.e. generalize. Specialization vs generalization Nobel laureates have more hobbies. Olympic athletes have less. Shift nurses have same hobbies as non-shift workers. Hobbies help expertise in some areas Rewarding ONLY what succeeds locks behavior, halts exploration. Vary / delay incentives. Reward AFTER figuring out what works. Reinforcement and rewards Maybe “orderly” people specialize and creative people generalize? So pick what aligns with personality? ⭐⭐⭐ Peak (Anders Ericsson & Robert Pool): Compounded practice at the edge of competence, with good immediate feedback, helps 14-26%. But talent (genetics, upbringing, brainpower) differentiates more the expert level. Slow, effortful practice (spaced recall, interleaving topics, self-testing) builds lasting knowledge - but looks inefficient and doesn’t help with exams. Learning and long-term retention “Easy” 10K hours don’t help. ⭐⭐ Grit (Angela Duckworth): predicts roughly the same as conscientiousness (18%). It predicts success in stable paths moderately (but brainpower, etc. matter too). But premature grit hurts. Quit if it helps. But environment can defeat grit. Lessons from attention economy books. Claude # # The attention economy is real. It is designed to capture our mind, and it is winning. Distractions hurt MUCH more than we think. Batching, focus time helps. Privilege helps. The rich have more control over these than the poor do. ⭐⭐⭐⭐ Deep Work (Cal Newport, 2016) and ⭐⭐⭐ Digital Minimalism (Cal Newport, 2019): control the tools. Focus time, digital detox, embrace boredom. This helps - when you can afford to. ⭐⭐⭐ Indistractable (Nir Eyal): control yourself. The problem is internal (also true), so build habits, since willpower depletes (hm… not really). ⭐⭐⭐ How to Do Nothing (Jenny Odell, 2019): reject. Embrace boredom as resistance. This helps - when you can afford to. ⭐⭐ Stolen Focus (Johann Hari, 2022): regulate & rebel. The problem is systemic and external (also true). Reclaim your interface. BTW: Goldfish have excellent attention spans and memory :-) Lessons from trauma books. Claude # # ⭐⭐⭐ The Body Keeps the Score (Bessel van der Kolk, 2014): trauma recall shuts down the speech area. Eye movement desensitization (EMDR) helps. So does CBT, despite what the book says. But does yoga (only a little) or neurofeedback (too little data)? ⭐⭐⭐ What Happened to You? (Bruce Perry & Oprah Winfrey, 2021): calming people down before talking. Strong connections help more than a therapist. ⭐⭐ The Myth of Normal (Gabor Maté, 2022): trauma causes cancer (no), autoimmunity (partly), ALS (?), etc. ⭐ It Didn’t Start with You (Mark Wolynn, 2016): maybe anxiety is epigenetic and heriditary? Unproven. Family Constellation Therapy is wrong ⭐⭐ My Grandmother’s Hands (Resmaa Menakem, 2017): maybe racism is a somatic (body) response to generational (epigenetic) trauma? Too little data ⭐⭐ No Bad Parts (Richard Schwartz): maybe we’re not one person but a collection of parts, and interviewing family systems (IFS) helps? Unclear ⭐⭐⭐ Maybe You Should Talk to Someone (Lori Gottlieb): our memory is unreliable and therapy is messy. Connection & compassion help Most of these are based on the contested Polyvagal Theory: the nervous system scans for danger before the mind can process it. But the specific claims of the theory are wrong and it makes no other falsifiable claims. The nervous system has hierarchical responses to threat. 🟢 Not unique to PVT Social connection regulates physiology. 🟢 Not unique to PVT Unconscious threat detection (neuroception). 🟡 Weak evidence Mamellian brain (ventral vagal system) is uniquely mammalian. 🔴 Lungfish have it Reptilian brain (dorsal vagal) “shutdown” causes dissociation. 🔴 No evidence RSA directly measures vagal tone. 🔴 Contested Reptiles are “asocial”. 🔴 Wrong Trauma causes body changes too. It’s not just the mind. Childhood trauma persists. Relationships (connection & compassion) help more than therapy What constitutes tax residency in India? For an Indian citizen, as I understand it (after 2 hours of research): If you were in India >= 182 days: Resident* Else, if you left India this year for employment: NRI. Else, if you are an Indian Citizen living abroad (visiting or not): If Indian Income <= ₹15 Lakhs: NRI. Else if you were in India >= 120 days AND >= 365 days in the last 4 years: RNOR. Else if you are not liable to tax in any other country: RNOR. Else, if you left India for non-employment (students, tourism) and were in India >= 60 days AND >= 365 days in the last 4 years: Resident* Else: NRI. If you ended up as a Resident* If you were NRI in 9 of the last 10 years OR in India <= 729 days in the last 7 years: RNOR Else: ROR (Resident & Ordinarily Resident). For all practical purposes, RNOR is like an NRI. You pay tax only on Indian income, not global income. It’s like a transition status for returning NRIs. AVIF compresses better than WebP and may be the “next big thing”. I will be switching for all future images. Squoosh remains my choice of compressor and Ezgif’s AVIF maker and GIF to AVIF are handy.

Finding open source bugs with Ty

Astral released Ty (Beta) last month. As a prototyper, I don’t type check much - it slows me down. But the few apps I shipped to production had bugs type checking could have caught. Plus, LLMs don’t get slowed by type checking. So I decided to check if Ty can spot real bugs in real code. I asked ChatGPT: Run ty (Astral’s new type checker) on a few popular Python packages’ source code, list the errors Ty reports (most of which may be false positives), and identify at least a few that are genuine bugs, not false positives. Write sample code or test case to demonstrate the bug. ...

Get this blog via email on Google Groups

TL;DR: Join this Google Group to get my blog updates via email. My blog is over 25 years old. At first, people had to visit it to read it. Then I added an RSS feeds. Then email subscriptions. Then via social media, cross-posting on Twitter, now LinkedIn. The RSS feed remains. But I feel it’s time to bring back email subscriptions. It’s the oldest of the technologies, the most robust, and the one I believe will last the longest. ...

2025 5

While meditating, I realized 75% of “LULL” is the letter “L”. (This sort of thing happens a lot when I meditate.) MUMMY (60% M) and DADDY (60% D) have lower percentage, but are longer, so maybe get a bonus? I asked Claude Code what would top such a list. It picked a dictionary, generated the 333 words with 4+ letters and >50% concentration. What did I like best? “ASSESSES”. 5/8 letters are “S”. That’s nearly two-thirds. ...

Reusable libraries

From a folder sym-linked to multiple projects, identify reusable libraries and functions. # Role and Objective - Analyze all .py, .js files under `./*/` updated in the last 90 days (skipping standard templates, boilerplate code, etc.) and update `./reuse.md` to: 1. Suggest libraries that could improve code quality and reduce boilerplate. 2. Identify reusable functions and opportunities for generalization. # Checklist Begin with a concise checklist (3-7 bullets) outlining your steps: - Enumerate all specified files under `./*/`. Note: directories under `./` are symlinks. - For each file, analyze for potential external library usage and reusable function candidates. - Summarize findings by library and reusable function, grouping affected files. - Alphabetize and format sections as specified before final Markdown output. - Validate that all files are processed. # Instructions - For each file: - Identify code that could be replaced with modern, popular libraries. - Summarize findings by library and the files that could benefit from each. - Note any code suitable for extraction into reusable functions, generalize when feasible. - Alphabetize libraries and functions in their respective sections. ## Sub-categories ### External Libraries - List each identified library (bulleted, alphabetized). - For each, sub-list the affected file(s) (bulleted, relative paths). ### Reusable Functions - For each reusable/generalized function (bulleted, alphabetized): - **Signature:** Provide as a Markdown code block. - **Docstring:** 1-line summary. - **Files Benefiting from This Function:** Bulleted list of relevant files. - **Library:** Markdown code block(s), indented. # Agentic Operation and Verification - Attempt an autonomous first pass using available information; escalate with a clarifying question only if ambiguities arise. - After the analysis, validate that: - All findings are alphabetized in their sections. - Every file is categorized. - Output matches the required Markdown structure and section order. - If success criteria are not met (e.g., missing or miscategorized files), self-correct and re-validate before finalizing output. # Output Format - All sections must be valid Markdown. - Use unordered (bulleted) lists. - Section order: 1. Checklist 2. External Libraries 3. Reusable Functions # Stop Conditions - Stop when the updated Markdown file comprehensively reflects all findings, in the correct format. - Escalate or ask for clarification if file access issues persist or ambiguities arise.

Things I Learned - 29 Jun 2025

This week, I learned: “People are great at feedback on what you are doing wrong. They are not so good at telling you how to fix it. They don’t know you that well.” Amit Kapoor Perfect Cursors makes periodic cursor positions animate smoothly by interpolating on a spline** CloudFlare and Vercel now support sandboxes where you can execute code. The price is not so low that we can execute for free in bulk but works well infrequent or batched code execution. Simon Willison Here’s how I’m using ffmpeg for video recording & editing. To record screen at 5 frames per second, I run an abbreviation screenrecord which maps to: Gemini CLI has a generous free tier and uses Bootstrap over Tailwind Ref #ai-coding Cloudflare has a native agents SDK that looks good, especially for CloudFlare users. Ref There are several brands with recognizable chart style guides. It’s possible to generate style guides for these from the charts, but applying them via matplotlib is almost #impossible today. ChatGPT Hyperfine is like %timeit for the shell. Written in Rust ⭐ Vertical AI is a moat against AGI. Specialization reduces hallucinations. Custom workflows and regulations are sticky and defensible. We need to start selling to users, not IT, though. Ref When AI automates a task, the bottleneck shifts. AI process re-design is about reworking the process around the new bottleneck, and iterating quickly. With coding, it’s testing, reviewing, deploying, use-case identification. uvx git-smart-squash re-organizes haphazard commits using LLMs. git-smart-squash #ai-coding GitHub offers a free Docker container registry. Simon Willison There are three major areas where humans either are, or will soon be, more necessary than ever: trust, integration and taste – NYT. Anil. To deal with this: Learn things that might grow in importance, like: Data modeling APIs Code reviews Drawing and 3D modeling Narrative storytelling Design Movie making Statistics Sceptical fact checking Continuous AI auditing e.g. awesome-continous-ai or automated-auditing Zero knowledge proofs Homomorphic encryption Privacy-preserving computation Fingerprinting and watermarking Governance frameworks Ethics and AI dilemmas Negotiation Change management Remote working, management, hiring Creating attention scarcity Local cultures Work with people of growing importance People designing products in regulated industries Cross domain experts Art developers, game makers, designers System thinkers. Economists, ecologists, system planners. People who look for second order effects. Live in cities that might play a bigger role in the future Cities like Singapore and learn how it builds civics trust, creates digital IDs. Cities like Bangalore and Hyderabad and learn how they grow tech talent Creative cities like Paris, Seoul, Mexico City, Berlin, etc. on sabbaticals to taste hubs Try to: Build auditing credentials and IP Audit your calendar for what AI can do. Have it interview you Practice sceptical fact checking and audit A clever way to test a library’s quality is to have LLMs write code from docs and test it. Failing libraries have flawed code/docs. Improve. Ref #ai-coding Common Pile is an 8TB open dataset for LLM training that includes ArXiv, PubMed, StackExchange, GitHub, IRC, Regulations.gov, Patents, UK parliament, books. Easier than scraping. A useful way to have reasoning models do deep-research-like work is to have them “First, create a plan to solve the problem, clearly listing the objective, approach, and output. Then follow the plan.” DE-COP is a method to check if LLMs were trained on private content. GPT-4o was trained on O’Reilly books, based on this method. Ref LLMs are more persuasive than humans. But repeated exposure reduces the effect. Ref Phoenix.new uses live views to publish apps as it codes. The testing framework looks at the screen while it codes and fixes errors. It commits every change Anthropic system prompt asking Claude to pursue its goals led to self preservation behavior. Ref The hungrier I am the better the food tastes. A good reason to eat less quantity and frequency You can purge the jsDelivr cache manually. Helps if you released a new version of a package and way to purge an alias (e.g. https://cdn.jsdelivr.net/npm/your-package@1) XConvert is a convenient online app to compress .webm videos. Not great design but fairly good compression. You can draw a treemap of import times via python -X importtime app.py > timing.txt and then paste them at https://kmichel.github.io/python-importtime-graph/. PyOpenLayers adds interactive mapping via OpenLayers to Marimo and Jupyter. In a TechCrunch interview with Jared Kaplan has was asked if Anthropic is becoming less safety conscious because they released Opus 4 which blackmails. Kaplan replied that they have stronger testing and higher transparency, so they’re more likely to share AI dangers early. Great positioning! Conversations are about perspective change and this nailed it. The system prompts for Anthropic misalignment evals are a fascinating read. AI PR Watcher tracks GitHub pull requests from Codex and other LLMs. Codex is way ahead of anything else on volume and success rate. Devin is next on volume, Cursor is next on success rate.

Things I Learned - 27 Apr 2025

This week, I learned: OpenAI’s reasoning models are much ahead of other models when multiplying two numbers in their heads. Ref ⭐ Promptfoo may be the most mature open source LLM evals tool. Simon Willison Dyson Sphere. LemonSlice showcases real-time audio-video models (avatars) that are close enough to real. Notes from Latent Space ICLR 2025, Singapore Daniel: Menlo’s ReZero. A model that keeps searching till it finds the answer. There are multiple search techniques: Multi-step retreival, Iterative retrieval, Query rewriting. Also, reasoning. The LLM token generation sequence is normally: <think>, <search>, <answer>. Insight: “If we explicitly reward LLMs for retrying after a failed search, they out-perform one-attempt systems.” So <think>, <search>, <think>, <search>, <think>, <search>, <answer>. ⭐ Prompt reasoning models, e.g. “Keep searching till you find the best answer.” Roger, Nous Research Supervised learning is limited because accuracy is piece-wise linear, i.e. it’s broken up. Continuous optimization is meaningless. Reinforcement learning works better because rewards can be discrete. (But it converts things back into differentiable loss functions behind the scenes.) Rewards can be good/bad. Single or multi-step. Whatever. We’re in the “Era of experience”, i.e. models gain experience from the environment themselves. ⭐ So, we need environments models can learn in. This is the next thing after training data. That needs a standard for environments. We’d need a model, a trainer, and the environment. The environments whatever capabilities. Run code. Browser. A game. … With an exposed interface Eugene Cheah (Featherless.ai) Transformer architectures need n-square GPUs as # of tokens grow. Featherless is exploring an RWKV architecture that scales linearly. THere are other such architectures. Performer, Linformer, Reformer, Hyena. Mistral-Nemo-12b-ic is one of the most popular fine-tuned model. It’s small enough to run on a server. Justus Mattern (Prime Intellect) Intellect-2 is a continously learning (RL) model that uses decentralized training on peer-to-peer GPUs. Solving problems on bandwidth, verifiable contributions, etc. ChatGPT Deep Research now also has an O4-Mini version to serve smaller reports. Free users get 0 original + 5 lightweight 5 tasks / month. $20 version gets 10 + 15. $200 version gets 100 + 150. The month begins on first use of Deep Research and runs on a 30 day “window”. Ref O4-Mini-High is great at going through an under-documented repo and finding things. For example, here’s how I configured cmdg. ChatGPT is my new Jupyter Notebook :-) Google announced new AI capabilities at Google Next APAC 2025. Blog. Interesting ones are: @Gemini in chat Google Meet support for “Catch me up” Google Vids: Create short video clips Google Sheets: does better analysis Google Slides: image generation Google Docs: Create Audio Clips (like NotebookLM in Google Docs) Google Docs: “Help me refine” is better than before Google Workspace Flows gcalcli is a convenient way to export Google Calendar. Example: uvx gcalcli agenda --tsv 2025-01-01 2025-01-05 cmdg is a command line GMail client that I’ve now switched to for quick email checks. 80% of my email is spam and this is good enough to scan and delete those. It also avoids running a 200-500 MB tab in the browser that constantly shows me how many unread emails I have. From Worklife with Adam Grant: Cancelling cancel culture with Loretta Ross “Lighten up! Fighting Nazis should be fun. It’s being a Nazi that sucks. If you’re not having fun fighting for hope and joy and human rights, maybe you’re doing the fight wrong. We are the ones who should be having fun.” “You can say what you mean. But you don’t have to say it mean.” There is always a way to put it across better. Refusing to say mean things is about to discover these approaches. “The true mark of a lifelong learner is knowing that you can learn something from every single person you meet.” If you remember that, you can’t be a know it all. semantic-text-splitter could be the go-to text splitter. It’s Rust-based, supports MarkdownSplitter, and multiple tokenizers. Alternatives like semchunk, advanced-chunker, chonkie, etc. seem clunkier. ULID is like UUID but time-sortable. That’s an improvement over timestamp IDs (definitely) and potentially even UUIDs. They can be generated by clients as a globally unique ID. Try pip install python-ulid and npm install ulid. The Consumer Product Safety Commission Data has thousands of reports of product safety over time You can run xclip -sel clip -o | pandoc -f markdown -t html --no-highlight | xclip -sel clip -t text/html -i to convert Markdown in the clipboard to rich text. But xclip doesn’t support multiple selections, so the text is lost. ChatGPT DuckDB UI & Notebooks will potentially be a good alternative to Datasette, DBeaver, etc. But for now, there are still glitches. It crashes with a SIGSEGV (Address boundary error) when connecting to SQLite databases. Ollama limits MAX_TOKENS to 2K by default. AI assisted search helps wherever I would have used Google, e.g. Debugging. “Fix CUDA initialization: CUDA unknown error” Tool search. “Find an online word counter tool.” Library search. “Find a JS micro library to render Markdown.” OpenAI API capabilites lag ChatGPT features. For example: o4-mini via the API does not search the web natively as part of its reasoning. o4-mini, o3, o3-mini, o1, gpt-4.1-nano don’t yet support the web_search_preview tool. Only gpt-4.1 and gpt-4.1-mini do. Limitations Search results are NOT visible via the API. They’re fed directly to the model. The number of searches or results is unknown. Each search costs 0.25-0.5 cents. Pricing For reasoning traces (e.g. .reasoning.summary: "medium") you need to verify your organization via withpersona.com which failed with my Indian passport AND Singapore work permit. The ChatGPT Plus plan ($20) gives you 50 O4 mini messages a day, which I exceeded! It’s supposed to reset at midnight UTC Ref but might operate on a rolling window ChatGPT. “Currently, there is no way to check how many messages you have used in your usage budget.” OpenAI SignalBloom reads SEC filings and writes analyst reports on it using LLMs “Evaluation in the loop” or “Evals-in-the-loop” is a new term I learnt. SignalBloom’s Hallucination Bechmark If AI interacts with the world and generates data from its own experience and learns from that, we have a new scaling mechanism. DeepMind podcast OpenAI’s search API is fairly expensive at $30+/1K calls. Typically, to read interesting HN articles, I will make 30 calls which is about 75c. Instead I should use the app and summarise HM news across different days manually based on my interests! Finally! t-strings land in Python. They’re like JavaScript template literals. DuckDB’s CSV parser might be one of the most forgiving parsers. Even better than Pandas or SQLite3. Ref Good managers will probably make good AI managers. AI agents can probably substitute humans in business experiments. Ethan Mollick If Windsurf stops working, reload the extension. GitHub TLS certificates will start expiring in 47 days from 15 Mar 2029, forcing automated domain renewals. Digicert Nix flakes are a reliable alternative to DevContainers that don’t need Docker - but don’t work on Windows. Ink is like React for the CLI. The Unsure Calculator is a great tool to calculate formulas with multiple uncertainties, like: My office is 9-11 km away and it takes me 45-55 min to reach. So I cycle at 9~11 / 45~55 * 60 ~ 10-14 kmph (12 most likely). I spend $6-15 on lunch and eat out 80-120 days a year. So I spend 6~15 * 80~120 ~ $600~1550 ($1000 most likely) eating out yearly. I take 30-120 min to prepare a quiz question. Each exam has 6-12 questions. So I need 30~120 * 6~12 / 60 = 4~20 hours (11 most likely) Using Kiran’s macOS setup for dev I enabled colorized less and mouse options for tmux. time fish -i -c exit prints the time taken for fish startup. fish --profile-startup ~/fish.profile -i -c exit prints the time taken by each command on fish startup to ~/fish.profile. I used this to speed up my fish startup. The 8 top features of the OpenAI Responses API that are an improvement over the Completions API (IMHO) are: Link to previous response rather than sending history Uploading files directly Swappable system instructions while retaining the chat history Customisable reasoning effort AND reasoning summary detail Truncation in the middle option Web search context size option File search filters by file attributes Flex service tier for lower cost OpenAI doesn’t charge for file storage but does charge 10 cents / GB-day for vector storage beyond 1 GB. The first 1GB is free Augment Code is an AI code editor that’s growing popular on Reddit. #ai-coding The GPT 4.1 models have a 75% discounted prompt caching (instead of the usual 50%), making them particularly suited for repetitive tasks. OpenAI chatgpt.com shortcut keys are revealed via Ctrl + /. Here’s my ranking on usefulness: Ctrl + Shift + C: Copy last response as Markdown! Ctrl + Shift + ;: Copy last code block Ctrl + Shift + S: Sidebar toggle Ctrl + Shift + O: Open new chat Shift + Esc: Focus chat input Ctrl + Shift + I: Ccustom instructions Ctrl + Shift + X: Delete chat

Things I Learned - 02 Mar 2025

This week, I learned: Proxmox Virtual Environment is an open-source alternative to VMWare, Hyper-V, Citrix XenServer, etc. (There’s nothing there that prompts me to explore it further.) With Podman on Windows (a Docker equivalent), many Docker-enabled tasks become easier. For example, running PostgreSQL is as easy as: podman run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:latest podman exec -it postgres psql -U postgres -c "CREATE DATABASE mydb;" Bad deep research prompts are: vague/broad, under-specified or ambiguous. In short, the more you know what you want, the better. Iterate until then. What kind of reports do clients are research companies to produce? I was curious to see if Deep Research can replace these. Here are a bunch of ideas. ChatGPT Strategy & Management Consulting Research (McKinsey & Company, Boston Consulting Group, Bain & Company, Strategy&, Accenture Strategy) Produce a comprehensive strategic transformation report for a Fortune 500 consumer goods company. Analyze global market trends, competitor strategies, and actionable growth recommendations, including case studies and source citations. Generate an in‐depth study on corporate restructuring trends in emerging markets. Focus on successful turnaround strategies, CEO leadership factors, and strategic pivots, with a comparative analysis of key players. Create a report on M&A trends in the technology sector over the past five years. Detail deal drivers, integration best practices, and forecast future acquisition opportunities, citing relevant data. IT & Technology Research Analysts (Gartner, Forrester Research, IDC, 451 Research, Ovum) Produce a market assessment report on emerging cloud computing platforms. Include vendor evaluations, adoption forecasts, and key technology drivers with supporting data and charts. Generate an in‐depth cybersecurity trends report for enterprise IT. Analyze recent threat vectors, defense strategies, and best practices for risk mitigation, providing actionable recommendations. Create a comprehensive study on the impact of artificial intelligence in enterprise software. Include competitive benchmarking, technology adoption rates, and forecasted market changes. Marketing & Consumer Research (Nielsen, Kantar Group, Ipsos, GfK, Euromonitor International) Produce a consumer behavior analysis report for a leading retail brand. Identify key demographic shifts, purchasing trends, and brand loyalty factors, and provide actionable insights with data visualizations. Generate a detailed report on digital media consumption trends among millennials, incorporating survey results, social media analytics, and case studies of successful campaigns. Create a market segmentation report for a new consumer electronics launch. Identify key consumer segments, behavioral drivers, and media usage patterns with clear recommendations. Financial Investment Research (Goldman Sachs, JPMorgan Chase, Morgan Stanley, Morningstar, Keefe Bruyette & Woods) Produce an equity research report on mid-cap technology stocks. Include detailed financial modeling, valuation analysis, and buy/sell/hold recommendations with supporting data and charts. Generate a fixed income analysis report for corporate bonds in the industrial sector. Assess credit risk, yield forecasts, and macroeconomic influences, citing key data sources. Create a comprehensive report on global market trends impacting investment banking. Analyze regulatory changes, market sentiment, and performance metrics of leading financial institutions. Healthcare Research (IQVIA, Frost & Sullivan, Evaluate Ltd, Deloitte Healthcare, IMS Health) Produce a market analysis report on emerging biotechnologies in oncology. Include competitive landscape, regulatory challenges, and growth forecasts with relevant case studies. Generate a comprehensive report on patient satisfaction and telemedicine adoption trends. Analyze survey data from leading healthcare providers and benchmark best practices. Create a detailed study on pharmaceutical market dynamics in emerging economies. Focus on pipeline developments, regulatory environments, and market potential with actionable insights. Legal Research Providers (LexisNexis, Westlaw, Bloomberg Law, Fastcase) Produce a legal risk assessment report on the impact of recent data privacy regulations for multinational corporations. Include case studies, trend analysis (2019–2024), and strategic recommendations. Generate a comprehensive report summarizing key federal and Supreme Court rulings on intellectual property rights over the past five years, highlighting trends and divergent interpretations. Create a detailed report on the evolution of securities law and its effect on investment research practices, incorporating analysis of recent litigation and regulatory updates. Media & News Research (Factiva, Kantar Media, Comscore, Cision) Produce a media consumption trends report that analyzes audience behavior shifts across digital, TV, and print platforms. Include data visualizations, key drivers, and forecasted trends. Generate a comprehensive report on the impact of social media on traditional news reporting, with case studies and a comparative analysis of engagement metrics. Create a detailed study on the effectiveness of multimedia advertising campaigns, evaluating ROI, consumer engagement, and best practices with actionable insights. Economic & Industry-Specific Research (Economist Intelligence Unit, BMI Research, IHS Markit, Consensus Economics) Produce a macroeconomic outlook report for emerging markets, including GDP, inflation, and employment forecasts, with detailed data analysis and visualizations. Generate an industry analysis report on the automotive sector, covering technological innovations, competitive dynamics, and consolidation trends. Create a comprehensive country risk assessment report for a target region, detailing political, economic, and regulatory factors with recommendations for investors. Human Resources & Employee Engagement Research (Gallup, Great Place to Work, Mercer) Produce an employee engagement report for a multinational firm based on recent survey data. Identify key drivers of satisfaction, retention challenges, and improvement recommendations. Generate a comprehensive study on the impact of remote and hybrid work models on employee productivity across industries, including best practices and benchmark data. Create a detailed report on workplace culture transformation, analyzing organizational behavior trends, employee feedback, and actionable strategies to boost engagement. Environmental, Social & Governance (ESG) Research (MSCI ESG Research, Sustainalytics, ISS ESG, Bloomberg ESG) Produce an ESG performance report for a portfolio of global companies. Include sustainability scores, risk assessments, and recommendations for improvement with data visualizations. Generate a comprehensive study on the impact of climate change regulations on the energy sector, including policy analysis, market forecasts, and strategic implications. Create a detailed report on corporate social responsibility trends in the consumer goods industry, incorporating qualitative and quantitative analyses with actionable recommendations. Education & Academic Research (RAND Corporation, National Center for Education Statistics, HolonIQ) Produce an analysis report on the future of online education, examining technological adoption, market growth projections, and student outcome trends with supporting data. Generate a comprehensive study on the effects of educational policy reforms on public school performance in the U.S., including trend analysis and actionable recommendations. Create a detailed international higher education trends report, covering tuition dynamics, international student mobility, and emerging academic programs with comparative data. Real Estate & Property Research (CBRE, JLL, CoStar Group, Cushman & Wakefield) Produce a commercial real estate market analysis report for major urban centers, including occupancy trends, rental rate forecasts, and investment opportunity assessments. Generate a comprehensive study on residential housing market dynamics in emerging economies, focusing on affordability, supply-demand gaps, and policy impacts. Create a detailed report on the impact of urban redevelopment projects on local real estate values, including case studies, forecasts, and strategic recommendations. Energy & Natural Resources Research (Wood Mackenzie, Rystad Energy, Bloomberg New Energy Finance) Produce an analysis report on global renewable energy trends, covering technology adoption, market forecasts, and key policy drivers, with detailed data and visuals. Generate a comprehensive commodity price forecasting report for oil, natural gas, and key metals, incorporating historical trends, risk assessments, and predictive modeling. Create a detailed report on energy transition strategies for traditional energy companies, focusing on clean technology investments and market adaptation strategies. Supply Chain & Logistics Research (ARC Advisory Group, Gartner Supply Chain Research, Supply Chain Insights) Produce a report on supply chain resilience for global manufacturers. Analyze risk factors, digital transformation impacts, and best practices for operational efficiency with supporting data. Generate a comprehensive study on the impact of technology on logistics networks, including case studies on digital optimization and cost reduction strategies. Create a detailed report on emerging last-mile delivery solutions, assessing innovations, consumer expectations, and scalability with actionable insights. Cybersecurity & Information Security Research (KuppingerCole, Forrester Security, IDC Cybersecurity, Cybersecurity Ventures) Produce an in-depth report on emerging cybersecurity threats for large enterprises, including detailed analysis of recent incidents, risk vectors, and defense strategies. Generate a comprehensive cybersecurity market landscape report, evaluating vendor performance, technology forecasts, and best practices for mitigating risks. Create a detailed report on regulatory compliance trends in information security within the financial services industry, with case studies and strategic recommendations. Social Media, Digital & Online Research (Comscore, SimilarWeb, Brandwatch) Produce a digital audience behavior report for a global brand, focusing on social media trends, engagement metrics, and platform performance with detailed data analysis. Generate a comprehensive analysis of influencer marketing effectiveness across digital channels, including ROI metrics, case studies, and best practices. Create a detailed report on online brand sentiment analysis, incorporating social listening data, trend forecasts, and actionable recommendations. Public Opinion & Political Research (Pew Research Center, Gallup, YouGov) Produce a public opinion polling report on voter sentiment ahead of a major election. Include demographic breakdowns, key issue analysis, and trend visualizations for the past five years. Generate a comprehensive study on political risk in emerging markets, analyzing historical data, current trends, and future projections, with policy recommendations. Create a detailed report on the influence of media on public policy, using survey data, social media analysis, and comparative case studies. Sports, Entertainment & Media Research (Nielsen Sports, Sportcal, Kantar Media Sports) Produce a market analysis report on sports sponsorship trends, detailing viewership metrics, brand engagement, and investment ROI with industry case studies. Generate a comprehensive report on audience behavior in the streaming media industry, including demographic insights, consumption trends, and competitive benchmarks. Create a detailed analysis of digital advertising effectiveness in the entertainment sector, including segmentation data, ROI analysis, and strategic recommendations. Innovation, R&D & Technology Trends Research (Innosight, Frost & Sullivan Innovation, CB Insights) Produce a global R&D investment trends report, analyzing technology spending, innovation indices, and the impact on market growth across key industries. Generate a comprehensive study on disruptive technologies in manufacturing, including competitive analysis, market potential forecasts, and adoption trends. Create a detailed report on emerging innovation hubs worldwide, focusing on startup ecosystems, funding trends, and collaborative opportunities in technology. Agriculture & Agribusiness Research (Rabobank Agribusiness Research, USDA Economic Research Service, AgFunder) Produce an analysis report on global agricultural market trends, including crop yield forecasts, trade dynamics, and policy impacts, with data visualizations. Generate a comprehensive study on agritech innovations such as precision farming and sustainable practices, including case studies and market forecasts. Create a detailed report on the impact of climate change on food production and supply chain stability in agribusiness, with risk assessments and strategic recommendations. Environmental & Climate Change Research (Carbon Trust, IHS Markit Energy Transition, Bloomberg New Energy Finance) Produce a report on the economic and social impacts of climate change on urban infrastructure, including forecasting models and policy recommendations. Generate a comprehensive study on national climate policies and their effects on industrial competitiveness, with detailed trend analysis and source citations. Create a detailed report on corporate sustainability initiatives, assessing environmental risk management practices and providing actionable recommendations for improvement. Customer Experience (CX) & User Experience (UX) Research (Forrester CX Research, Gartner CX Research, Qualtrics, Nielsen Norman Group) Produce a report on customer journey mapping for a leading retail brand, identifying key touchpoints, pain points, and actionable improvement strategies with data visualizations. Generate a comprehensive study on digital user experience trends for e-commerce platforms, including usability testing insights, design best practices, and conversion optimization recommendations. Create a detailed report on customer satisfaction and loyalty metrics across multiple industries, integrating survey data and actionable recommendations to enhance overall CX. Blockchain, Cryptocurrency & Fintech Research (Chainalysis, CoinDesk Research, Deloitte Fintech Research, CB Insights) Produce an analysis report on emerging blockchain technologies and their applications in financial services, including market trends, adoption forecasts, and case studies. Generate a comprehensive study on cryptocurrency market dynamics, analyzing regulatory developments, investor sentiment, and competitive landscapes with source citations. Create a detailed report on fintech disruption in traditional banking, with case studies on leading startups, technology adoption, and future market forecasts. Venture Capital, Startup & Private Equity Research (PitchBook, CB Insights, Crunchbase, Preqin) Produce a global venture capital investment trends report, including performance analysis of high-growth startups, sector benchmarks, and emerging market opportunities. Generate a comprehensive study on private equity market dynamics, covering deal flow analysis, exit strategies, and forecasted trends with supporting data. Create a detailed report on emerging startup ecosystems in key regions, highlighting funding trends, investor activity, and growth potential with actionable insights. Operations Research & Management Science Consulting (The Brattle Group, NERA Economic Consulting, CRA International) Produce a report on optimization techniques for operational efficiency in large-scale manufacturing, including quantitative analysis, simulation models, and case studies. Generate a comprehensive study on the application of predictive analytics in supply chain management, focusing on data modeling, process improvements, and actionable insights. Create a detailed report on advanced quantitative modeling approaches to solve complex business problems in logistics and operations, including scenario analysis and recommendations. Cultural & Social Research (Ethnographic/Sociocultural Studies) (Ipsos MORI, Kantar TNS, YouGov) Produce a qualitative ethnographic study on urban consumer lifestyle trends, incorporating field observations, interviews, and cultural analysis with actionable insights. Generate a comprehensive study on how cultural shifts influence global brand perception, including comparative case studies and trend analysis. Create a detailed report on sociocultural dynamics and consumer behavior in emerging economies, integrating in-depth field research and actionable recommendations. Economic & Demographic Research Firms (Oxford Economics, The Conference Board, CEIC Data) Produce a macroeconomic forecasting report for a specific region, including GDP, inflation, and employment trends with detailed data visualizations and source citations. Generate a detailed demographic analysis report for a target market, highlighting age distribution, income levels, and consumption patterns with actionable insights. Create a comprehensive report on the economic impact of demographic shifts on consumer markets, with policy recommendations and trend analysis. Academic & Think Tank Research Organizations (Brookings Institution, RAND Corporation, Carnegie Endowment for International Peace) Produce a policy research report on global governance challenges and their implications for economic development, including case studies, literature reviews, and expert interviews. Generate a comprehensive study on social inequality and its effects on public health and education outcomes, supported by empirical research and trend analysis. Create a detailed report on emerging trends in international relations and their impact on global trade and security, integrating academic research and data analytics. Market Research Technology & Software Providers (Qualtrics, SurveyMonkey, Confirmit) Produce a report on the latest innovations in survey technology and data analytics software for market research, including product comparisons, user case studies, and future trend forecasts. Generate a comprehensive study on the integration of AI and machine learning in consumer insights platforms, highlighting case studies, performance metrics, and industry benchmarks. Create a detailed report on digital transformation trends in market research technology, featuring analysis of leading software solutions, market share data, and recommendations for technology adoption. When evaluating inputs, models tend to prefer the first response, prefer their own response, and prefer longer responses. ThursdAI Real-time speech-to-text options for transcription: Deepgram has a MediaRecorder API, which is perfect. Whisper Streaming Web is a web app that can transcribe audio real-time from the browser. A good approach, but I wouldn’t use it for meeting transcription on my mid-end laptop. Streaming takes up the bulk of my GPU, leaving little for transcription. whisper-live runs as a Python console app and does something similar. Whisper WebGPU runs on the browser (only 200MB). Cool! But slow and still takes up GPU. Mini-omni is an open-source Qwen-based LLM that can hear and talk while thinking in real-time. An interesting experiment, but not for prototyping. OpenAI shares an insights report with clients that has insights on what different professions search for. What doctors search for is: Is my diagnosis right? How do I read this report? Is my prescription correct? Is there a cheaper medicine? What’s the life expectancy given these symptoms? Dataclasses in Python have a slight overhead over named tuples. The 2 main uses I see for them are: providing defaults and offering type hints. UVB 76 is a radio channel has been broadcasting static (with occasional Russian conversation) since 1976. No one knows why. It’s live at https://m.youtube.com/watch?v=8h_D2P0iqMk Romans washed clothes in urine. The government taxed the purchase of urine for commercial purposes! That’s the origin of the phrase “Pecunia non olet” which means “money doesn’t stink”. Nix is a package manager that creates container-like environments. Like a cross between Docker and apt / venv. It has an immutable file system. DevBox is a higher-level tool built on top of Nix that streamlines developer workflows, e.g. common project environment setup. VS Code can be used to develop inside a Docker container via Podman, too. Set dev.containers.dockerPath": "podman" Ref Rill Data is an interesting BI tool based on DuckDB. It auto-generates a dashboard given a dataset. It’s possible to assign “variables” in SQL (notably in DuckDB). Here’s an example: WITH sessions AS (FROM events SELECT COUNT(DISTINCT session_id) AS value), pages AS (FROM events SELECT COUNT(*) AS value) FROM sessions, pages SELECT sessions.value / pages.value AS pages_per_session; DuckDB has a GROUP BY * that groups by all categorical columns. SELECT x, y, COUNT(*) FROM t GROUP BY * is equivalent to SELECT x, y, COUNT(*) FROM t GROUP BY x, y. VS Code can be used as a code executor by adding {"key": "shift+enter", "command": "workbench.action.terminal.runSelectedText", "when": "editorFocus"} to the keybindings.json file. Press Shift-Enter to run the selection on the terminal. Useful for DuckDB, SQLite, etc. Ref LLMs are excellent at database migration. They can convert schemas and queries across SQL dialects (e.g. BigQuery to DuckDB, etc.) at 90%+ accuracy. This is useful when clients want to migrate cloud providers, go from on-prem to cloud, or reduce cost by switching databases.

2024 4

Perl, 1994-2011

In 1994, I learnt Perl. It was fantastic. I used it to: 1995: Build CCChat - the unofficial IITM email system and software repository 1999: Build my entire blog from scratch 2000: Author my 2nd year thesis on the Behavioural Aspects of Financial Analysts by analyzing 600MB of IBES data 2002: Analyze where to place the central processing hubs for a bank 2004: Analyze the interest durations of public sector banks 2005: Creating music quizzes 2006: Create my own music search engine (which earned me about $100 a month in Google Ad revenue for a while) 2006: Automated resume filtering 2007: Create custom search engines 2008: Build application launchers In 2006, I was convinced I should stick to Perl over Python. ...

Things I Learned - 09 Jun 2024

This week, I learned: httpretty can mock ALL Python HTTP libraries Japanese pray to dead parents instead of gods. The dead are preserved in plates by priests. Japanese are generally non religious Looks like GPT-4o is using CNNs to create vector embeddings of images, with images gridded into a 1x1, 2x2, etc. PLUS OCR. Ref The sum of a sinusoidal series is like a spirogram. Spinning circle linked to another and so on https://www.andreinc.net/2024/04/24/from-the-circle-to-epicycles

Things I Learned - 18 Feb 2024

This week, I learned: Fine tuning makes economic sense only if the input tokens SAVED is twice the output token size on each call. Docker container memory usage on WSL2 docker stats frolvlad/alpine-glibc:alpine-3.17: 540KB ubuntu: 1MB (python3: +5MB) nikolaik/python-nodejs:python3.10-nodejs18-bullseye: 1.4MB (python3: +5MB) python:3-alpine: 612KB (python3: +7.5MB) python:3: 500KB (python3: +11.2MB) continuumio/miniconda3: 7.6MB (+6.5MB) Discussion with Vinu Yamunan Databuck by FirstEigen. Autolysis plus monitoring Quality council has the data steward (maintainer of each dataset) coming together with the uses on a weekly basis to understand what quality problems to users are facing. Data owners jaundice at a lower frequency to get an understanding #TODO Automate rules for data quality in our projects and intranet Convert a config rule into business language. Explain SQL. These are good use cases for llm’s Graph DBs are powerful for flexible data structures, but query generation needs AI or expertise. Check the Neo4J language cypher Explore storing SAME data in relational DBs AND in graph DBs / document DBs for different use cases Dallas rocketry challenge. Build a rocket that can take an egg to 800 feet exactly and land without breaking it Discussion with Karthik A #TODO Ask IIT students to do internship tasks. Use advent of code is a qualifying criterion Tata motors unionized DB admins for longevity. No one can take their jobs. Hires people who LIKE their jobs Rust gives me typing. It’s very efficient. Pola.rs is interesting but Pandas as good enough. Explore alerts from CCTV feeds. Karthik sends email alerts with pictures for: “Is the machine on or off”? for productivity “Are people not wearing helmets?” for safety at Cummins #TODO Integrate with WhatsApp. Use LLMs with function calling for responses Use expiring links (to pictures or content). It increases engagement Check Deno licensing. Is there a commercial clause? #ANS No - it’s MIT license Centre or excellence for zero emission tech at IIT. Karthik is part of it Explore auth0. 7000 users are free toml is part of the Python 3.11 standard library! If copilot writes code we don’t understand we are screwed. Hence expertise matters Discussion with Vikas Kedia #TODO Plan an AMA The mind becomes lazy with financial success. Vikas is treating his podcast as a startup Hire a professional videographer for your content Financial RoI in financial markets is the highest. Programming is high too but FS is even better “Performative power” – when you’re forced to perform, you get better ideas Observable 2.0 is an open source static site generator for data Python dataclasses SORA is OpenAI’s video generation model, and is stunning! If Appa comes to Singapore even for a week, he will feel better and can boast to his friends. At over 90, it may be better to move Appa to where I am since many of his friends would be no more and shops, doctors, etc can be managed and getting an independent house nearby is not hard. There is an SEZ in Gujarat where Indians can invest like in Mauritius without forex restraint Shubha: Media sites are moving away from Vickrey auctions to first-price auctions for ads. That’s because they send the auction price forward to a search engine and the winning second-price value can lose even though the owner is willing to pay more. Second-price auctions don’t work unless ALL bidders are in the SAME auction. Ad networks are a hierarchy of auctions! Gemini 1.5 launched. Fly.io offers GPU hosting and auto stop when they have nothing to do. Embeddings in random forest are very effective at classification – much better than dot product. To deploy apps with OAuth + templating support in a small Docker container, use Caddy Deno has native TypeScript, browser APIs, and compiles to multiple OSs Ruff is a MUCH faster flake8 Two pass generation is a clever technique to get multiple SEQUENTIAL answers in a single API request. For example the schema {'code', 'optimized_code'} will generate code and then optimize it. Unions in function calling allows flexible multi-step prompts in a single API.

Things I Learned - 14 Jan 2024

This week, I learned: Transparent LED screens will be useful in windshieds to display maps as we drive. Marimo is a reactive alternative to Jupyter notebooks that saves files as pure Python. To run an org-specific chatbot on your own LLM: (via awesome-chatgpt) opengpts - but it doesn’t support auth chatbot-ui - but Supabase is hard to install anse - but it doesn’t support auth ChatGPT-Next-Web - but it doesn’t support auth Python 3.13 gets a store and copy JIT If an npm package adds another package as a dependency with version “*”, target package cannot unpublish ANY version! So this is a way of freezing EVERY repo and preventing unpublishing of EVERY version – an unintentional flaw in the npm design. via Quantization is better than fewer parameters. So prefer high parameters (e.g. 70b) and quantize to 4-bit. In-browser playgrounds has compiled WASM versions of Python, PHP, SQLite. Happiness Lab podcast. Happiness lessons of the ancients Talking to strangers makes us happy Giving money makes us happy Free time makes us happier than working hard Tangi Domain-specific models being beaten by general purpose models is a phase. It will reverse towards domain. AI will potentially help build and understand domain-specific models Models are evolving so rapidly that humans cannot interpret models. We need a process to interpret models! xAI, Responsible AI, Physics-guided or Knowledge-guided models (called grey box models) are therefore a trend CS papers Don’t review other papers, certainly not other fields. Disregard measurement errors. When CS papers get applied to climate, manufacturing or biology, we’ll worry about Interpretability Domain-specific mechanics. (Introduce that into the training as a constraint.) Many domain experts are using AI to UNDERSTAND their process. Need to explore Uncertainty IB adds context to make learning applicable. But that distracts from the core learning, and if there’s a gap it widens Most data science courses teach “Python science”, not data science. They teach a bunch of models. They don’t teach how even one kind of model e.g. LSTM works. Most coaching programs today teach FAMILIARITY with problems, not critical thinking Most of current education will become redundant thanks to LLMs. For students AND teachers Coding will become irrelevant Cognitive thinking, reasoning, human relations, systems thinking will become more relevant Troubleshooting will become more important. AI is not self-diagnosing. I would hire someone who can figure out something is going wrong, diagnose what’s going wrong, and fix it #TODO Hire for troubleshooting ability. Give a Q, an A, and ask them to figure out if it’s wrong, why, and fix it All my exams and quizzes are open book, open ChatGPT. Onus is on me to give a problem that forces you to think. #TODO Write a question paper that is ChatGPT proof. Exploring AI could be a ToK subject. “How to interact with an AI?” We need a manual on how to use AI. Like Simon Willison says Content doesn’t suffice. You need pedegogy. What to serve you at what time, how, how to assess. Lots of businesses are filling this gap Students get great confidence when a teacher points to online content and says, I"ll tell you WHAT to see" and COMPLEMENTS that in their class “The map is not the territory.” Most people confuse sample mean for the actual. #ASK Parameter estimation -> Signal estimation -> State estimation Stats vs DL differ in that There is no notion of a defined “truth”. Hence reliability is not measurable Parameters have no value. Hence interpretability is ignored. #TODO Read 2020 National Education Policy. It’s quite modern. We need a manual on self-learning too Listening is not learning. You know only if you implement. Levels for students: I can solve it. I can explain why it works. I can find alternatives. I can apply it to a new area, reformulating (requires imagination.) For teachers, you also need: Responsible learning (extra careful about what to teach and how to teach, to exceite them, to teach at THEIR level). Show the universality and connecting to other concepts. E.g. noise reduction with FT is like using water to remove dirt. Transform to water domain, remove dirt, transform back to air domain. It’s better than dusting clothes to remove clothes. Washing machine programs are just different models of removing noise in the water domain. Teach people who WANT to learn AND who will APPLY it long-term. That’s what maximizes impact Grad students are more satisfying that way. Else, it is WASTED effort. (Not that it’s a bad thing for the student, but the effort IS wasted for the teacher) Therefore, I believe students should have general engineering first, and let students pick specialization later. Some universitie are doing that. #THINK Students remember my philosophy more than my content. We impart character, not just knowledge. Astrology and horoscopes serve a different function. They provide explainability, not predictive ability. As the world becomes less explainable, the need for astrology will grow. Explainability is about creating STORIES that fits data plausibly. It has nothing to do with data or truth. Explainability and predictive ability and reproducibility are all different. Maybe, Science is about the latter two, less about explainability. Astrology is a model. The map is not the territory. It’s an explanatory, not a predictive model. #THINK Therefore, my lessons are just explanations. Stats about experiments are STILL explanations. They are NOT reproducible or predictive. Hence not yet science The meaning of our life is the transformation we undergo in our lives #TODO Read “The Journey of Souls” by Michael Newton. A hypnotherapist #TODO Try regression therapy / hypnosis. Record it and listen to it. Just for fun! Rohini Deshpande Slam book was the Facebook of the 1900s Prepared mind is an extremely powerful tool for learning. Practice prepared mind When women drop out of education or career, that is also a waste from the teacher and system perspective The time for career growth is the same as child bearing time for women. That’s not true for men. But child rearing can be done by either. That’s not recognised. It’s 0K for a man to raise the child and make the home and 0K to treat that as the default Since men are more senior, it’s usually logical for them to stay in their jobs. That’s a systematic bias. When seniors advise women to step back. they respect it. That widens the barrier. Why not eliminate that situation? Be proud of the working women in the family Stats are just a symptom. They don’t explain the cause. (Map is not the territory.) Explanations are what really helps us fix the cause. Hence stories are important. Read Tinker Tailor Soldier Spy RV Athimber health tips: Eat foods with low glycemic index Eliminate free salt completely Voyage AI Embeddings have a higher quality, similar price compared to OpenAI embeddings. There’s a clear benefit to replacing text-embedding-3-large with voyage-3-lite. There’s a 200 MTok free tier currently. mixtral-offloading cleverly loads only the model layer required at any point, letting you run Mixtral 8x7b on Colab Free and on 16GB GPUs. This notebook runs on Colab Free too. CodeGPT is an alternative to Github Copilot that can use any LLM.

2023 1

LLMs can teach experts

I am a fairly good programmer. So, when I see a problem, my natural tendency is to code. I’m trying to break that pattern. Instead, I ask ChatGPT. For example, I asked: Write a compact 1-line Python expression that checks if user.id ends with @gramener.com or @straive.com user.id.endswith(("@gramener.com", "@straive.com")) After 15 years of using Python, I learnt that .endswith() supports tuple suffixes. This has been around since Python 2.5 (released in 2006 – before I knew Python.) The documentation has a tiny sentence in the middle saying “suffix can also be a tuple of suffixes to look for.” ...

2021 3

Maps, Delimitation, and Gerrymandering

I delivered a talk at PyCon India 2019. My slides are on Github. This is a transcript of that talk. What I’m going to be talking about is how you can get insights by joining two maps but before we go there, just some basic bookkeeping things. In case you’re tweeting, these are the hashtags, you probably want to be using the #PyconIndia, my hashtag my IDs, #SANAND0, you don’t need to worry about the slides, they are online. I’ve already posted on Twitter, the link to the slide deck, the slide deck that you’re using but if you desperately do want to take notes, then one small suggestion. Research has shown that taking notes on pen and paper is much better than taking notes on laptops if you want to remember stuff or on mobile phones. So this was a discovery for me. In fact, it was my discovery of the year and I’m following it diligently. Do give it a shot if you want to take notes. Let’s dive in. ...

Programming Minecraft with Websockets

Minecraft lets you connect to a websocket server when you’re in a game. The server can receive and send any commands. This lets you build a bot that you can … (well, I don’t know what it can do, let’s explore.) Minecraft has commands you can type on a chat window. For example, type / to start a command and type setblock ~1 ~0 ~0 grass changes the block 1 north of you into grass. (~ means relative to you. Coordinates are specified as X, Y and Z.) ...

How to extend Markdown with custom blocks

One problem I’ve had in Markdown is rendering a content in columns. On Bootstrap, the markup would look like this: <div class="row"> <div class="col">...</div> <div class="col">...</div> </div> How do we get that into Markdown without writing HTML? On Python, the attribute lists extension lets you add a class. For example: This is some content {: .row} … renders <p class="row">This is some content</p>. But I can’t do that to multiple paragraphs. Nor can I next content, i.e. add a .col inside the .row. ...

2020 1

lxml is fast enough

Given the blazing speed of Node.js these days, I expected HTML parsing to be faster on Node than on Python. So I compared lxml with htmlparser2 – the fastest libraries on Python and JS in parsing the reddit home page (~700KB). lxml took ~8.6 milliseconds htmlparser2 took ~14.5 milliseconds Looks like lxml is much faster. I’m likely to stick around with Python for pure HTML parsing (without JavaScript) for a while longer. In [1]: from lxml.html import parse In [2]: %timeit tree = parse('reddit.html') 8.69 ms ± 190 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) const { Parser } = require("htmlparser2"); const { DomHandler } = require("domhandler"); const fs = require("fs"); const html = fs.readFileSync("reddit.html"); const handler = new DomHandler(function(error, dom) {}); const start = +new Date(); for (var i = 0; i < 100; i++) { const parser = new Parser(); parser.write(html); parser.end(); } const end = +new Date(); console.log((end - start) / 100); Note: If I run the htmlparser2 code 100 times instead of 10, it only takes 7ms per loop. The more the number of loops, the faster it parses. I guess Node.js optimizes repeated loops. But I’m only interested in the first iteration, since I’ll be parsing files only once.

2012 4

The most popular scientific Python modules

I just scraped the scientific packages on pypi. Here are the top 50 by downloads. Name Description Size Downloads numpy NumPy: array processing for numbers, strings, records, and objects. 2000000 133076 scipy SciPy: Scientific Library for Python 7000000 33990 pygraphviz Python interface to Graphviz 99000 22828 geopy Python Geocoding Toolbox 32000 18617 googlemaps Easy geocoding, reverse geocoding, driving directions, and local search in Python via Google. 69000 15135 Rtree R-Tree spatial index for Python GIS 495000 14370 nltk Natural Language Toolkit 1000000 12844 Shapely Geometric objects, predicates, and operations 93000 12635 pyutilib.component.doc Documentation for the PyUtilib Component Architecture. 372000 10181 geojson Encoder/decoder for simple GIS features 12000 9407 GDAL GDAL: Geospatial Data Abstraction Library 410000 8957 scikits.audiolab A python module to make noise from numpy arrays 1000000 8856 pupynere NetCDF file reader and writer. 16000 8809 scikits.statsmodels Statistical computations and models for use with SciPy 3000000 8761 munkres munkres algorithm for the Assignment Problem 42000 8409 scikit-learn A set of python modules for machine learning and data mining 2000000 7735 networkx Python package for creating and manipulating graphs and networks 1009000 7652 pyephem Scientific-grade astronomy routines 927000 7644 PyBrain PyBrain is the swiss army knife for neural networking. 255000 7313 scikits.learn A set of python modules for machine learning and data mining 1000000 7088 obspy.seisan SEISAN read support for ObsPy. 3000000 6990 obspy.wav WAV(audio) read and write support for ObsPy. 241000 6985 obspy.seishub SeisHub database client for ObsPy. 237000 6941 obspy.sh Q and ASC (Seismic Handler) read and write support for ObsPy. 285000 6926 crcmod CRC Generator 128000 6714 obspy.fissures DHI/Fissures request client for ObsPy. 1000000 6339 stsci.distutils distutils/packaging-related utilities used by some of STScI's packages 25000 6215 pyopencl Python wrapper for OpenCL 1000000 6124 Kivy A software library for rapid development of hardware-accelerated multitouch applications. 11000000 5879 speech A clean interface to Windows speech recognition and text-to-speech capabilities. 17000 5809 patsy A Python package for describing statistical models and for building design matrices. 276000 5517 periodictable Extensible periodic table of the elements 775000 5498 pymorphy Morphological analyzer (POS tagger + inflection engine) for Russian and English (+perhaps German) languages. 70000 5174 imposm.parser Fast and easy OpenStreetMap XML/PBF parser. 31000 4940 hcluster A hierarchical clustering package for Scipy. 442000 4761 obspy.core ObsPy - a Python framework for seismological observatories. 487000 4608 Pyevolve A complete python genetic algorithm framework 99000 4509 scikits.ann Approximate Nearest Neighbor library wrapper for Numpy 82000 4368 obspy.imaging Plotting routines for ObsPy. 324000 4356 obspy.xseed Dataless SEED, RESP and XML-SEED read and write support for ObsPy. 2000000 4331 obspy.sac SAC read and write support for ObsPy. 306000 4319 obspy.arclink ArcLink/WebDC client for ObsPy. 247000 4164 obspy.iris IRIS Web service client for ObsPy. 261000 4153 Orange Machine learning and interactive data mining toolbox. 14000000 4099 obspy.neries NERIES Web service client for ObsPy. 239000 4066 pandas Powerful data structures for data analysis, time series,and statistics 2000000 4037 pycuda Python wrapper for Nvidia CUDA 1000000 4030 GeoAlchemy Using SQLAlchemy with Spatial Databases 159000 3881 pyfits Reads FITS images and tables into numpy arrays and manipulates FITS headers 748000 3746 HTSeq A framework to process and analyze data from high-throughput sequencing (HTS) assays 523000 3720 pyopencv PyOpenCV - A Python wrapper for OpenCV 2.x using Boost.Python and NumPy 354000 3660 thredds THREDDS catalog generator. 25000 3622 hachoir-subfile Find subfile in any binary stream 16000 3540 fluid Procedures to study geophysical fluids on Python. 210000 3520 pygeocoder Python interface for Google Geocoding API V3. Can be used to easily geocode, reverse geocode, validate and format addresses. 7000 3514 csc-pysparse A fast sparse matrix library for Python (Commonsense Computing version) 111000 3455 topex A very simple library to interpret and load TOPEX/JASON altimetry data 7000 3378 arrayterator Buffered iterator for big arrays. 7000 3320 python-igraph High performance graph data structures and algorithms 3000000 3260 csvkit A library of utilities for working with CSV, the king of tabular file formats. 29000 3236 PyVISA Python VISA bindings for GPIB, RS232, and USB instruments 237000 3201 Quadtree Quadtree spatial index for Python GIS 40000 3000 ProxyHTTPServer ProxyHTTPServer -- from the creator of PyWebRun 3000 2991 mpmath Python library for arbitrary-precision floating-point arithmetic 1000000 2901 bigfloat Arbitrary precision correctly-rounded floating point arithmetic, via MPFR. 126000 2879 SimPy Event discrete, process based simulation for Python. 5000000 2871 Delny Delaunay triangulation 18000 2790 pymc Markov Chain Monte Carlo sampling toolkit. 1000000 2727 PyBUFR Pure Python library to encode and decode BUFR. 10000 2676 collective.geo.bundle Plone Maps (collective.geo) 11000 2676 dap DAP (Data Access Protocol) client and server for Python. 125000 2598 rq RQ is a simple, lightweight, library for creating background jobs, and processing them. 29000 2590 pyinterval Interval arithmetic in Python 397000 2558 StarCluster StarCluster is a utility for creating and managing computing clusters hosted on Amazon's Elastic Compute Cloud (EC2). 2000000 2521 fisher Fast Fisher's Exact Test 43000 2503 mathdom MathDOM - Content MathML in Python 169000 2482 img2txt superseded by asciiporn, http://pypi.python.org/pypi/asciiporn 443000 2436 DendroPy A Python library for phylogenetics and phylogenetic computing: reading, writing, simulation, processing and manipulation of phylogenetic trees (phylogenies) and characters. 6000000 2349 geolocator geolocator library: locate places and calculate distances between them 26000 2342 MyProxyClient MyProxy Client 67000 2325 PyUblas Seamless Numpy-UBlas interoperability 51000 2252 oroboros Astrology software 1000000 2228 textmining Python Text Mining Utilities 1000000 2198 scikits.talkbox Talkbox, a set of python modules for speech/signal processing 147000 2188 asciitable Extensible ASCII table reader and writer 312000 2160 scikits.samplerate A python module for high quality audio resampling 368000 2151 tabular Tabular data container and associated convenience routines in Python 52000 2114 pywcs Python wrappers to WCSLIB 2000000 2081 DeliciousAPI Unofficial Python API for retrieving data from Delicious.com 19000 2038 hachoir-regex Manipulation of regular expressions (regex) 31000 2031 Kamaelia Kamaelia - Multimedia & Server Development Kit 2000000 2007 seawater Seawater Libray for Python 2000000 1985 descartes Use geometric objects as matplotlib paths and patches 3000 1983 vectorformats geographic data serialization/deserialization library 10000 1949 PyMT A framework for making accelerated multitouch UI 18000000 1945 times Times is a small, minimalistic, Python library for dealing with time conversions between universal time and arbitrary timezones. 4000 1929 CocoPy Python implementation of the famous CoCo/R LL(k) compiler generator. 302000 1913 django-shapes Upload and export shapefiles using GeoDjango. 9000 1901 sympy Computer algebra system (CAS) in Python 5000000 1842 pyfasta fast, memory-efficient, pythonic (and command-line) access to fasta sequence files 14000 1836 Comments Ron Z 25 Jun 2013 10:19 pm: Another good one is simpleCV: http://www.simplecv.org/ Ravindranath M 8 Apr 2013 7:13 am: Nice list Anand. Very useful. – This is Ravi from Comviva, who attended your introduction.

Inspecting code in Python

Lisp users would laugh, since they have macros, but Python supports some basic code inspection and modification. Consider the following pieces of code: margin = lambda v: 1 - v['cost'] / v['sales'] What if you wanted another function that lists all the dictionary indices used in the function? That is, you wanted to extract cost and sales? This is a real-life problem I encountered this morning. I have 100 functions, each defining a metric. For example, ...

Is Protocol buffers worth it?

Google’s Protocol Buffers is a “language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler” XML is slow and large. There’s no doubting that. JSON’s my default alternative, though it’s a bit large. CSV’s ideal for tabular data, but ragged hierarchies are a bit difficult. I was trying to see if Protocol Buffers would be smaller and faster, at least when using Python. I took JSON as the base, and checked the write speed, read speed and file sizes. Here’s the comparison: ...

Scraping for a laptop

I’ve returned my laptop, and it’s time to buy a new one. For the first time in my life, I’m buying a laptop for myself. I have a fairly clear idea of what I want: a 500GB+ 7200 rpm hard disk with 4GB of RAM and an Intel Core i7. I thought that would make finding one of those powerful laptops for producing music since I record some stuff too out of hobby. Sheer naïveté. Not a single site let me filter by hard disk rpm in India. (To be fair, I haven’t found any sites outside India that did that either.) ...

2011 4

Software for my new laptop 2

Time for a new laptop, and to replace software. Here’s my new list. A lot has changed in the last 5 years. Mainly, I use the browser, cygwin and Portable Apps a lot more. (The last is to escape jailers, not registry bloat.) Media Chrome [new]: For browsing and development. Fast, light, and stays out of the way. Firefox: I keep it just for printing. Chrome sucks at printing. Media Player Classic: Nothing against it, but I decided to stick to just one app, which is… VLC: Continues to be the best media player, IMHO. WinAmp: I just manage my playlists as M3U files, using Python programs. Audacity: Still the easiest way to record audio. Camstudio: The simplest free portable screen capture software I know. PicPick [new]: Lightweight, powerful screenshot grabber VirtualDub: Not the simplest, but still good for what I need: cropping and joining video. MediaCoder [new]: Good for video/audio conversions. Maybe I’ll install this later. Foxit Reader: The simples free portable PDF reader I know, better than… NitroPDF Reader [new]: … which is good for Printing PDFs – better than… Primo PDF: … which has trouble on rare occasions. Microsoft Reader: I have a lot of ebooks in .LIT. Kindle for PC [new]: I don’t own a Kindle, but I’ve bought a few ebooks. Paint.NET: Good enough for cropping and adjusting colours on images. Windows Live Writer [new]: The best way to write this blog WYSIWYG Inkscape [new]: I occasionally edit vector graphics. Google Earth. Google Maps is good enough. ImgBurn: I no longer use CDs/DVDs. Just flash drives and external hard disks. Picasa: I’ve stopped browsing pictures. No time. Sharing ...

Faster data crunching

I’ve been playing with big data lately. The good part is, it’s easy to get interesting results. The data is so unwieldy that even average value calculations provoke a “Amazing! I didn’t know that,” response (No exaggeration. I heard this from two separate ~ $1bn businesses this month.) The bad part is that calculating even that simple average is slow. For example, take this 40MB file (380MB unzipped) and extract the first column. ...

Why node.js

I’ve moved from Python to Javascript on the server side – specifically, Tornado to Node.js. Three years ago, I moved from Perl to Python because I got free hosting at AppEngine. Python’s a cleaner language, but that was not enough to make me move. Free hosting was. Initially, my apps were on AppEngine, but that wouldn’t work for corporate apps, so I tried Django. IMHO, Django’s too bulky, has too much “magic”, and templates are restrictive. Then I tried Tornado: small; independent modules; easy to learn. I used it for almost 2 years. ...

Visualising student performance 2

This earlier visualisation was revised based feedback from teachers. It’s split into two parts: one focused on performance by subject, and another on performance of each student. Students’ performance by subject This is fairly simple. Under each subject, we have a list of students, sorted by marks and grouped by grade. The primary use of this is to identify top performers and bottom performers at a glance. It also gives an indication of the grade distribution. ...

2010 2

Visualising student performance

I’ve been helping with visualising student scores for ReportBee, and here’s what we’ve currently come up with. Each row is a student’s performance across subjects. Let’s walk through each element here. The first column shows their relative performance across different subjects. Each dot is their rank in a subject. The dots are colour coded based on the subject (and you can see the colours on the image at the top: English is black, Mathematics is dark blue, etc.) ...

Twitter via e-mail

Since I don’t have Internet access on my BlackBerry (because I’m in prison), I’ve had a pretty low incentive to use Twitter. Twitter’s really handy when you’re on the move, and over the last year, there were dozens of occasions where I really wanted to tweet something, but didn’t have anything except my BlackBerry on hand. Since T-Mobile doesn’t support Twitter via SMS, e-mail is my only option, and I haven’t been able to find a decent service that does what I want it to do. ...

2009 4

Open source in corporates

Last month, my first application went live. I’ve been writing code for 20 years. Not one line of my code has been officially deployed in a corporate. (Loser…) It’s a happy feeling. Someone defined happiness as the intersection of pleasure and meaning. Writing code is pleasurable. Others using it is meaningful. But this post isn’t quite about that. It’s about the hoops I’ve had to jump through to make this happen. ...

Round buttons with Python Image Library

After much hunting, I finally settled on Hedger Wang’s simple round CSS links as the most acceptable cross-browser round button implementation. The minified CSS is about 2.5KB, and the syntax is very simple. To make an input button into a round button, just wrap it within a <span class="button">: <span class="button"><input type="submit"></span> … and it’s just as easy to convert a link into a rounded button: <a class="button" href=”/”><span>Home</span></a> It works by using a transparent PNG / GIF that looks like this: ...

Automating PowerPoint with Python

Writing a program to draw or change slides is sometimes easier than doing it manually. To change all fonts on a presentation to Arial, for example, you’d write this Visual Basic macro: Sub Arial() For Each Slide In ActivePresentation.Slides For Each Shape In Slide.Shapes Shape.TextFrame.TextRange.Font.Name = "Arial" Next Next End Sub If you didn’t like Visual Basic, though, you could write the same thing in Python: import win32com.client, sys Application = win32com.client.Dispatch("PowerPoint.Application") Application.Visible = True Presentation = Application.Presentations.Open(sys.argv[1]) for Slide in Presentation.Slides: for Shape in Slide.Shapes: Shape.TextFrame.TextRange.Font.Name = "Arial" Presentation.Save() Application.Quit() Save this as arial.py and type “arial.py some.ppt” to convert some.ppt into Arial. ...

To Python from Perl

I’ve recently switched to Python, after having programmed in Perl for many years. I’m sacrificing all my knowledge of the libraries and language quirks of Perl. The reason I moved despite that is for a somewhat trivial reason, actually. It’s because Python doesn’t require a closing brace. Consider this Javascript (or very nearly C or Java) code: var s=0; for (var i=0; i<10; i++) { for (var j=0; j<10; j++) { s = s + i * j } } That’s 6 lines, with two lines just containing the closing brace. Or consider Perl. ...

2008 2

Automating Internet Explorer with jQuery

Most of my screen-scraping so far has been through Perl (typically WWW::Mechanize). The big problem is that it doesn't support Javascript, which can often be an issue: The content may be Javascript-based. For example, Amazon.com shows the bestseller book list only if you have Javascript enabled. So if you're scraping the Amazon main page for the books bestseller list, you won't get it from the static HTML. The navigation may require Javascript. Instead of links or buttons in forms, you might have Javascript functions. Many pages use these, and not all of them degrade gracefully into HTML. (Try using Google Video without Javascript.) The login page uses Javascript. It creates some crazy session ID, and you need Javascript to reproduce what it does. You might be testing a Javascript-based web-page. This was my main problem: how do I automate testing my pages, given that I make a lot of mistakes? There are many approaches to overcoming this. The easiest is to use Win32::IE::Mechanize, which uses Internet Explorer in the background to actually load the page and do the scraping. It's a bit slower than scraping just the HTML, but it'll get the job done. ...

Statistically improbable phrases on Google AppEngine

I read about Google AppEngine early this morning, and applied for an invite. Google’s issuing beta invites to the first 10,000 users. I was pretty convinced I wasn’t among those, but turns out I was lucky. AppEngine lets you write web apps that Google hosts. People have been highlighting that it give you access to the Google File System and BigTable for the first time. But to me, that isn’t a big deal. (I’m not too worried about reliability, and MySQL / flat files work perfectly well for me as a data store.) ...

2006 2

Software for my new laptop

And so, thanks to Infosys Consulting being spun off as a separate legal entity in the UK, I got my new laptop. (Because our old laptops were legally the assets of Infosys Technologies Ltd, and not Infosys Consulting Inc. Weirder things have happened, but who’s complaining?) My old Toshiba Portege A200 has been replaced by a Dell Latitude D420 (which I was dreaming for, after having just read Jeff’s post on big laptops). ...

Python vs Perl

Python vs Perl. Sums up my feelings perfectly: Python may be better for larger projects, but for my meddling, I’ll stick to Perl. It’s served me well for 10 years. Until 1999, I used Perl a fair bit, but no more than Java or C or anything else. My first “real-life” use of Perl was in 2000, when I was processing 600MB of IBES data. Access and SPSS couldn’t handle the load. Perl slurped all the data in a few seconds, though. A few years later, when processing bank data (3GB worth, this time), Perl again was the only saviour. In fact, between Excel and Perl (and CPAN), I think I have all the data analysis power I’ve ever needed. This blog, for instance, is written in an Excel spreadsheet, exported to XML, and converted into the blog format by Perl.