AWS Architecture Guide: Production Patterns and Best Practices
Everything I’ve learned building on AWS since 2012, organized by domain.
Serverless
- AWS Lambda Cold Starts: Causes, Measurement, and Mitigation — The definitive cold start guide
- AWS Step Functions: Orchestrating Complex Workflows — State machine patterns
- AWS EventBridge: Event-Driven Architectures — Building event-driven systems
Containers
- AWS ECS vs EKS: Choosing Your Container Orchestrator — When to use each
- Building Production-Ready Docker Images — Multi-stage builds and distroless
Data & AI
- AWS Aurora Serverless v2: Architecture and Performance — Serverless database deep dive
- AWS Bedrock: Building AI Applications — Foundation models in production
Governance & Cost
- AWS Cost Optimization Techniques That Work — Practical cost reduction
- AWS Organizations and Control Tower — Multi-account strategy
- Implementing Zero Trust Networking on AWS — Network security architecture
Infrastructure as Code
- AWS CDK vs Terraform: Practical Comparison — Choosing your IaC tool
- Terraform State Management Best Practices — Remote state and locking
- Terraform Modules: Design Patterns — Reusable infrastructure
Kubernetes Guide: From Basics to Production Operations
This is the hub for everything I’ve written about Kubernetes. Whether you’re setting up your first cluster or optimizing a multi-tenant production environment, start here.
Cluster Security
- Kubernetes RBAC Deep Dive: Multi-Tenant Clusters — Role-based access control for teams sharing a cluster
- Kubernetes Network Policies: Practical Security Guide — Pod-to-pod traffic control with Calico and Cilium
- Kubernetes eBPF Observability and Security — Runtime security with eBPF
Scaling & Performance
- Kubernetes HPA with Custom Metrics — Autoscaling beyond CPU with Prometheus metrics
- K8s Scaling Mastery: Manual, HPA & Metrics APIs — Complete scaling overview
- Kubernetes Multi-Cluster Management — Fleet and Rancher for multi-cluster
Networking & Ingress
- Kubernetes Ingress Controllers: NGINX, Traefik, Istio — Choosing the right ingress controller
- Kubernetes Gateway API: The Future of Ingress — Gateway API vs Ingress resources
Advanced Operations
- Kubernetes Operators and Custom Controllers in Go — Building operators with Kubebuilder
- Implementing SLOs and Error Budgets in Practice — SRE practices for K8s workloads
- Distributed Tracing with OpenTelemetry — Observability for microservices
Kubernetes Multi-Cluster Management with Fleet and Rancher
I’ve been running Kubernetes in production for years now, and there’s a specific kind of pain that only hits you once you cross the threshold from “a couple of clusters” to “wait, how many do we have again?” That threshold, for me, was eight clusters. Eight clusters across three cloud providers and two on-prem data centers. And every single one of them had drifted into its own little snowflake.
This isn’t a theoretical post. I’m going to walk through how I used Fleet and Rancher to wrangle that mess back into something manageable, and why I think GitOps-driven multi-cluster management is the only sane approach once you’re past three or four clusters.
Rust WebAssembly: Building High-Performance Web Applications
Last year I ported an image processing pipeline from JavaScript to Rust compiled to WebAssembly. The JS version took 1.2 seconds to apply a chain of filters — blur, sharpen, color correction, resize — to a 4K image in the browser. The Rust Wasm version did the same work in 58 milliseconds. Not a typo. A 20x speedup, running in the same browser, on the same machine, called from the same React app.
AWS Aurora Serverless v2: Architecture and Performance Guide
Aurora Serverless v2 is what v1 should have been. I don’t say that lightly — I ran v1 in production for two years and spent more time fighting its scaling quirks than actually building features. The pausing, the cold starts, the inability to add read replicas. It was a product that promised serverless databases and delivered something that felt like a managed instance with extra steps.
When v2 landed, I was skeptical. AWS has a habit of slapping “v2” on things that are marginally better. But I migrated a production PostgreSQL workload from RDS provisioned to Aurora Serverless v2 last year, and it genuinely changed how I think about database scaling strategies. The scaling is fast, granular, and — this is the part that surprised me — it doesn’t drop connections when it scales. That alone makes it a different product entirely.
Implementing SLOs and Error Budgets in Practice
99.99% availability sounds great until you realize that’s 4 minutes and 19 seconds of downtime per month. Four minutes. That’s barely enough time to get paged, open your laptop, authenticate to the VPN, and find the right dashboard. You haven’t even started diagnosing anything yet.
I’ve watched teams commit to four-nines SLOs because someone in a leadership meeting said “we need to be best in class.” No capacity planning. No discussion about what it would cost. No understanding that the jump from 99.9% to 99.99% isn’t a 0.09% improvement — it’s a 10x reduction in your margin for error.
Python Packaging in 2026: uv, Poetry, and the Modern Ecosystem
I mass-deleted requirements.txt files from a monorepo last month. Fourteen of them. Some had unpinned dependencies, some had pins from 2021, one had a comment that said # TODO: fix this next to a package that no longer exists on PyPI. Nobody cried. The CI pipeline didn’t break. We’d already moved everything to pyproject.toml and uv.
Python packaging has been a punchline for years. “It’s 2024 and we still can’t install packages properly” was a meme that wrote itself. But here’s the thing — it’s 2026 now, and the landscape genuinely changed. Not incrementally. Fundamentally. uv showed up and rewrote the rules. Poetry matured into something reliable. pyproject.toml won. The old setup.py + requirements.txt + virtualenv + pip stack isn’t dead, but it’s legacy. If you’re starting a new project today and reaching for that combo, you’re choosing the hard path for no reason.
Kubernetes Ingress Controllers: NGINX vs Traefik vs Istio Gateway
NGINX Ingress is the Honda Civic of ingress controllers. Boring, reliable, gets the job done. I’ve deployed it on dozens of clusters and it’s never been the thing that woke me up at 3am. That’s the highest compliment I can give any piece of infrastructure.
But boring doesn’t mean it’s always the right choice. I’ve spent the last three years running all three major ingress options — NGINX Ingress Controller, Traefik, and Istio’s Gateway — across production clusters of varying sizes. I migrated one platform from NGINX to Istio and nearly lost my mind in the process. I’ve also watched Traefik quietly become the best option for teams that nobody talks about at conferences.
AWS Step Functions: Orchestrating Complex Workflows
I deleted roughly 2,000 lines of orchestration code from our payment processing service last year. Replaced it with about 200 lines of Amazon States Language JSON. The system got more reliable, not less. That’s the short version of why I think Step Functions is one of the most underappreciated services in AWS.
The longer version involves a 3am incident, a chain of Lambda functions calling each other through direct invocation, and a payment that got charged twice because nobody could tell where the workflow had actually failed.
Terraform Testing: Unit, Integration, and End-to-End
Most Terraform code has zero tests. That’s insane for something managing production infrastructure. We wouldn’t ship application code without tests — why do we treat the thing that creates our VPCs, databases, and IAM roles like it’s somehow less important?
I learned this lesson the painful way. Last year I pushed a Terraform change that modified a security group rule on a shared networking stack. The plan looked clean. Added an ingress rule, removed an old one. Terraform showed exactly two changes. I approved it, applied it, and went to lunch. By the time I got back, three services were down. The “old” rule I removed was the one allowing traffic between our application tier and the database subnet. The plan was technically correct — it did exactly what I told it to. But I’d told it the wrong thing, and nothing in our pipeline caught it.
Distributed Tracing with OpenTelemetry: A Complete Guide
I spent four hours on a Tuesday night debugging a 30-second API call. Four hours. The call touched 12 services — auth, inventory, pricing, three different caching layers, a recommendation engine, two legacy adapters, and a handful of internal APIs that nobody remembered writing. Logs told me nothing useful. Metrics showed elevated latency somewhere in the pricing path, but “somewhere” isn’t actionable at 11pm when your on-call phone won’t stop buzzing.
Container Security Scanning in CI/CD Pipelines
If you’re not scanning container images before they hit production, it’s only a matter of time before something ugly shows up in your environment. I learned this the hard way, and I’m going to walk you through exactly how I set up container security scanning in CI/CD pipelines so you don’t repeat my mistakes.
The Wake-Up Call
About two years ago, I was running a handful of microservices on ECS. Everything was humming along. Deployments were smooth, monitoring looked clean, the team was shipping features weekly. Life was good.
AWS EventBridge: Building Event-Driven Architectures
EventBridge is the most underused AWS service. I’ll die on that hill. Teams will build these elaborate Rube Goldberg machines out of SNS topics, SQS queues, and Lambda functions stitched together with duct tape and prayers, when EventBridge would’ve given them a cleaner architecture in a fraction of the time.
I know this because I was one of those teams. About two years ago I inherited a system where a single order placement triggered a cascade of 14 SNS topics fanning out to 23 SQS queues. Nobody could tell me what happened when an order was placed without opening a spreadsheet. A spreadsheet. For message routing. When I asked why they hadn’t used EventBridge, the answer was “we started before it existed and never migrated.” Fair enough. But the pain was real — we’d get phantom duplicate processing, messages landing in DLQs with no context about where they came from, and debugging meant grepping through six different CloudWatch log groups hoping to find a correlation ID someone remembered to pass along.
Python Performance Optimization: Profiling and Tuning Guide
Don’t optimize until you’ve profiled. I’ve watched teams rewrite entire modules that weren’t even the bottleneck. Weeks of work, zero measurable improvement. The code was “cleaner” I guess, but the endpoint was still slow because the actual problem was three database queries hiding inside a template tag.
I learned this the hard way on a Django project a couple of years back. We had a view that took 4+ seconds to render. The team was convinced it was the serialization layer — we were building a big nested JSON response, lots of related objects. Someone had already started rewriting the serializers when I asked if anyone had actually profiled it. Blank stares.
Kubernetes Operators: Building Custom Controllers in Go
Operator SDK vs kubebuilder — I pick kubebuilder every time. Operator SDK wraps kubebuilder anyway, adds a layer of abstraction that mostly just gets in the way, and the documentation lags behind. Kubebuilder gives you the scaffolding, the code generation, and then gets out of your face. That’s what I want from a framework.
I built my first operator about two years ago. The task: automate database provisioning for development teams. Every time a team needed a new PostgreSQL instance, they’d file a Jira ticket, wait for the platform team to provision it, get credentials back in a Slack DM (yes, really), and manually configure their app. The whole cycle took three to five days. Sometimes longer if someone was on leave.
Rust Error Handling Patterns for Production Applications
I got paged at 3am on a Tuesday because a Rust service I’d deployed two weeks earlier crashed hard. No graceful degradation, no useful error message in the logs. Just a panic backtrace pointing at line 247 of our config parser: .unwrap().
The config file had a trailing comma that our test fixtures didn’t cover. One .unwrap() on a serde_json::from_str call, and the whole service went down. I sat there in the dark, laptop balanced on my knees, fixing a one-line bug that should never have made it past code review.
AWS CDK vs Terraform: A Practical Comparison in 2026
I use both. Terraform for multi-cloud, CDK when it’s pure AWS and the team knows TypeScript. That’s the short answer. But the long answer has a lot more nuance, and I’ve earned that nuance the hard way — including one migration that nearly broke a team’s shipping cadence for two months.
This isn’t a “which one is better” post. I don’t think that question makes sense without context. What I can tell you is where each tool shines, where each one will bite you, and how to pick the right one for your situation in 2026. I’ve shipped production infrastructure with both, maintained both in anger, and migrated between them. Here’s what I’ve learned.
Platform Engineering: Building an Internal Developer Platform
Platform engineering is DevOps done right. Or maybe it’s DevOps with a product mindset. Either way, it’s the recognition that telling every team to “own their own infrastructure” without giving them decent tooling is a recipe for chaos. I’ve watched organisations try the “you build it, you run it” approach and end up with fifteen different ways to deploy a container, nine half-configured Terraform repos, and developers who spend more time fighting YAML than writing features.
Kubernetes Horizontal Pod Autoscaling with Custom Metrics
CPU-based autoscaling is a lie for most web services. There, I said it.
I spent a painful week last year watching an HPA scale our API pods from 3 to 15 based on CPU utilization. The dashboards looked great — CPU was being “managed.” Meanwhile, the service was falling over because every single one of those 15 pods was fighting over a connection pool limited to 50 database connections. More pods made the problem worse. We were autoscaling ourselves into an outage.
Go Concurrency Patterns for Microservices
Goroutines are cheap. Goroutine leaks are not.
I learned this the hard way at 2am on a Tuesday, staring at Grafana dashboards showing one of our services consuming 40GB of RAM and climbing. The service normally sat around 500MB. We’d shipped a change three days earlier — a seemingly innocent fan-out pattern to parallelize calls to a downstream API. The code looked fine. Reviews passed. Tests passed. What we’d missed was that when the downstream service timed out, nothing was cancelling the spawned goroutines. They just… accumulated. Thousands per minute, each holding onto its request body and response buffer, waiting for a context that would never expire because we’d used context.Background() instead of propagating the parent context.
Implementing Zero-Trust Networking on AWS
VPNs are not zero trust. Stop calling them that.
I can’t count how many times I’ve sat in architecture reviews where someone points at a Site-to-Site VPN or a Client VPN endpoint and says “we’re zero trust.” No. You’ve built a tunnel. A tunnel that, once you’re inside, gives you access to everything on the network. That’s the opposite of zero trust. That’s a castle with a drawbridge and nothing inside but open hallways.
Python Type Hints and Static Analysis in Production Codebases
If you’re writing Python without type hints in 2026, you’re making life harder for everyone — including future you. I held out for a while. I liked Python’s flexibility, the duck typing, the “we’re all consenting adults here” philosophy. Then a production bug cost my team three days of debugging, and I changed my mind permanently.
I’m going to walk through how I’ve adopted type hints across production codebases, the tooling that makes it practical, and the patterns that actually matter versus the ones that are just academic noise.
AWS Cost Optimization: 15 Techniques That Actually Work
I got a call from a startup founder last year. “Our AWS bill just hit $47,000 and we have twelve engineers.” They’d been running for about eighteen months, never really looked at the bill, and suddenly it was eating their runway. I spent a week inside their account. We cut it to $28,000. That’s a 40% reduction, and honestly most of it was embarrassingly obvious stuff.
That experience crystallized something I’d been thinking about for a while: most AWS cost problems aren’t sophisticated. They’re neglect. People provision things, forget about them, and the meter keeps running. The fixes aren’t glamorous either — they’re methodical, sometimes tedious, and they work.
Kubernetes RBAC Deep Dive: Securing Multi-Tenant Clusters
I’m going to say something that’ll upset people: if your developers have cluster-admin access in production, you’re running on borrowed time. I don’t care how small your team is. I don’t care if “everyone’s responsible.” It’s insane, and I’ve got the scars to prove it.
This article is the RBAC deep dive I wish I’d had before a developer on my team ran kubectl delete namespace production-api on a Friday afternoon. Not maliciously. He thought he was pointed at his local minikube. He wasn’t. That namespace had 14 services, and we spent the weekend rebuilding it from manifests that were — let’s be generous — “mostly” up to date.
Terraform Modules: Design Patterns for Reusable Infrastructure
I once inherited a project with a single main.tf that was over 3,000 lines long. No modules. No abstractions. Just one enormous file that deployed an entire production environment — VPCs, ECS clusters, RDS instances, Lambda functions, IAM roles — all jammed together with hardcoded values and copy-pasted blocks. Changing a security group rule meant scrolling for five minutes and praying you edited the right resource. It was, without exaggeration, the worst Terraform I’ve ever seen.
GitOps with ArgoCD: From Zero to Production
ArgoCD won the GitOps war. I’ll say it. Flux is fine—it works, it’s CNCF graduated, it has its fans—but ArgoCD’s UI alone makes it worth choosing. When something’s out of sync at 2am, I don’t want to be parsing CLI output. I want to click on a resource tree and see exactly what drifted.
I’ve been running ArgoCD in production across multiple clusters for a couple of years now, and this is the guide I wish I’d had when I started. We’ll go from a fresh install to a production-grade setup with app-of-apps, RBAC, SSO, multi-cluster management, and sane sync policies.
Rust for Cloud Engineers: Why Systems Programming Matters
I started learning Rust as someone who’d spent years writing Python scripts and Go services for cloud infrastructure. My first reaction was honestly frustration — the borrow checker felt like a compiler that existed purely to reject my code. But something kept pulling me back. The binaries were tiny. The startup times were instant. And once my code compiled, it just… worked. No runtime panics at 3am. No mysterious memory leaks creeping up after a week in production.
AWS ECS vs EKS: Choosing the Right Container Orchestrator in 2026
ECS is underrated. Most teams picking EKS don’t need it. I’ve been saying this for years, and I’ll keep saying it until the industry stops treating Kubernetes as the default answer to every container question.
I watched a team — smart engineers, solid product — choose EKS for what was essentially a three-service CRUD application behind an ALB. They’d read the blog posts, watched the conference talks, and decided Kubernetes was the future. Three months later they were still stabilizing the cluster. Not building features. Not shipping value. Debugging Helm chart conflicts, fighting with the AWS VPC CNI plugin, and trying to understand why their pods kept getting evicted. The application itself worked fine. The orchestration layer was the problem.
Building Production-Ready Docker Images: A Multi-Stage Build Guide
I’ve shipped Docker images to production for years now, and the single biggest improvement I’ve made wasn’t some fancy orchestration tool or a new CI platform. It was learning to write proper multi-stage Dockerfiles. My CI pipeline used to spend 20 minutes rebuilding a bloated 2GB image every push. After switching to multi-stage builds, that image dropped to 45MB and builds finished in under 3 minutes. That’s not a typo.
Python Async Programming: asyncio, Tasks, and Real-World Patterns
I avoided asyncio for years. Callbacks, event loops, futures — it all felt like unnecessary complexity when threads worked fine. Then we had an API endpoint making 200 sequential HTTP calls to an upstream service. 45 seconds per request. We threw asyncio.gather at it and the whole thing dropped to 3 seconds. That was the moment it clicked.
Python’s async story has matured enormously. What used to be a mess of yield from and manual loop management is now clean, readable, and genuinely powerful. If you’ve been putting off learning asyncio properly, this is the guide I wish I’d had.
Kubernetes Network Policies: A Practical Security Guide
I’m going to be blunt here. If you’re running Kubernetes without network policies, every pod in your cluster can talk to every other pod. That’s a flat network. It’s terrifying.
I learned this the hard way. A few years back, a compromised container in our staging namespace made a direct TCP connection to the production PostgreSQL pod. No firewall, no segmentation, nothing stopping it. The attacker didn’t even need to be clever — they just scanned the internal network and found an open port. We had pod security policies in place, RBAC locked down, image scanning, the works. But zero network policies. That one gap made everything else irrelevant.
AWS Lambda Cold Starts: Causes, Measurement, and Mitigation Strategies
I’ve lost count of how many times someone’s told me “Lambda has cold start problems” like it’s some fatal flaw. It isn’t. Cold starts are a tradeoff. You get near-infinite scale and zero idle cost, and in return, the first request to a new execution environment takes a bit longer. That’s the deal.
The real problem is that most teams either panic about cold starts when they don’t matter, or ignore them completely when they absolutely do. I’ve seen both. We had a payment API on Lambda that was timing out on cold starts during Black Friday — the Java function took 6 seconds to initialize with Spring Boot, and our API Gateway timeout was set to 5 seconds. Every new concurrent request during the traffic spike just… failed. That was a bad day.
Terraform State Management Best Practices in 2026
I’ve been managing Terraform state across production environments for years now, and if there’s one thing I’m certain of, it’s this: state management is where most Terraform setups fall apart. Not modules. Not provider quirks. State.
The state file is Terraform’s memory. It’s how Terraform knows what it built, what changed, and what to tear down. Lose it, corrupt it, or let two people write to it at the same time, and you’re in for a rough day. I once lost a state file for a networking stack and spent the better part of 6 hours reimporting over 200 resources by hand. VPCs, subnets, route tables, NAT gateways — one at a time. Never again.
SRE Practices for Serverless Architectures: Ensuring Reliability Without Servers
Serverless architectures have transformed how organizations build and deploy applications, offering benefits like reduced operational overhead, automatic scaling, and consumption-based pricing. However, the ephemeral nature of serverless functions, limited execution contexts, and distributed architecture introduce unique reliability challenges. Site Reliability Engineering (SRE) practices must evolve to address these challenges while maintaining the core principles of reliability, observability, and automation.
This comprehensive guide explores how to apply SRE practices to serverless architectures, with practical examples and implementation strategies for ensuring reliability in environments where you don’t manage the underlying infrastructure.
Rust Year in Review: 2025's Major Milestones and Achievements
As 2025 draws to a close, it’s time to look back on what has been an extraordinary year for the Rust programming language. From significant language enhancements and ecosystem growth to expanding industry adoption and community achievements, Rust has continued its impressive trajectory. What began as Mozilla’s research project has evolved into a mainstream programming language that’s reshaping how we think about systems programming, web development, and beyond.
In this comprehensive year-in-review, we’ll explore the major milestones and achievements that defined Rust in 2025. We’ll examine the language improvements that landed, the ecosystem developments that expanded Rust’s capabilities, the industry adoption trends that solidified its position, and the community growth that fueled its success. Whether you’ve been following Rust closely throughout the year or are just catching up, this retrospective will provide valuable insights into Rust’s evolution over the past twelve months.
AI-Driven Cybersecurity: Advanced Threat Detection and Response
The cybersecurity landscape has reached a critical inflection point. As threat actors deploy increasingly sophisticated attacks using automation and artificial intelligence, traditional security approaches are struggling to keep pace. Security teams face overwhelming volumes of alerts, complex attack patterns, and a persistent shortage of skilled personnel. In response, organizations are turning to AI-driven cybersecurity solutions to detect, analyze, and respond to threats with greater speed and accuracy than ever before.
Rust in 2025: Future Directions and Predictions
As 2025 draws to a close, the Rust programming language continues its impressive trajectory of growth and adoption. From its humble beginnings as Mozilla’s research project to its current status as a mainstream language used by tech giants and startups alike, Rust has proven that its unique combination of safety, performance, and expressiveness fills a critical gap in the programming language landscape. But what lies ahead for Rust in 2025? What new features, ecosystem developments, and adoption trends can we expect to see?
Rust for AI and Machine Learning in 2025: Libraries, Performance, and Use Cases
Artificial Intelligence and Machine Learning continue to transform industries across the globe, driving innovations in everything from healthcare and finance to autonomous vehicles and creative tools. While Python has long dominated the AI/ML landscape due to its extensive ecosystem and ease of use, Rust has been steadily gaining ground as a compelling alternative for performance-critical components and production deployments. With its focus on safety, speed, and concurrency, Rust offers unique advantages for AI/ML workloads that require efficiency and reliability.
DevOps for Edge Computing: Extending CI/CD to the Network Edge
The rise of edge computing is transforming how organizations deploy and manage applications. By moving computation closer to data sources and end users, edge computing reduces latency, conserves bandwidth, and enables new use cases that weren’t previously possible. However, this distributed architecture introduces significant challenges for DevOps teams accustomed to centralized cloud environments.
This comprehensive guide explores how to extend DevOps principles and practices to edge computing environments, enabling reliable, secure, and scalable deployments across potentially thousands of edge locations.
FinOps Practices for Cloud Cost Optimization in Distributed Systems
As organizations increasingly adopt distributed systems in the cloud, managing and optimizing costs has become a critical challenge. The dynamic, scalable nature of cloud resources that makes distributed systems powerful can also lead to unexpected expenses and inefficiencies if not properly managed. This is where FinOps—the practice of bringing financial accountability to cloud spending—comes into play.
This article explores practical FinOps strategies and techniques for optimizing cloud costs in distributed systems without compromising performance, reliability, or security.
Hiring Cloud Engineers: What to Look For
As organizations accelerate their cloud adoption journeys, the demand for skilled cloud engineers has skyrocketed. Building a high-performing cloud team is now a critical competitive advantage, yet finding and retaining top cloud talent remains one of the most significant challenges facing technology leaders today. The rapid evolution of cloud technologies, combined with a global shortage of experienced professionals, has created a fiercely competitive hiring landscape.
This comprehensive guide explores what to look for when hiring cloud engineers, from essential technical skills and certifications to soft skills and cultural fit. Whether you’re building a cloud team from scratch or expanding an existing one, this guide provides actionable strategies for attracting, assessing, and retaining the cloud talent your organization needs to succeed.
Rust Best Practices for Maintainable Code in 2025
Writing code that works is just the first step in software development. For projects that need to evolve and be maintained over time, code quality and maintainability are just as important as functionality. Rust, with its emphasis on safety and correctness, provides many tools and patterns that can help you write code that’s not only correct but also maintainable. However, like any language, it requires discipline and adherence to best practices to ensure your codebase remains clean, understandable, and sustainable.
Service Mesh Architecture: The SRE's Guide to Network Reliability
As organizations adopt microservices architectures, the complexity of service-to-service communication grows exponentially. Managing this communication layer—including routing, security, reliability, and observability—has become one of the most challenging aspects of operating modern distributed systems. Service mesh architecture has emerged as a powerful solution to these challenges, providing a dedicated infrastructure layer that handles service-to-service communication.
This comprehensive guide explores service mesh architecture from an SRE perspective, focusing on how it enhances reliability, security, and observability in microservices environments.
Rust in Industry: Case Studies and Success Stories in 2025
Since its 1.0 release in 2015, Rust has steadily gained adoption across various industries, from tech giants to startups, and from web services to embedded systems. What began as Mozilla’s research project has evolved into a mainstream programming language that companies increasingly rely on for performance-critical, secure, and reliable systems. As we look at the landscape in 2025, Rust’s adoption has reached new heights, with more organizations than ever using it to solve real-world problems.
Rust Compared to Other Programming Languages: A Comprehensive Analysis
Choosing the right programming language for a project is a critical decision that can significantly impact development speed, code quality, performance, and maintainability. Rust, with its focus on memory safety without garbage collection, has carved out a unique position in the programming language landscape. But how does it compare to other popular languages like C/C++, Go, Java, Python, and JavaScript? Understanding these comparisons can help you make informed decisions about when and why to choose Rust for your projects.
AI-Powered Data Analytics: Transforming Enterprise Decision Making
The volume, velocity, and variety of data that organizations generate today have far outpaced traditional analytics methods. As businesses struggle to extract meaningful insights from increasingly complex datasets, artificial intelligence has emerged as a transformative force in data analytics. AI-powered analytics goes beyond conventional approaches by automating pattern detection, generating predictive insights, and even recommending actions based on data-driven findings.
This comprehensive guide explores how AI is revolutionizing data analytics, with practical implementation strategies and real-world examples to help organizations harness the full potential of their data assets.
Common Cloud Security Misconfigurations: Detection and Remediation
Cloud security misconfigurations have become one of the leading causes of data breaches and security incidents. As organizations rapidly adopt cloud services and infrastructure, the complexity of configurations increases, creating numerous opportunities for security gaps. According to recent industry reports, misconfigurations account for nearly 65-70% of cloud security incidents, making them a critical area of focus for security teams.
This comprehensive guide explores common cloud security misconfigurations across major cloud providers (AWS, Azure, and Google Cloud), providing detailed detection methods, remediation strategies, and prevention techniques. Whether you’re a cloud architect, security engineer, or DevOps professional, this guide will help you identify and address the most prevalent security risks in your cloud environments.
Rust's Design Philosophy and Principles: Understanding the Language's Core Values
Every programming language embodies a set of values and principles that guide its design decisions and evolution. Rust, with its unique combination of memory safety, performance, and expressiveness, is built on a foundation of carefully considered principles that shape everything from its syntax to its type system. Understanding these principles not only helps you write better Rust code but also provides insight into why Rust works the way it does and how to make decisions that align with the language’s philosophy.
Container Security Best Practices: Protecting Your Containerized Applications
As organizations increasingly adopt containerization for application deployment, securing these environments has become a critical concern. Containers introduce unique security challenges that differ from traditional infrastructure, requiring specialized approaches and tools. From vulnerable base images to insecure runtime configurations, the attack surface for containerized applications is substantial and often overlooked.
This comprehensive guide explores container security best practices across the entire container lifecycle, providing practical strategies and tools to help DevOps teams build and maintain secure containerized environments.
Go Distributed Consensus: Implementing Raft and Leader Election
In distributed systems, one of the most challenging problems is achieving consensus among a group of nodes that may experience failures, network partitions, and message delays. How do we ensure that a cluster of servers agrees on a shared state when any node might fail at any time? This fundamental problem underlies many distributed systems challenges, from database replication to distributed locking and coordination services.
Distributed consensus algorithms provide a solution by enabling a collection of machines to work as a coherent group that can survive the failures of some of its members. Among these algorithms, Raft has emerged as one of the most widely implemented due to its focus on understandability and practical implementation. Unlike more complex algorithms like Paxos, Raft was designed to be comprehensible and implementable, making it an excellent choice for Go developers building distributed systems.
Observability Patterns for Distributed Systems: Beyond Metrics, Logs, and Traces
In today’s world of microservices, serverless functions, and complex distributed systems, traditional monitoring approaches fall short. Modern systems generate vast amounts of telemetry data across numerous components, making it challenging to understand system behavior, identify issues, and troubleshoot problems. This is where observability comes in—providing deep insights into what’s happening inside your systems without having to deploy new code to add instrumentation.
This comprehensive guide explores advanced observability patterns for distributed systems, going beyond the basic “three pillars” of metrics, logs, and traces to help SRE teams build more observable systems and solve complex problems faster.
Data Mesh Architecture: A Paradigm Shift for Distributed Data
As organizations scale their data initiatives, traditional centralized data architectures—data warehouses, data lakes, and even lake houses—often struggle to keep pace with the growing complexity and domain diversity of modern enterprises. Data Mesh has emerged as a paradigm shift in how we think about and implement data architectures, particularly in distributed systems.
This article explores the principles, implementation patterns, and practical considerations for adopting Data Mesh architecture in distributed systems.
AI-Powered Code Generation: Transforming Enterprise Software Development
The landscape of software development is undergoing a profound transformation with the rise of AI-powered code generation tools. What began as simple code completion features has evolved into sophisticated systems capable of generating entire functions, classes, and even applications from natural language descriptions. For enterprise organizations, these tools offer unprecedented opportunities to accelerate development cycles, reduce technical debt, and allow developers to focus on higher-value creative work.
This comprehensive guide explores how enterprises can effectively implement AI code generation tools, establish appropriate governance frameworks, and maximize developer productivity while maintaining code quality and security.
Rust Package Management with Cargo: Beyond the Basics
Cargo, Rust’s package manager and build system, is one of the language’s greatest strengths. It handles dependency management, compilation, testing, documentation generation, and package publishing, providing a seamless experience for Rust developers. While most Rust programmers are familiar with basic Cargo commands like cargo build and cargo test, the tool offers a wealth of advanced features that can significantly improve your development workflow and help you manage complex projects more effectively.
Rust Documentation Practices: Creating Clear, Comprehensive, and Useful Docs
Documentation is a crucial aspect of software development, serving as a bridge between code authors and users. Well-written documentation helps users understand how to use your code, explains why certain design decisions were made, and guides contributors on how to extend or modify your project. Rust takes documentation seriously, providing first-class tools and conventions that make it easy to create clear, comprehensive, and useful documentation directly alongside your code.
In this comprehensive guide, we’ll explore Rust’s documentation ecosystem, from inline doc comments to full-fledged documentation websites. You’ll learn how to write effective documentation, leverage Rust’s documentation tools, and follow best practices that have emerged in the Rust community. By the end, you’ll have a solid understanding of how to create documentation that enhances the quality and usability of your Rust projects, whether you’re working on a small library or a large-scale application.
GitOps for Multi-Environment Deployments: Scaling Infrastructure as Code
As organizations scale their cloud-native applications, managing deployments across multiple environments—from development and staging to production and disaster recovery—becomes increasingly complex. GitOps has emerged as a powerful paradigm for managing this complexity by using Git as the single source of truth for declarative infrastructure and applications.
This comprehensive guide explores how to implement GitOps practices for multi-environment deployments, providing practical strategies and tools to ensure consistency, security, and scalability across your entire deployment pipeline.
SOC 2 and ISO 27001 for SaaS Companies: A Comprehensive Implementation Guide
For SaaS companies, security and compliance have evolved from optional differentiators to essential business requirements. As organizations increasingly rely on cloud-based solutions to handle sensitive data, customers and partners demand assurance that their information is protected according to recognized standards. SOC 2 and ISO 27001 have emerged as the two most important compliance frameworks for SaaS providers, serving as trusted indicators of security maturity and risk management capabilities.
This comprehensive guide explores the implementation of SOC 2 and ISO 27001 for SaaS companies. We’ll cover the requirements, implementation strategies, certification processes, and approaches for maintaining ongoing compliance. Whether you’re just starting your compliance journey or looking to enhance your existing security program, this guide provides actionable insights to help you achieve and maintain these critical certifications.
Testing and Debugging in Rust: Ensuring Code Quality and Reliability
Testing and debugging are essential aspects of software development, ensuring that code works as expected and helping to identify and fix issues when it doesn’t. Rust provides a rich set of tools and features for testing and debugging, from built-in unit testing frameworks to advanced property-based testing libraries and powerful debugging capabilities. These tools, combined with Rust’s strong type system and ownership model, help developers catch bugs early and build reliable, maintainable software.
Quantum Computing for Enterprise: Implementation Guide
Understand quantum computing applications in enterprise environments.
Understanding Quantum Computing
Quantum Computing Fundamentals
Key concepts that distinguish quantum from classical computing:
Quantum Bits (Qubits):
- Unlike classical bits (0 or 1), qubits can exist in superposition
- Can represent multiple states simultaneously
- Enable quantum computers to process vast amounts of information
- Current systems have dozens to hundreds of qubits
- Future fault-tolerant systems will require millions
Quantum Superposition:
- Qubits can exist in multiple states at once
- Allows quantum computers to explore multiple solutions simultaneously
- Creates exponential scaling of computational space
- Enables certain algorithms to achieve dramatic speedups
Quantum Entanglement:
Rust's Security Features: Building Robust, Vulnerability-Free Software
Security vulnerabilities continue to plague software systems, with memory safety issues like buffer overflows, use-after-free, and data races accounting for a significant percentage of critical CVEs (Common Vulnerabilities and Exposures). Rust was designed from the ground up with security in mind, offering a unique approach that prevents these classes of bugs at compile time without sacrificing performance. This “security by design” philosophy has made Rust increasingly popular for security-critical applications, from operating systems and browsers to cryptographic libraries and network services.
SRE Incident Management: Response and Recovery
Implement effective incident management processes.
The Foundations of Effective Incident Management
Before diving into specific practices, let’s establish the core principles that underpin effective incident management:
Key Principles
- Blameless Culture: Focus on systems and processes, not individuals
- Preparedness: Plan and practice for incidents before they occur
- Clear Ownership: Define roles and responsibilities clearly
- Proportional Response: Match the response to the severity of the incident
- Continuous Learning: Use incidents as opportunities to improve
The Incident Lifecycle
Understanding the complete incident lifecycle helps teams develop comprehensive management strategies:
Transfer Learning Techniques: Leveraging Pre-trained Models for Enterprise AI Applications
In the rapidly evolving field of artificial intelligence, transfer learning has emerged as one of the most powerful techniques for building effective models with limited data and computational resources. By leveraging knowledge gained from pre-trained models, organizations can significantly reduce the time, data, and computing power needed to develop high-performing AI applications.
This comprehensive guide explores practical transfer learning techniques that can help enterprise teams build sophisticated AI solutions even when faced with constraints on data availability and computational resources.
Serverless Architecture Patterns for Distributed Systems
Serverless computing has revolutionized how we build and deploy distributed systems, offering a model where cloud providers dynamically manage the allocation and provisioning of servers. This approach allows developers to focus on writing code without worrying about infrastructure management, scaling, or maintenance. As serverless architectures mature, distinct patterns have emerged that address common challenges in distributed systems.
This article explores key serverless architecture patterns, providing practical implementation examples and guidance on when to apply each pattern in your distributed systems.
The Future of Rust: Roadmap and Upcoming Features
Since its 1.0 release in 2015, Rust has evolved from a promising systems programming language into a mature, production-ready technology used by companies and developers worldwide. Its unique combination of performance, safety, and ergonomics has driven adoption across various domains, from operating systems and embedded devices to web services and game development. As we look to the future, Rust continues to evolve with an ambitious roadmap that aims to address current limitations, expand into new domains, and further improve developer experience.
Microservices Architecture Patterns: Design Strategies for Scalable Systems
Microservices architecture has become the dominant approach for building complex, scalable applications. By breaking down monolithic applications into smaller, independently deployable services, organizations can achieve greater agility, scalability, and resilience. However, implementing microservices effectively requires careful consideration of numerous design patterns and architectural decisions.
This comprehensive guide explores proven microservices architecture patterns that help teams navigate the complexities of distributed systems while avoiding common pitfalls. Whether you’re planning a new microservices implementation or refining an existing one, these patterns will provide valuable strategies for building robust, maintainable systems.
Service Discovery in Distributed Systems: Patterns and Implementation
In distributed systems, particularly microservices architectures, services need to find and communicate with each other efficiently. As systems scale and become more dynamic—with services being deployed, scaled, and terminated frequently—hardcoded network locations become impractical. This is where service discovery comes in, providing mechanisms for services to locate each other dynamically at runtime.
This article explores various service discovery patterns, their implementation approaches, and best practices for building robust service discovery mechanisms in distributed systems.
Rust Interoperability: Seamlessly Working with Other Languages
One of Rust’s greatest strengths is its ability to interoperate with other programming languages. This interoperability allows developers to gradually introduce Rust into existing projects, leverage specialized libraries from other ecosystems, and build components that can be used across different platforms and languages. Whether you’re looking to speed up a Python application with Rust, integrate Rust components into a C++ codebase, or expose Rust functionality to JavaScript, the language provides robust tools and patterns for seamless integration.
Edge Computing Architectures: Bringing Computation Closer to Data Sources
As data volumes grow exponentially and latency requirements become more stringent, traditional cloud computing models face increasing challenges. Edge computing has emerged as a powerful paradigm that brings computation and data storage closer to the sources of data, enabling faster processing, reduced bandwidth usage, and new capabilities for real-time applications. From IoT devices and autonomous vehicles to content delivery and industrial automation, edge computing is transforming how we architect distributed systems.
Automated Remediation: Building Self-Healing Systems for Modern SRE Teams
In the world of Site Reliability Engineering (SRE), the goal has always been to reduce toil—repetitive, manual work that adds little value and scales linearly with service growth. One of the most effective ways to achieve this is through automated remediation: the practice of automatically detecting and fixing common issues without human intervention. By building self-healing systems, SRE teams can not only improve reliability but also free up valuable time for strategic engineering work.
SRE Capacity Planning: Resource Management
Master capacity planning techniques.
Understanding Capacity Planning for SRE
Before diving into specific methodologies, let’s establish what capacity planning means in the context of Site Reliability Engineering.
What is Capacity Planning?
Capacity planning is the process of determining the resources required to meet expected workloads while maintaining service level objectives (SLOs). For SRE teams, this involves:
- Forecasting demand: Predicting future workload based on historical data and business projections
- Resource modeling: Understanding how workload translates to resource requirements
- Capacity allocation: Provisioning appropriate resources across services and regions
- Performance analysis: Ensuring systems meet performance targets under expected load
- Cost optimization: Balancing reliability requirements with infrastructure costs
Why Capacity Planning Matters for SRE
Effective capacity planning directly impacts several key aspects of reliability engineering:
Rust's Ecosystem and Community: The Foundation of Success
A programming language is more than just syntax and features—it’s also the ecosystem of libraries, tools, and resources that surround it, and the community of people who use, develop, and advocate for it. Rust has distinguished itself not only through its technical merits but also through its exceptionally vibrant ecosystem and welcoming community. From the comprehensive package manager Cargo to the collaborative governance model, Rust’s ecosystem and community have been instrumental in the language’s growing adoption and success.
Data Consistency Models in Distributed Systems
In distributed systems, one of the most challenging aspects is managing data consistency across multiple nodes. The CAP theorem tells us that we can’t simultaneously achieve perfect consistency, availability, and partition tolerance—we must make trade-offs. Understanding these trade-offs and the spectrum of consistency models is crucial for designing distributed systems that meet your specific requirements.
This article explores the various consistency models available in distributed systems, from strong consistency to eventual consistency, and provides guidance on selecting the appropriate model for your application needs.
Building an AI Ethics and Governance Framework for Enterprise Applications
As artificial intelligence becomes increasingly embedded in enterprise applications and decision-making processes, organizations face growing pressure to ensure their AI systems are developed and deployed responsibly. Beyond regulatory compliance, implementing robust AI ethics and governance frameworks has become a business imperative—protecting against reputational damage, enhancing customer trust, and mitigating risks associated with AI deployment.
This comprehensive guide explores how to build and implement an effective AI ethics and governance framework for enterprise applications, providing practical strategies and tools that technical leaders can use to ensure responsible AI development and deployment.
Machine Learning with Rust: Performance and Safety for AI Applications
Machine learning has traditionally been dominated by languages like Python, which offer ease of use and a rich ecosystem of libraries. However, as models grow larger and performance requirements become more demanding, there’s increasing interest in alternatives that can provide better efficiency without sacrificing developer productivity. Rust, with its focus on performance, safety, and modern language features, is emerging as a compelling option for machine learning applications, particularly in production environments where speed and reliability are critical.
Site Reliability Engineering Fundamentals: Building and Scaling Reliable Services
Site Reliability Engineering (SRE) has emerged as a critical discipline at the intersection of software engineering and operations. Pioneered by Google and now adopted by organizations of all sizes, SRE applies software engineering principles to operations and infrastructure challenges, with a focus on creating scalable and highly reliable software systems. As distributed systems grow more complex, the principles and practices of SRE have become essential for maintaining service reliability while enabling rapid innovation.
Data Engineering Best Practices: Building Robust Pipelines
Master data engineering principles.
Data Pipeline Architecture
Architectural Patterns
Foundational approaches to data pipeline design:
Batch Processing:
- Processing data in scheduled intervals
- Handling large volumes efficiently
- Optimizing for throughput over latency
- Implementing idempotent operations
- Managing dependencies between jobs
Stream Processing:
- Processing data in near real-time
- Handling continuous data flows
- Implementing windowing strategies
- Managing state and checkpointing
- Ensuring exactly-once processing
Lambda Architecture:
- Combining batch and streaming layers
- Providing both accurate and real-time views
- Managing duplicate processing logic
- Reconciling batch and speed layers
- Optimizing for different access patterns
Kappa Architecture:
API Design for Distributed Systems: Principles and Best Practices
In distributed systems, APIs serve as the critical interfaces between services, enabling communication, integration, and collaboration across components. Well-designed APIs can significantly enhance system flexibility, maintainability, and scalability, while poorly designed ones can lead to tight coupling, performance bottlenecks, and brittle architectures. As organizations increasingly adopt microservices and distributed architectures, mastering API design has become an essential skill for modern software engineers.
This article explores key principles, patterns, and best practices for designing effective APIs in distributed systems, with practical examples to guide your implementation.
Game Development with Rust: Building Fast, Reliable Games
Game development demands a unique combination of performance, reliability, and expressiveness from programming languages. Traditionally dominated by C++ for its speed and control, the field is now seeing growing interest in Rust as an alternative. Rust offers comparable performance to C++ while eliminating entire classes of bugs through its ownership system and providing modern language features that improve developer productivity. From indie 2D games to high-performance game engines, Rust is proving to be a compelling choice for game developers.
DevSecOps Implementation Guide: Integrating Security into the Development Lifecycle
As organizations accelerate their digital transformation and software delivery, security can no longer be an afterthought or a final checkpoint before deployment. DevSecOps—the integration of security practices within the DevOps process—has emerged as a critical approach for building secure applications from the ground up. By embedding security throughout the software development lifecycle, organizations can deliver secure, compliant applications without sacrificing speed or agility.
This comprehensive guide explores the principles, practices, tools, and cultural changes needed to successfully implement DevSecOps in your organization. Whether you’re just starting your DevSecOps journey or looking to enhance your existing practices, this guide provides actionable strategies to integrate security into every phase of your development process.
Embedded Systems Programming with Rust: Safety and Performance for Resource-Constrained Devices
Embedded systems programming has traditionally been dominated by C and C++, languages that offer the low-level control and performance necessary for resource-constrained environments. However, these languages also come with significant drawbacks, particularly in terms of memory safety and modern language features. Rust offers a compelling alternative, providing the same level of control and performance while eliminating entire classes of bugs through its ownership system and zero-cost abstractions.
In this comprehensive guide, we’ll explore how Rust is changing the landscape of embedded systems development. From bare-metal programming on microcontrollers to higher-level abstractions for IoT devices, you’ll learn how Rust’s unique features make it an excellent choice for embedded applications. By the end, you’ll understand how to leverage Rust’s safety and performance for your own embedded projects, whether you’re building a simple sensor node or a complex industrial control system.
Monitoring and Observability in Distributed Systems
In the world of distributed systems, understanding what’s happening across your services is both critical and challenging. As systems grow in complexity—spanning multiple services, data stores, and infrastructure components—traditional monitoring approaches fall short. This is where modern monitoring and observability practices come into play, providing the visibility needed to operate distributed systems with confidence.
This article explores the evolution from basic monitoring to comprehensive observability, providing practical guidance on implementing effective observability practices in distributed systems.
Real-Time Data Processing: Stream Analytics
Build real-time data processing systems using stream processing frameworks.
Real-Time Data Processing Fundamentals
Core Concepts and Terminology
Understanding the building blocks of real-time systems:
Real-Time Processing vs. Batch Processing:
- Real-time: Continuous processing with minimal latency
- Batch: Periodic processing of accumulated data
- Micro-batch: Small batches with higher frequency
- Near real-time: Low but not immediate latency
- Stream processing: Continuous data flow processing
Key Concepts:
- Events: Discrete data records representing occurrences
- Streams: Unbounded sequences of events
- Producers: Systems generating event data
- Consumers: Systems processing event data
- Topics/Channels: Named streams for event organization
- Partitions: Subdivisions of streams for parallelism
- Offsets: Positions within event streams
Processing Semantics:
Event-Driven Architecture Patterns: Building Responsive and Scalable Systems
Event-driven architecture (EDA) has emerged as a powerful architectural paradigm for building responsive, scalable, and resilient distributed systems. By decoupling components through asynchronous event-based communication, EDA enables organizations to build systems that can handle complex workflows, scale independently, and evolve more flexibly than traditional request-response architectures. However, implementing EDA effectively requires understanding various patterns, technologies, and trade-offs.
This comprehensive guide explores event-driven architecture patterns, covering event sourcing, CQRS, message brokers, stream processing, and implementation strategies. Whether you’re designing a new system or evolving an existing one, these insights will help you leverage event-driven approaches to build systems that can adapt to changing business requirements while maintaining performance, reliability, and maintainability.
Web Development with Rust: An Introduction to Building Fast, Secure Web Applications
Web development with Rust is gaining momentum as developers seek alternatives that offer better performance, improved security, and fewer runtime surprises than traditional web stacks. While Rust wasn’t initially designed for web development, its emphasis on safety, speed, and concurrency makes it an excellent fit for modern web applications that need to be reliable and efficient. From low-level HTTP servers to full-stack frameworks, the Rust ecosystem now offers a variety of tools for building web applications at different levels of abstraction.
Testing Distributed Systems: Strategies for Ensuring Reliability
Testing distributed systems presents unique challenges that go far beyond traditional application testing. With components spread across multiple machines, complex network interactions, and various failure modes, ensuring reliability requires specialized testing strategies. Traditional testing approaches often fall short when confronted with the complexities of distributed environments, where issues like network partitions, race conditions, and partial failures can lead to subtle and hard-to-reproduce bugs.
This article explores comprehensive testing strategies for distributed systems, providing practical approaches to validate functionality, performance, and resilience across distributed components.
AI Anomaly Detection Systems: Architectures and Implementation
Anomaly detection has become a critical capability for modern organizations, enabling them to identify unusual patterns that could indicate security breaches, system failures, performance issues, or business opportunities. With the explosion of data from infrastructure, applications, and business processes, traditional rule-based approaches to anomaly detection are no longer sufficient. This is where AI-powered anomaly detection systems come in, offering the ability to automatically learn normal patterns and identify deviations without explicit programming.
GraphQL API Design Best Practices: Building Flexible and Efficient APIs
GraphQL has transformed API development by enabling clients to request exactly the data they need, reducing over-fetching and under-fetching that plague traditional REST APIs. Since its public release by Facebook in 2015, GraphQL has gained widespread adoption across organizations of all sizes, from startups to enterprises. However, building a well-designed GraphQL API requires careful consideration of schema design, performance optimization, security, and maintainability.
This comprehensive guide explores GraphQL API design best practices, covering schema design principles, performance optimization techniques, security considerations, versioning strategies, and implementation approaches. Whether you’re building your first GraphQL API or looking to improve existing implementations, these insights will help you create flexible, efficient, and maintainable GraphQL APIs that deliver an exceptional developer experience.
File I/O in Rust: Reading and Writing Files Safely and Efficiently
File input and output (I/O) operations are fundamental to many applications, from configuration management to data processing. Rust’s approach to file I/O combines safety, performance, and ergonomics, providing powerful abstractions that prevent common errors while maintaining fine-grained control when needed. Unlike languages with implicit error handling or those that ignore potential failures, Rust’s type system ensures that file operations are handled correctly, making your code more robust and reliable.
In this comprehensive guide, we’ll explore Rust’s file I/O capabilities, from basic reading and writing to advanced techniques like memory mapping and asynchronous I/O. You’ll learn how to work with files efficiently, handle errors gracefully, and choose the right approach for different scenarios. By the end, you’ll have a solid understanding of how to perform file operations in Rust that are both safe and performant.
Kubernetes Advanced Deployment Strategies: Beyond Rolling Updates
Kubernetes has revolutionized how we deploy and manage containerized applications, with its built-in rolling update strategy providing a solid foundation for zero-downtime deployments. However, as applications grow in complexity and criticality, more sophisticated deployment strategies become necessary to minimize risk, validate changes in production, and respond quickly to issues.
This comprehensive guide explores advanced deployment strategies in Kubernetes that go beyond basic rolling updates. We’ll cover blue-green deployments, canary releases, A/B testing, and progressive delivery patterns, with practical examples and implementation guidance. Whether you’re looking to reduce deployment risk, test features with real users, or build a fully automated progressive delivery pipeline, this guide will help you implement the right strategy for your needs.
Security in Distributed Systems: Challenges and Best Practices
Security in distributed systems presents unique challenges that go beyond traditional application security. With components spread across multiple machines, networks, and potentially different trust domains, the attack surface expands dramatically. Each communication channel, data store, and service becomes a potential entry point for attackers. As organizations increasingly adopt distributed architectures, understanding how to secure these complex systems has become a critical concern.
This article explores the key security challenges in distributed systems and provides practical strategies and best practices to address them effectively.
Kubernetes Networking: Advanced Cluster Communication
Master Kubernetes networking including CNI.
Introduction and Setup
Kubernetes networking has a reputation for being complex, and honestly, that reputation is well-deserved. The challenge isn’t that the concepts are inherently difficult—it’s that they’re completely different from traditional networking. If you’re coming from a world of VLANs, subnets, and static IP addresses, Kubernetes networking requires a fundamental shift in thinking.
The good news is that once you understand the core principles, Kubernetes networking is actually quite elegant. It’s dynamic, software-defined, and surprisingly simple—once you stop fighting it and start working with its design philosophy.
AI Governance Frameworks: Building Responsible AI Systems
As artificial intelligence becomes increasingly integrated into critical business systems and decision-making processes, organizations face growing pressure to ensure their AI systems are developed and deployed responsibly. AI governance frameworks provide structured approaches to managing AI risks, ensuring ethical compliance, and maintaining regulatory alignment. Without proper governance, organizations risk developing AI systems that make biased decisions, violate privacy, lack transparency, or create other unintended consequences.
This comprehensive guide explores AI governance frameworks, covering risk management, ethical principles, regulatory compliance, and best practices. Whether you’re just beginning to implement AI or looking to enhance governance of existing AI systems, these insights will help you build more responsible, trustworthy, and compliant AI capabilities.
Rust's Standard Library: Essential Tools for Every Project
Rust’s standard library is a carefully curated collection of core components that provide essential functionality for almost every Rust program. Unlike some languages that include “batteries” for nearly every use case, Rust’s standard library is intentionally focused, offering only the most fundamental tools while leaving more specialized functionality to the crate ecosystem. This design philosophy ensures that the standard library remains lean, well-maintained, and suitable for a wide range of environments, from embedded systems to web servers.
Kubernetes Security: Cluster and Workload Protection
Security in Kubernetes isn’t just about locking down your cluster—it’s about building a defense-in-depth strategy that protects your workloads, data, and infrastructure while maintaining operational efficiency. This guide takes you through the essential security practices that separate production-ready clusters from development environments.
Security Foundations
Kubernetes security isn’t something you can add as an afterthought—it needs to be designed into your cluster architecture from the beginning. The difference between a secure cluster and a vulnerable one often comes down to understanding the fundamental security model and implementing proper controls at every layer.
Quantum Computing in Distributed Systems: Preparing for the Quantum Future
Quantum computing represents one of the most significant technological revolutions on the horizon, with the potential to transform how we approach complex computational problems. As quantum computers continue to advance, their integration with distributed systems will create new possibilities and challenges for system architects and developers. While fully fault-tolerant quantum computers are still developing, organizations should begin preparing for the quantum future today.
This article explores the intersection of quantum computing and distributed systems, examining how quantum technologies will impact distributed architectures and providing practical guidance on preparing for the quantum advantage.
Building Fault-Tolerant Distributed Systems: Strategies and Patterns
In distributed systems, failures are not just possible—they’re inevitable. Networks partition, servers crash, disks fail, and software bugs manifest in production. Building systems that can withstand these failures while maintaining acceptable service levels is the essence of fault tolerance. As distributed architectures become increasingly complex, mastering fault tolerance has never been more critical.
This article explores strategies, patterns, and practical techniques for building fault-tolerant distributed systems that can gracefully handle failures without catastrophic service disruptions.
Macros in Rust: Metaprogramming Made Simple
Macros are one of Rust’s most powerful features, enabling metaprogramming—code that writes code. Unlike macros in C and C++, which are simple text substitution mechanisms, Rust’s macros are hygienic and operate on the abstract syntax tree (AST), making them both powerful and safe. They allow you to extend the language, reduce boilerplate, create domain-specific languages, and implement compile-time code generation without sacrificing Rust’s safety guarantees.
In this comprehensive guide, we’ll explore Rust’s macro system in depth, from basic declarative macros to advanced procedural macros. You’ll learn how macros work, when to use them, and how to write your own macros to solve real-world problems. By the end, you’ll have a solid understanding of how to leverage Rust’s macro system to write more expressive, maintainable, and DRY (Don’t Repeat Yourself) code.
API Security Best Practices: Protecting Your Digital Interfaces
As organizations increasingly expose their services and data through APIs, these interfaces have become prime targets for attackers. According to recent studies, API attacks have grown by over 300% in the past two years, with the average organization experiencing dozens of API security incidents annually. The consequences of API breaches can be severe, ranging from data theft and service disruption to regulatory penalties and reputational damage.
This comprehensive guide explores API security best practices, covering authentication, authorization, encryption, rate limiting, input validation, and monitoring. Whether you’re building new APIs or securing existing ones, these insights will help you implement robust protection against common vulnerabilities and attacks, ensuring your digital interfaces remain secure, reliable, and compliant with regulatory requirements.
Rust Memory Safety: How Ownership & the Borrow Checker Actually Work
Memory-related bugs are among the most pernicious issues in software development. Buffer overflows, use-after-free errors, double frees, and data races have plagued systems programming for decades, leading to security vulnerabilities, crashes, and unpredictable behavior. Traditional approaches to solving these problems involve either manual memory management (prone to human error) or garbage collection (which introduces runtime overhead and unpredictable pauses).
Rust takes a revolutionary approach to memory safety by enforcing strict rules at compile time through its ownership system, borrow checker, and type system. This approach ensures memory safety without garbage collection, combining the performance of languages like C and C++ with the safety guarantees typically associated with higher-level languages.
LLM Production Deployment: Architectures, Strategies, and Best Practices
Large Language Models (LLMs) have revolutionized natural language processing and AI applications, enabling capabilities that were previously impossible. However, deploying these powerful models in production environments presents unique challenges due to their size, computational requirements, and the complexity of the systems needed to serve them efficiently.
This comprehensive guide explores the architectures, strategies, and best practices for deploying LLMs in production. Whether you’re working with open-source models like Llama 2 or Mistral, fine-tuned variants, or commercial APIs like OpenAI’s GPT-4, this guide will help you navigate the complexities of building robust, scalable, and cost-effective LLM-powered applications.
Rust for Robotics in 2025: Libraries, Tools, and Best Practices
Robotics development presents unique challenges that demand high performance, reliability, and safety guarantees. From industrial automation and autonomous vehicles to consumer robots and drones, these systems must interact with the physical world in real-time while ensuring predictable behavior. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for robotics development.
In this comprehensive guide, we’ll explore Rust’s ecosystem for robotics as it stands in early 2025. We’ll examine the libraries, frameworks, and tools that have matured over the years, providing developers with robust building blocks for creating efficient and reliable robotic systems. Whether you’re building industrial robots, autonomous drones, or experimental platforms, this guide will help you navigate the rich landscape of Rust’s robotics ecosystem.
Concurrency in Rust: Fearless Parallelism
Concurrency is notoriously difficult to get right. Race conditions, deadlocks, and other concurrency bugs are among the most insidious issues in software development, often manifesting only under specific timing conditions that are hard to reproduce and debug. Rust tackles this challenge head-on with a concurrency model that leverages the type system and ownership rules to prevent data races and other concurrency errors at compile time.
In this comprehensive guide, we’ll explore Rust’s approach to concurrency, from basic threads to advanced asynchronous programming. You’ll learn how Rust’s ownership system enables “fearless concurrency”—the ability to write concurrent code with confidence that the compiler will catch common mistakes before they become runtime bugs. By the end, you’ll have a solid understanding of how to build efficient, safe concurrent applications in Rust.
Case Study: How We Cut Cloud Costs by 30% Without Sacrificing Performance
Cloud cost optimization is a critical concern for organizations of all sizes, but particularly for growing companies that experience the shock of rapidly escalating cloud bills as they scale. At Ataiva, we recently worked with TechNova, a mid-sized SaaS company experiencing this exact challenge. Their monthly AWS bill had grown from $50,000 to over $200,000 in just 18 months as their customer base expanded, putting significant pressure on margins and raising concerns among investors.
Lifetimes in Rust: Managing References Safely
Lifetimes are one of Rust’s most distinctive and initially challenging features. While other aspects of Rust’s ownership system deal with who owns a value, lifetimes address how long references to that value remain valid. This mechanism ensures memory safety without a garbage collector by validating at compile time that no reference outlives the data it points to—a common source of bugs in languages like C and C++.
In this comprehensive guide, we’ll explore Rust’s lifetime system in depth, from basic concepts to advanced patterns. You’ll learn how lifetimes work, when and how to use lifetime annotations, and techniques for handling complex borrowing scenarios. By the end, you’ll have a solid understanding of how lifetimes contribute to Rust’s memory safety guarantees and how to leverage them effectively in your code.
Rust for Computer Vision in 2025: Libraries, Tools, and Best Practices
Computer vision and image processing applications demand high performance, reliability, and often real-time capabilities. From autonomous vehicles and robotics to augmented reality and medical imaging, these systems process enormous amounts of visual data and must do so efficiently and safely. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for computer vision development.
In this comprehensive guide, we’ll explore Rust’s ecosystem for computer vision and image processing as it stands in early 2025. We’ll examine the libraries, frameworks, and tools that have matured over the years, providing developers with robust building blocks for creating efficient and reliable vision applications. Whether you’re building real-time video processing systems, image analysis tools, or integrating computer vision with machine learning, this guide will help you navigate the rich landscape of Rust’s computer vision ecosystem.
Kubernetes Operators: Custom Resource Management
Build and deploy Kubernetes operators for automated application management.
Introduction and Setup
When I first started working with Kubernetes, I quickly realized that managing complex applications required more than just deploying pods and services. That’s where operators come in - they’re like having an experienced system administrator encoded in software, continuously managing your applications with domain-specific knowledge.
Understanding Kubernetes Operators
Operators extend Kubernetes by combining Custom Resource Definitions (CRDs) with controllers that understand how to manage specific applications. I’ve seen teams struggle with manual database backups, complex scaling decisions, and application lifecycle management. Operators solve these problems by automating operational tasks that would otherwise require human intervention.
Blockchain in Enterprise Distributed Systems: Beyond Cryptocurrencies
While blockchain technology first gained prominence as the foundation for cryptocurrencies like Bitcoin, its potential applications extend far beyond digital currencies. At its core, blockchain is a distributed ledger technology that provides a secure, transparent, and immutable record of transactions across a decentralized network. These properties make it particularly valuable for enterprise distributed systems that require trust, transparency, and data integrity across multiple parties.
This article explores practical enterprise applications of blockchain technology in distributed systems, examining implementation patterns, challenges, and best practices for organizations looking to leverage this transformative technology.
Infrastructure as Code Best Practices: Beyond the Basics
Infrastructure as Code (IaC) has revolutionized how organizations manage their cloud resources, enabling teams to provision and manage infrastructure through machine-readable definition files rather than manual processes. While most teams have adopted basic IaC practices, many struggle to implement the advanced patterns and workflows that lead to truly maintainable, secure, and efficient infrastructure management.
This comprehensive guide explores advanced Infrastructure as Code best practices that go beyond the basics. We’ll cover strategies for testing, security, modularity, team workflows, and more—all designed to help you elevate your IaC implementation from functional to exceptional. Whether you’re using Terraform, CloudFormation, Pulumi, or another IaC tool, these principles will help you build more robust infrastructure management capabilities.
Distributed Caching Strategies for High-Performance Applications
In today’s digital landscape, where milliseconds can make the difference between user engagement and abandonment, caching has become an indispensable technique for building high-performance applications. As systems scale and distribute across multiple servers or regions, simple in-memory caching is no longer sufficient. This is where distributed caching comes into play—providing a shared cache that spans multiple servers, enabling consistent performance across distributed applications.
This article explores distributed caching strategies, patterns, and implementations that can help you build faster, more scalable applications while reducing the load on your databases and backend services.
Rust for Audio Programming in 2025: Libraries, Tools, and Best Practices
Audio programming presents unique challenges that demand both high performance and reliability. From real-time digital signal processing to music creation tools, audio applications require low latency, predictable memory usage, and freedom from unexpected crashes or glitches. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for audio development.
In this comprehensive guide, we’ll explore Rust’s ecosystem for audio programming as it stands in early 2025. We’ll examine the libraries, frameworks, and tools that have matured over the years, providing developers with robust building blocks for creating efficient and reliable audio applications. Whether you’re building digital audio workstations, audio plugins, embedded audio devices, or game audio engines, this guide will help you navigate the rich landscape of Rust’s audio programming ecosystem.
Traits in Rust: Interfaces with Superpowers
In object-oriented programming, interfaces define a contract that implementing classes must fulfill. Rust’s trait system serves a similar purpose but goes far beyond traditional interfaces, offering a powerful mechanism for defining shared behavior, enabling polymorphism, and creating flexible abstractions—all while maintaining Rust’s guarantees of memory safety and performance.
Traits are one of Rust’s most distinctive and powerful features, enabling code reuse without inheritance and polymorphism without runtime overhead. In this comprehensive guide, we’ll explore Rust’s trait system in depth, from basic usage to advanced patterns. You’ll learn how to define and implement traits, use trait bounds, work with trait objects, and leverage traits to write generic code that is both flexible and efficient.
Kubernetes Configuration Management
Master Kubernetes configuration with ConfigMaps.
Introduction and Setup
Configuration management in Kubernetes nearly broke me when I first started trying to use it. I spent three days debugging why my application couldn’t connect to the database, only to discover I’d misspelled “postgres” as “postgress” in a ConfigMap. That typo taught me more about Kubernetes configuration than any documentation ever could.
The frustrating truth about Kubernetes configuration is that it looks simple until you need it to work reliably across environments. ConfigMaps and Secrets seem straightforward, but managing configuration at scale requires patterns that aren’t obvious from the basic examples.
Working with Structs and Enums in Rust: Building Robust Data Models
Data modeling is at the heart of software development, and the tools a language provides for representing data significantly impact code quality, maintainability, and correctness. Rust offers two powerful constructs for modeling data: structs and enums. These complementary tools allow developers to express complex data relationships with precision while leveraging Rust’s type system to prevent entire categories of bugs at compile time.
In this comprehensive guide, we’ll explore Rust’s structs and enums in depth, from basic usage to advanced patterns. You’ll learn how to create flexible, type-safe data models that express your domain concepts clearly and leverage the compiler to catch errors early. By the end, you’ll have a solid understanding of when and how to use each construct effectively in your Rust projects.
SLO and SLI Implementation Guide: Building Reliable Services
In today’s digital landscape, reliability has become a critical differentiator for services and products. Users expect systems to be available, responsive, and correct—all the time. However, pursuing 100% reliability is not only prohibitively expensive but often unnecessary. This is where Service Level Objectives (SLOs) and Service Level Indicators (SLIs) come in, providing a framework to define, measure, and maintain appropriate reliability targets that balance user expectations with engineering costs.
This comprehensive guide explores the practical aspects of implementing SLOs and SLIs in your organization. We’ll cover everything from selecting the right metrics to building the technical infrastructure needed to track them, and establishing the processes to act on the resulting data. Whether you’re just starting with reliability engineering or looking to refine your existing practices, this guide provides actionable insights to help you build more reliable services.
Pattern Matching in Rust: Powerful, Expressive, and Safe
Pattern matching stands as one of Rust’s most powerful and distinctive features, elevating it beyond a mere control flow mechanism to a fundamental aspect of the language’s design philosophy. Unlike the simple switch statements found in many languages, Rust’s pattern matching system provides a rich, expressive way to destructure complex data types, handle multiple conditions, and ensure exhaustive checking of all possible cases. This combination of power and safety makes pattern matching an essential tool in every Rust programmer’s toolkit.
Rust's Blockchain Development Ecosystem in 2025
Blockchain technology has evolved significantly since the introduction of Bitcoin in 2009, expanding beyond cryptocurrencies to encompass smart contracts, decentralized finance (DeFi), non-fungible tokens (NFTs), and various forms of decentralized applications (dApps). As blockchain systems have grown more complex and demanding, the need for programming languages that prioritize safety, performance, and reliability has become increasingly apparent. Rust, with its focus on memory safety without sacrificing performance, has emerged as a leading language for blockchain development.
Scaling Startups with Cloud Best Practices
Scaling a startup’s technical infrastructure is one of the most challenging aspects of company growth. As user numbers increase, feature sets expand, and market demands evolve, the technology decisions made in the early days are put to the test. Cloud computing has revolutionized how startups scale, offering unprecedented flexibility and power—but also introducing complexity and potential pitfalls.
This comprehensive guide explores cloud best practices for scaling startups, covering everything from architectural patterns and cost optimization to security, DevOps, and organizational strategies. Whether you’re experiencing hypergrowth or planning for sustainable expansion, these practices will help you build a robust, efficient, and adaptable cloud infrastructure that supports your business goals.
MLOps Pipeline Architecture: Building Production-Ready ML Systems
Machine learning has moved beyond research and experimentation to become a critical component of many production systems. However, successfully deploying and maintaining ML models in production requires more than just good data science—it demands robust engineering practices, automated pipelines, and governance frameworks. This is where MLOps (Machine Learning Operations) comes in, bridging the gap between ML development and operational excellence.
This comprehensive guide explores the architecture of production-grade MLOps pipelines, covering everything from data preparation to model monitoring. Whether you’re building your first ML system or looking to improve your existing ML operations, this guide provides practical insights and implementation patterns for creating reliable, scalable, and governable machine learning systems.
Rust Error Handling (2025): Result, Option & the ? Operator Explained
Error handling is a critical aspect of writing reliable software, yet it’s often treated as an afterthought in many programming languages. Some languages rely on exceptions that can be easily overlooked, while others use error codes that can be ignored. Rust takes a fundamentally different approach by making error handling explicit through its type system, primarily using the Result and Option types. This approach ensures that errors are handled deliberately rather than by accident or omission. This error handling system works hand-in-hand with Rust’s ownership system to create safe, reliable code.
Rust's Distributed Systems Ecosystem in 2025
Distributed systems have become the backbone of modern computing infrastructure, powering everything from cloud services and microservices architectures to blockchain networks and IoT platforms. Building these systems presents unique challenges: network partitions, partial failures, consistency issues, and the inherent complexity of coordinating multiple nodes. Rust, with its focus on reliability, performance, and fine-grained control, has emerged as an excellent language for tackling these challenges.
In this comprehensive guide, we’ll explore Rust’s ecosystem for building distributed systems as it stands in early 2025. We’ll examine the libraries, frameworks, and tools that have matured over the years, providing developers with robust building blocks for creating reliable and scalable distributed applications. Whether you’re building a microservices architecture, a peer-to-peer network, or a distributed database, this guide will help you navigate the rich landscape of Rust’s distributed systems ecosystem.
Rust's Type System: A Deep Dive into Safety and Expressiveness
Rust’s type system stands as one of its most powerful features, combining the expressiveness of modern languages with the safety guarantees that systems programming demands. Unlike dynamically typed languages that defer type checking to runtime, or statically typed languages with escape hatches that can lead to undefined behavior, Rust’s type system is designed to catch errors at compile time while remaining flexible enough for real-world programming challenges.
In this comprehensive exploration, we’ll dive deep into Rust’s type system, examining how it balances safety and expressiveness. We’ll cover everything from basic types to advanced type-level programming techniques, providing you with the knowledge to leverage Rust’s type system to its fullest potential. By the end, you’ll understand why Rust’s approach to types is a game-changer for building reliable software.
Borrowing and References in Rust: The Art of Safe Memory Sharing
In our previous exploration of Rust’s ownership system, we established how Rust manages memory through a set of compile-time rules that track the ownership of values. While ownership provides the foundation for Rust’s memory safety guarantees, constantly transferring ownership would make code unnecessarily complex and inefficient. This is where Rust’s borrowing system comes into play—a sophisticated mechanism that allows you to use values without transferring ownership.
Borrowing, implemented through references, is what makes Rust’s ownership model practical for everyday programming. It enables multiple parts of your code to access the same data concurrently while still maintaining Rust’s strict safety guarantees. In this comprehensive guide, we’ll dive deep into Rust’s borrowing system, explore the nuances of references, and uncover advanced patterns that will elevate your Rust programming skills.
Implementing Distributed Tracing: A Practical Guide for Modern Applications
In today’s world of distributed systems and microservices architectures, understanding the flow of requests across dozens or even hundreds of services has become increasingly challenging. When a user experiences a slow response or an error, pinpointing the root cause can feel like searching for a needle in a haystack. This is where distributed tracing comes in—providing a powerful lens through which we can observe, understand, and optimize our distributed applications.
Rust Security Features and Best Practices in 2025
Security has become a paramount concern in software development, with vulnerabilities and exploits causing billions in damages annually. As systems become more interconnected and complex, the need for programming languages that prioritize security by design has never been greater. Rust, with its focus on memory safety without sacrificing performance, has positioned itself as a leading language for security-critical applications. By eliminating entire classes of bugs at compile time, Rust provides developers with powerful tools to write secure code from the ground up.
Kubernetes Pod Security Policies: Best Practices for Cluster Protection
As Kubernetes adoption continues to grow across organizations of all sizes, securing containerized workloads has become a critical concern. Pod Security Policies (PSPs) and their successor, Pod Security Admission, represent Kubernetes’ native approach to enforcing security best practices at the pod level. By controlling the security-sensitive aspects of pod specifications, these mechanisms help prevent privilege escalation and limit the potential damage from container-based attacks.
This comprehensive guide explores how to implement effective pod security controls in Kubernetes, covering both the legacy Pod Security Policies and the newer Pod Security Standards and Admission Controller. You’ll learn practical strategies for balancing security with operational requirements, implementing defense in depth, and addressing common security challenges in Kubernetes environments.
Understanding Rust's Ownership System: The Key to Memory Safety
Rust’s ownership system stands as one of the language’s most revolutionary contributions to systems programming. While other languages rely on garbage collection or manual memory management, Rust introduces a third approach: ownership with borrowing. This system enables Rust to guarantee memory safety at compile time without runtime overhead, preventing entire categories of bugs that plague other languages. For developers coming from languages like C++, Java, or Python, understanding ownership is the key to unlocking Rust’s full potential. This ownership system is also a key part of Rust’s security features and best practices and works hand-in-hand with Rust’s error handling system.
Privacy Policy
Privacy Policy
Last Updated: January 15, 2025
This Privacy Policy describes how andrewodendaal.com (“we”, “our”, or “us”) collects, uses, and protects your information when you visit our website.
Information We Collect
Automatically Collected Information
When you visit our site, we automatically collect certain information about your device and usage:
- IP address and general location
- Browser type and version
- Operating system
- Pages visited and time spent
- Referring website
- Device type (desktop, mobile, tablet)
Cookies and Tracking Technologies
We use cookies and similar technologies to:
Terms of Service
Terms of Service
Last Updated: January 15, 2025
These Terms of Service (“Terms”) govern your use of andrewodendaal.com (“the Site”) operated by Andrew Odendaal (“we”, “our”, or “us”).
Acceptance of Terms
By accessing and using this website, you accept and agree to be bound by the terms and provision of this agreement. If you do not agree to abide by the above, please do not use this service.
Use License
Permission is granted to temporarily download one copy of the materials on andrewodendaal.com for personal, non-commercial transitory viewing only. This is the grant of a license, not a transfer of title, and under this license you may not:
Distributed Systems Fundamentals: Core Concepts Every Developer Should Know
In today’s interconnected world, distributed systems have become the backbone of modern software architecture. From global e-commerce platforms to real-time collaboration tools, distributed systems enable applications to scale beyond the confines of a single machine, providing resilience, performance, and global reach. However, with these benefits come significant challenges that every developer must understand to build effective distributed applications.
This article explores the fundamental concepts of distributed systems, providing a solid foundation for developers looking to navigate this complex but essential domain. We’ll examine the core principles, common challenges, and practical approaches that form the basis of distributed system design.
Getting Started with Rust: A Comprehensive Installation and Setup Guide
Rust has emerged as one of the most promising programming languages of the decade, offering an unparalleled combination of performance, reliability, and productivity. Whether you’re a seasoned developer looking to expand your toolkit or a newcomer to systems programming, setting up Rust correctly is your first step toward mastering this powerful language. This comprehensive guide will walk you through the installation process across different operating systems, help you configure your development environment, and introduce you to essential tools in the Rust ecosystem.
Rust Interoperability: Seamlessly Working with Other Languages in 2025
In today’s complex software landscape, few applications are built using a single programming language. Different languages offer different strengths, and existing codebases represent significant investments that can’t be rewritten overnight. This reality makes language interoperability—the ability for code written in different languages to work together seamlessly—a critical feature for any modern programming language. Rust, with its focus on safety, performance, and practicality, has developed robust interoperability capabilities that allow it to integrate smoothly with a wide range of other languages.
Rust's unwrap: Unlocking Its Potential and Avoiding Pitfalls
Learn how to effectively use Rust’s unwrap method, including its benefits, risks, and safer alternatives, in this comprehensive guide. At the heart of its error-handling mechanism lie the Option and Result types, which provide developers with tools to explicitly manage the presence or absence of values and handle potential errors in computations. However, there exists a method—unwrap—that offers a shortcut for extracting values from these types. While powerful, its misuse can lead to unexpected panics, making it a topic of both fascination and caution among Rustaceans.
Optimizing the Two Sum Problem: Techniques, Trade-offs, and Performance
The Problem Statement
One of the classic algorithm problems frequently encountered in interviews is the Two Sum problem. It challenges you to find two indices in an array such that the sum of the elements at these indices equals a given target. It seems simple, but the real depth lies in optimizing its solution.
There is this common programming question that goes something like this:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Chaos Engineering Practices: Building Resilient Systems Through Controlled Failure
In today’s complex distributed systems, failures are inevitable. Networks partition, services crash, dependencies slow down, and hardware fails. Traditional testing approaches often fall short in identifying how these systems behave under unexpected conditions. Chaos Engineering has emerged as a disciplined approach to identify weaknesses in distributed systems by deliberately injecting failures in a controlled manner.
This comprehensive guide explores chaos engineering principles, tools, implementation strategies, and real-world examples. Whether you’re just starting your reliability journey or looking to enhance your existing practices, these approaches will help you build more resilient systems that can withstand the turbulence of production environments.
Low-Code/No-Code Platforms: Democratizing Application Development
The demand for software applications continues to outpace the availability of professional developers, creating significant backlogs and slowing digital transformation initiatives. Low-code and no-code development platforms have emerged as powerful solutions to this challenge, enabling both professional developers and business users to build applications with minimal traditional coding. By abstracting away complex technical details through visual interfaces and pre-built components, these platforms democratize application development and accelerate delivery.
This comprehensive guide explores low-code and no-code platforms, covering their capabilities, use cases, implementation strategies, governance, and best practices. Whether you’re evaluating these platforms for your organization or looking to optimize your existing implementation, these insights will help you leverage low-code/no-code approaches to drive innovation while maintaining enterprise standards.
Kubernetes Fundamentals: Container Orchestration Basics
Learn the core concepts and practical skills needed to deploy, manage, and scale containerized applications using Kubernetes.
Introduction and Setup
Introduction to Kubernetes
Container orchestration sounds complicated, but the problem it solves is simple: how do you run dozens or hundreds of containers across multiple servers without losing your sanity? Docker works great for single containers, but when you need to manage entire applications with databases, web servers, and background workers, you quickly realize you need something more sophisticated.
Cloud Cost Optimization: Maximizing ROI
Master cloud cost optimization strategies.
Understanding Cloud Waste: The Hidden Cost of Convenience
Before diving into solutions, it’s important to understand the common sources of cloud waste:
1. Idle Resources
Resources that are provisioned but not actively used:
- Running instances with low CPU utilization
- Provisioned databases with minimal connections
- Load balancers routing traffic to a single instance
2. Overprovisioned Resources
Resources allocated beyond actual requirements:
- Instances with more CPU/memory than needed
- Databases with excessive provisioned IOPS
- Oversized storage volumes with low utilization
3. Orphaned Resources
Resources that are no longer needed but still incurring costs:
Cloud Performance Tuning: Optimization Strategies
Optimize cloud application performance with advanced tuning techniques.
Introduction to Cloud Performance Tuning
Working with hundreds of customer applications has taught me that performance problems follow predictable patterns. Whether it’s a startup scaling their first viral app or an enterprise migrating legacy systems, the same fundamental issues appear repeatedly: chatty applications making too many API calls, databases overwhelmed by inefficient queries, and auto-scaling policies that react too slowly to traffic spikes.
Observability Platforms Comparison: Choosing the Right Monitoring Solution
As systems grow more complex and distributed, traditional monitoring approaches fall short. Modern observability platforms have emerged to provide deeper insights into system behavior, performance, and health. However, choosing the right observability solution for your organization can be challenging given the wide range of options available, each with different strengths, architectures, and pricing models.
This comprehensive guide compares leading observability platforms including Prometheus, Grafana, Datadog, New Relic, Elastic Observability, and Dynatrace. We’ll examine their features, architectures, pricing models, and ideal use cases to help you make an informed decision for your specific needs.
Microservices vs Monoliths: Architecture Patterns
Understand the trade-offs between microservices and monolithic architectures.
Understanding the Architectural Patterns
Before diving into comparisons, let’s establish a clear understanding of each architectural pattern.
Monolithic Architecture
A monolithic architecture is a traditional unified model where all components of an application are interconnected and interdependent, functioning as a single unit.
Key Characteristics:
- Single Codebase: All functionality exists in a single codebase
- Shared Database: Components typically share a single database
- Unified Deployment: The entire application is deployed as a single unit
- Tightly Coupled: Components are interconnected and interdependent
- Vertical Scaling: Typically scaled by adding more resources to a single server
Example Structure of a Monolithic E-commerce Application:
How to Migrate Docker Repositories to a New DockerHub Username
If you’ve ever tried to rename your DockerHub username, you know there’s no direct way to do it. For many users, creating a new DockerHub account and transferring all their repositories is the best option. This guide walks you through automating the process of migrating all Docker images from an old username to a new one. We’ll share a complete shell script, so you don’t have to manually tag and push each image, saving you time and effort.
Python 3.13 No-GIL Mode: How to Unlock True Multi-Threading and Boost Performance
Python 3.13 has quietly introduced a game-changing experimental feature: no-GIL mode! For years, the Global Interpreter Lock (GIL) has been a barrier to true parallelism in Python, limiting Python threads to one at a time. But with Python 3.13, you can now compile Python to run without the GIL, allowing Python threads to fully utilize multiple cores. Let’s dive into why this matters, how to try it out, and what kinds of performance gains you might see.
API-First Development: Building Scalable Interfaces
Master API-first development methodologies.
API-First Fundamentals
Core Principles and Benefits
Understanding the foundational concepts:
API-First Definition:
- Designing APIs before implementing applications
- Treating APIs as first-class products
- Focusing on consumer needs and use cases
- Establishing clear contracts between systems
- Enabling parallel development workflows
- Creating consistent, reusable interfaces
Traditional vs. API-First Approach:
Traditional Development:
Requirements → Application Development → API Creation → Integration → Deployment
API-First Development:
Requirements → API Design → API Contract → Parallel Development → Integration → Deployment
├─ Frontend Development
├─ Backend Implementation
└─ Consumer Integration
Key Benefits:
Kubernetes vs Serverless: Architecture Decision Guide
Compare Kubernetes and serverless architectures.
Understanding the Core Concepts
Before diving into comparisons, let’s establish a clear understanding of each approach.
Kubernetes: Container Orchestration at Scale
Kubernetes is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications.
Key Components:
- Nodes: Physical or virtual machines that form the Kubernetes cluster
- Pods: The smallest deployable units, containing one or more containers
- Deployments: Controllers that manage pod replication and updates
- Services: Abstractions that define how to access pods
- ConfigMaps and Secrets: Resources for configuration and sensitive data
- Namespaces: Virtual clusters for resource isolation
- Ingress: Rules for external access to services
Core Capabilities:
Benefits of Cloud-Native Applications: Building for the Modern Infrastructure
The landscape of application development and deployment has undergone a profound transformation over the past decade. Traditional monolithic applications hosted on physical servers have given way to cloud-native applications designed specifically to leverage the capabilities of modern cloud infrastructure. This shift isn’t merely a change in hosting environment—it represents a fundamental reimagining of how applications are built, deployed, and operated.
Cloud-native applications are specifically designed to thrive in cloud environments, embracing principles like containerization, microservices architecture, declarative APIs, and immutable infrastructure. These applications are built to harness the full potential of cloud platforms, delivering unprecedented levels of scalability, resilience, and agility.
Event-Driven Architecture: Building Reactive Systems
Design and implement event-driven architectures using messaging patterns.
Understanding Event-Driven Architecture
Before diving into specific patterns, let’s establish a clear understanding of what constitutes an event-driven architecture.
What is an Event?
An event is a record of something that has happened—a fact. Events are immutable, meaning once an event has occurred, it cannot be changed or deleted. Events typically include:
- A unique identifier
- Event type or name
- Timestamp
- Payload (the data describing what happened)
- Metadata (additional contextual information)
Examples of events include:
Rust Performance Optimization: High-Performance Programming
Optimize Rust applications for maximum performance with profiling.
Performance Optimization Fundamentals
Before diving into specific techniques, let’s establish some fundamental principles:
The Optimization Process
1. Measure - Establish a baseline and identify bottlenecks
2. Analyze - Understand why the bottlenecks exist
3. Improve - Make targeted changes to address the bottlenecks
4. Verify - Measure again to confirm improvements
5. Repeat - Continue until performance goals are met
Premature Optimization
As Donald Knuth famously said, “Premature optimization is the root of all evil.” Focus on writing clear, correct code first, then optimize where necessary:
AI-Powered Distributed Systems: Architectures and Implementation Patterns
The integration of artificial intelligence (AI) with distributed systems represents one of the most significant technological advancements in recent years. As distributed systems grow in complexity, traditional management approaches struggle to keep pace. AI offers powerful capabilities to enhance these systems with self-healing, intelligent scaling, anomaly detection, and automated optimization. This convergence is creating a new generation of distributed systems that are more resilient, efficient, and adaptive than ever before.
API Security Guide: Protect Your Application from Cyber Threats
Welcome to our journey into the world of API Security, Definitions, and Meanings!
My name is Alex, and I’m a cybersecurity expert with a passion for helping individuals and organizations understand the importance of protecting their APIs. With over 10 years of experience in the field, I’ve seen firsthand how a single misconfigured API can lead to catastrophic consequences.
So, why am I so passionate about API security? Well, it all started when I was working on a project that involved developing a custom API for a client. As I delved deeper into the world of APIs, I realized just how vulnerable they were to attacks. A single malicious actor could exploit a weakness in our API and gain access to sensitive data or disrupt the entire system.
Rust Design Patterns: Idiomatic Programming
Master Rust design patterns.
Memory Management Patterns
Rust’s ownership system influences how we manage resources:
RAII (Resource Acquisition Is Initialization)
RAII is a fundamental pattern in Rust where resources are acquired during initialization and released when the object goes out of scope:
struct File {
handle: std::fs::File,
}
impl File {
fn new(path: &str) -> Result<Self, std::io::Error> {
let handle = std::fs::File::open(path)?;
Ok(File { handle })
}
fn read_to_string(&mut self) -> Result<String, std::io::Error> {
let mut content = String::new();
self.handle.read_to_string(&mut content)?;
Ok(content)
}
}
// The file is automatically closed when `file` goes out of scope
fn process_file(path: &str) -> Result<String, std::io::Error> {
let mut file = File::new(path)?;
file.read_to_string()
}
Drop Guard
A drop guard ensures that cleanup code runs even if a function returns early:
How to Create Your Own Programming Language
A programming language is a system of communication and computation used to control a computer. Languages allow us to write instructions in a format that computers can understand and execute.
While many popular languages like Python, Java, and JavaScript already exist, you may want to create your own for learning purposes or to solve a specific problem. Here is an overview of the key steps involved in designing a custom programming language.
Poetry vs Pip: Comparing Python Dependency Management and Packaging Tools
Poetry and Pip are two popular tools for managing Python dependencies and packaging Python projects. Both have their own sets of advantages and disadvantages. This guide will provide a technical comparison of the two tools and demonstrate why Poetry has more features and is generally preferable to Pip for most use cases.
Key Differences
Some of the key differences between Poetry and Pip include:
-
Dependency resolution: Poetry uses a resolver to find the best combination of package versions to meet your requirements. Pip does not do this, it just installs the latest version that matches each requirement.
Sustainable Cloud Computing for Distributed Systems
As distributed systems increasingly rely on cloud computing resources, their environmental impact has become a growing concern. The global IT industry accounts for approximately 2-3% of worldwide carbon emissions—comparable to the aviation industry—with data centers alone consuming about 1% of global electricity. With the exponential growth of distributed systems and cloud computing, implementing sustainable practices is not just an environmental imperative but also a business necessity.
This article explores practical strategies and technologies for implementing sustainable cloud computing in distributed systems, helping organizations reduce their environmental impact while maintaining performance, reliability, and cost-effectiveness.
API Design Principles: Building Interfaces That Last
Application Programming Interfaces (APIs) have become the foundation of modern software development, enabling seamless integration between systems, powering microservices architectures, and facilitating third-party ecosystems. However, designing APIs that are intuitive, efficient, secure, and able to evolve over time requires careful consideration of numerous principles and best practices.
This comprehensive guide explores API design principles that lead to robust, developer-friendly interfaces. We’ll cover RESTful design, GraphQL, versioning strategies, authentication methods, documentation approaches, and patterns for creating APIs that stand the test of time. Whether you’re building public APIs for third-party developers or internal interfaces for microservices, these principles will help you create APIs that are a joy to use and maintain.
A Complete DevOps Guide for Beginners
Are you looking to improve your software development workflow and increase efficiency? Look no further than DevOps! In this comprehensive guide, we’ll explore what DevOps means, its benefits, and how to get started with implementing it in your own organization.
Hello there! My name is Andrew, and I’m excited to share my expertise on DevOps Engineering with you. As someone who has spent years working in the field, I’ve seen firsthand how it can transform organizations and bring people together. In this guide, we’ll explore what DevOps means, its benefits, and how to get started with implementing it in your own life.
Creating a Docker Alternative in Python
Docker is a popular containerization platform that allows developers to easily package applications into lightweight containers that can run isolated on any system. Containers provide a convenient way to deploy and scale applications by bundling together all the dependencies and configurations needed to run the app.
In this guide, we will walk through how to create a simple docker alternative in Python. The goal is to build a basic container runtime that can build images, run containers, and manage containers lifecycles. While this will only cover a subset of Docker’s functionality, it will demonstrate the core concepts needed to build a container engine.
Why Different Programming Languages Need to Exist
Programming languages allow us to communicate with computers by writing code. There are hundreds of programming languages in use today, and new ones are constantly being created. But why do we need so many different languages? Here are some key reasons:
Different Levels of Abstraction
Programming languages operate at different levels of abstraction from the underlying machine code that computers understand. Lower level languages like C and Assembly provide direct access to computer hardware and memory. They require developers to manage many details but allow for precise control and high performance.
Database Scaling Strategies: From Gigabytes to Petabytes
As applications grow in popularity and data volumes expand, database performance often becomes a critical bottleneck. What worked perfectly during development or early production can quickly become inadequate as user numbers increase and data accumulates. Scaling database systems effectively requires a deep understanding of various strategies, their trade-offs, and implementation approaches.
This comprehensive guide explores database scaling strategies from vertical scaling to distributed systems, covering relational and NoSQL approaches, replication, sharding, and cloud-native solutions. Whether you’re experiencing growing pains with your current database or planning ahead for future scale, these strategies will help you build resilient, high-performance database systems that grow with your business.
Rust for Quantum Computing in 2024: Libraries, Tools, and Best Practices
Quantum computing represents one of the most exciting frontiers in computer science, promising computational capabilities that could revolutionize fields from cryptography to drug discovery. As quantum hardware continues to advance, there’s a growing need for robust software tools to bridge the gap between quantum algorithms and physical quantum processors. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for quantum computing development.
The Future of AI in Software Development [2025]: Tools, Trends & What's Next
As we stand on the cusp of a new era in technology, the integration of Artificial Intelligence (AI) into software development is poised to revolutionize the way we create, maintain, and evolve digital solutions. By 2025, the landscape of software engineering is expected to undergo a dramatic transformation, with AI playing a pivotal role in every aspect of the development lifecycle. From intelligent code generation to predictive maintenance and beyond, the fusion of AI and software development promises to enhance productivity, improve code quality, and accelerate innovation at an unprecedented scale.
Learn Concurrency in Go
Concurrency in Go is one of its most powerful features, designed to make it easy to write concurrent programs. Go’s concurrency model is based on goroutines and channels, which provide a simple and efficient way to manage multiple tasks running in parallel.
Goroutines
A goroutine is a lightweight thread managed by the Go runtime. You can start a new goroutine using the
gokeyword followed by a function call. Goroutines run concurrently with other goroutines.Learn Go as a DevOps Engineer
Go, also known as Golang, is an open-source programming language designed for simplicity, efficiency, and reliability. It has become increasingly popular in the DevOps community due to its powerful standard library, ease of use, and performance capabilities. This guide aims to provide DevOps engineers with a comprehensive understanding of Go, from basic syntax to advanced topics, complete with practical examples and code snippets.
1. Introduction to Go
What is Go?
Go is a statically typed, compiled programming language designed by Google. It emphasizes simplicity and efficiency, making it ideal for scalable system programming and cloud-native development.
Rust CLI Applications: Command-Line Tool Development
Build robust.
Getting Started: A Simple CLI Application
Let’s start with a basic command-line application that accepts arguments and prints output:
use std::env; fn main() { // Collect command-line arguments let args: Vec<String> = env::args().collect(); // The first argument is the program name println!("Program name: {}", args[0]); // Print the remaining arguments if args.len() > 1 { println!("Arguments:"); for (i, arg) in args.iter().enumerate().skip(1) { println!(" {}: {}", i, arg); } } else { println!("No arguments provided"); } }This simple example demonstrates how to access command-line arguments using the standard library. However, for more complex applications, we’ll want to use dedicated argument parsing libraries.
How to Run Technical Discovery Sessions: A Comprehensive Guide
Technical discovery sessions are the foundation of successful software projects. These structured conversations between technical teams, stakeholders, and subject matter experts uncover requirements, constraints, and context that shape the entire project lifecycle. When done well, discovery sessions align expectations, identify risks early, and create a shared understanding that guides implementation. When done poorly, they lead to misaligned expectations, missed requirements, and ultimately, project failure.
This comprehensive guide explores how to plan and facilitate effective technical discovery sessions. Whether you’re a solution architect, technical lead, or project manager, this guide provides actionable strategies for preparation, facilitation, documentation, and follow-up to ensure your discovery sessions deliver maximum value.
Secrets Management in Cloud Environments: Best Practices and Tools
In today’s cloud-native world, applications require access to numerous secrets—API keys, database credentials, encryption keys, and other sensitive information. Managing these secrets securely is one of the most critical aspects of cloud security. Poor secrets management can lead to data breaches, unauthorized access, and compliance violations that can severely impact your organization.
This comprehensive guide explores best practices, tools, and implementation strategies for effective secrets management across AWS, Azure, and Google Cloud Platform (GCP), helping you build a robust security posture for your cloud environments.
Rust Module System: Code Organization
Master Rust’s module system.
Understanding the Basics of Rust’s Module System
At its core, Rust’s module system is about organizing code and controlling visibility. Let’s start with the fundamental concepts:
Modules: Organizing Code into Logical Units
A module is a container for items such as functions, structs, traits, impl blocks, and even other modules:
// Define a module named 'geometry" mod geometry { // Constants within the module const PI: f64 = 3.14159; // Functions within the module pub fn area_of_circle(radius: f64) -> f64 { PI * radius * radius } // Nested module pub mod shapes { pub struct Rectangle { pub width: f64, pub height: f64, } impl Rectangle { pub fn new(width: f64, height: f64) -> Rectangle { Rectangle { width, height } } pub fn area(&self) -> f64 { self.width * self.height } } } } fn main() { // Using items from the module let area = geometry::area_of_circle(5.0); println!("Area of circle: {}", area); let rect = geometry::shapes::Rectangle::new(10.0, 5.0); println!("Area of rectangle: {}", rect.area()); }Visibility and the pub Keyword
By default, everything in Rust is private. The
pubkeyword makes items accessible outside their defining module:Developing a Custom Kubernetes Controller in Go
A custom Kubernetes controller manages custom resources within a Kubernetes cluster, allowing for extended functionalities and custom automation.
Step-by-Step Guide
Define Custom Resource:
Define a custom resource definition (CRD) in a YAML file.
apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: myresources.mydomain.com spec: group: mydomain.com versions: - name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: spec: type: object properties: size: type: integer scope: Namespaced names: plural: myresources singular: myresource kind: MyResource shortNames: - mrGenerate Clientset:
Use kubebuilder to generate clientset, informers, and listers for your CRD.
Rust for IoT Development in 2024: Frameworks, Tools, and Best Practices
The Internet of Things (IoT) continues to transform our world, connecting billions of devices that collect, process, and exchange data. As IoT deployments grow in scale and complexity, the need for reliable, secure, and efficient software becomes increasingly critical. Rust, with its unique combination of memory safety without garbage collection, predictable performance, and modern language features, has emerged as an excellent choice for IoT development.
In this comprehensive guide, we’ll explore Rust’s ecosystem for IoT development as it stands in mid-2024. We’ll examine the frameworks, libraries, and tools that have matured over the years, providing developers with robust building blocks for creating secure and efficient IoT applications. Whether you’re building smart home devices, industrial sensors, wearables, or large-scale IoT platforms, this guide will help you navigate the rich landscape of Rust’s IoT development ecosystem.
Creating a Monitoring Agent in Go
Building a monitoring agent involves collecting metrics from a system and sending them to a monitoring server or displaying them on a dashboard.
Step-by-Step Guide
Define Metrics Structure:
Create a structure to store metrics.
type Metric struct { Name string Value float64 }Collect Metrics:
Implement functions to collect various system metrics (CPU usage, memory usage, etc.).
import ( "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/mem" ) func collectCPUMetrics() Metric { usage, _ := cpu.Percent(0, false) return Metric{Name: "cpu_usage", Value: usage[0]} } func collectMemoryMetrics() Metric { v, _ := mem.VirtualMemory() return Metric{Name: "memory_usage", Value: v.UsedPercent} }Send Metrics:
Implement a function to send metrics to a monitoring server (e.g., Prometheus, InfluxDB).
Building a CI/CD Pipeline Tool in Go
Developing a custom CI/CD pipeline tool in Go can help automate the processes of building, testing, and deploying applications. This project involves setting up pipelines, triggering builds, running tests, and deploying applications.
Step-by-Step Guide
Define the Pipeline Structure:
Create a structure to define pipeline stages, jobs, and steps.
type Step struct { Name string Command string } type Job struct { Name string Steps []Step } type Pipeline struct { Name string Jobs []Job }Parse Configuration:
Write a function to parse a pipeline configuration file (e.g., YAML or JSON).
Cloud Networking Best Practices: Designing Secure and Scalable Architectures
Networking is the foundation of cloud infrastructure, connecting your applications, services, and data across regions and to the internet. As organizations migrate more workloads to the cloud, designing secure, scalable, and high-performance network architectures becomes increasingly critical. Poor network design can lead to security vulnerabilities, performance bottlenecks, and operational challenges that impact your entire cloud environment.
This comprehensive guide explores cloud networking best practices across major cloud providers, covering VPC design, security controls, connectivity options, performance optimization, and monitoring strategies. Whether you’re building a new cloud environment or optimizing an existing one, these practices will help you create a robust networking foundation for your cloud infrastructure.
Rust Error Handling: Robust Program Design
Master Rust’s error handling with Result types.
Beyond the Basics: Result and Option
Let’s start with a quick refresher on Rust’s basic error handling types:
Result and Option Recap
// Result: for operations that can fail fn divide(a: i32, b: i32) -> Result<i32, &'static str> { if b == 0 { Err("Division by zero") } else { Ok(a / b) } } // Option: for values that might be absent fn find_user(id: u64) -> Option<User> { if id == 0 { None } else { Some(User { id, name: "User".to_string() }) } } // Using Result and Option together fn get_user_name(id: u64) -> Result<String, &'static str> { find_user(id).map(|user| user.name).ok_or("User not found") }The ? Operator
fn process_data() -> Result<String, &'static str> { let data = read_file("data.txt")?; // Returns early if Err let processed = process_string(&data)?; // Returns early if Err Ok(processed) } // Works with Option too fn first_even_number(numbers: &[i32]) -> Option<i32> { let first = numbers.first()?; // Returns None if empty if first % 2 == 0 { Some(*first) } else { None } }Combining Result and Option
fn process_optional_data(data: Option<&str>) -> Result<String, &'static str> { // Convert Option to Result let data = data.ok_or("No data provided")?; // Process the data if data.is_empty() { return Err("Data is empty"); } Ok(data.to_uppercase()) } // Using map and map_err for transformations fn transform_data(input: Option<&str>) -> Result<i32, String> { input .ok_or("No input provided".to_string()) .map(|s| s.parse::<i32>()) .map_err(|e| format!("Invalid input: {}", e))? .map_err(|e| format!("Parse error: {}", e)) }
Custom Error Types
For real-world applications, custom error types provide better organization and flexibility:
Everything you need to know to Master API Creation
Introduction to APIs
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. APIs can be categorized into various types, including REST, SOAP, GraphQL, and RPC. Among these, REST (Representational State Transfer) is the most widely used due to its simplicity and scalability.
This guide focuses primarily on RESTful APIs, which adhere to a set of constraints that make them efficient and easy to use. We’ll also touch on advanced topics like authentication, error handling, and rate limiting.
Progressive Web Apps: Modern Web Development
Build progressive web applications with service workers.
Understanding Progressive Web Apps
Core Concepts and Principles
Fundamental elements that define Progressive Web Apps:
Progressive Enhancement:
- Works for all users regardless of browser choice
- Core functionality available to everyone
- Enhanced experience for modern browsers
- Feature detection over browser detection
- Graceful degradation for older browsers
Responsive Design:
- Adapts to different screen sizes and orientations
- Fluid layouts and flexible images
- Mobile-first approach
- Touch-friendly interfaces
- Consistent experience across devices
App-like Experience:
Zero Trust Architecture: Security Framework Implementation
Design and implement zero trust security architectures with identity-based access control.
Understanding Zero Trust Security
Zero Trust is a security framework that requires all users and services, whether inside or outside the organization’s network, to be authenticated, authorized, and continuously validated before being granted access to applications and data.
Core Principles of Zero Trust
- Verify explicitly: Always authenticate and authorize based on all available data points
- Use least privilege access: Limit user access with Just-In-Time and Just-Enough-Access
- Assume breach: Minimize blast radius and segment access, verify end-to-end encryption, and use analytics to improve security posture
Traditional vs. Zero Trust Security
Traditional security models operate on the concept of “trust but verify,” where entities inside the network perimeter are inherently trusted. Zero Trust, by contrast, operates on “never trust, always verify,” treating every request as if it originates from an untrusted network.
WebAssembly in the Enterprise: Beyond the Browser
WebAssembly (Wasm) has evolved far beyond its origins as a browser technology. Initially designed to enable high-performance code execution in web browsers, Wasm has expanded into server-side applications, edge computing, containerization alternatives, and more. Its unique combination of near-native performance, sandboxed security, language-agnostic design, and compact binary format makes it increasingly attractive for enterprise applications seeking portability, security, and efficiency.
This comprehensive guide explores WebAssembly’s role in enterprise applications, covering server-side Wasm, edge computing use cases, containerization alternatives, multi-language development, and security considerations. Whether you’re evaluating Wasm for your organization or looking to expand your existing implementation, these insights will help you leverage WebAssembly’s capabilities to build portable, secure, and high-performance applications across diverse computing environments.
Building CI/CD Pipelines with GitHub Actions: A Comprehensive Guide
Continuous Integration and Continuous Deployment (CI/CD) have revolutionized how software teams deliver value. By automating the build, test, and deployment processes, CI/CD enables faster, more reliable software delivery with fewer manual interventions. Among the various CI/CD tools available today, GitHub Actions has emerged as a powerful and flexible solution, particularly for teams already using GitHub for source control.
This comprehensive guide will walk you through building effective CI/CD pipelines with GitHub Actions, from basic concepts to advanced implementation strategies, helping you accelerate your software delivery while maintaining quality and security.
How to AWS Assume Role and then revert to the previous role after
If you need to assume a role in AWS and then revert back to the previous role once complete, you can use the following snippet of code:
# Save original environment variables ORIGINAL_AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" ORIGINAL_AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" ORIGINAL_AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" # Assume the role and store the output in a variable assume_role_output=$(aws sts assume-role --role-arn arn:aws:iam::12345678912:role/YourCrossAccountAccessRole --role-session-name "AssumeRoleSession") # Extract temporary credentials from the assume role output using jq (JSON processor) export AWS_ACCESS_KEY_ID=$(echo "$assume_role_output" | jq -r '.Credentials.AccessKeyId') export AWS_SECRET_ACCESS_KEY=$(echo "$assume_role_output" | jq -r '.Credentials.SecretAccessKey') export AWS_SESSION_TOKEN=$(echo "$assume_role_output" | jq -r '.Credentials.SessionToken') # Later, if you want to revert back to the original environment variables # Restore the original environment variables export AWS_ACCESS_KEY_ID="$ORIGINAL_AWS_ACCESS_KEY_ID" export AWS_SECRET_ACCESS_KEY="$ORIGINAL_AWS_SECRET_ACCESS_KEY" export AWS_SESSION_TOKEN="$ORIGINAL_AWS_SESSION_TOKEN"Understanding the Process
Assuming a role in AWS allows you to temporarily access AWS resources that you wouldn’t have permission to access with your current credentials. After completing your tasks, it’s essential to revert back to your original role for security and access control reasons. This snippet demonstrates how to accomplish that using Bash scripting and the AWS CLI.
Zero Trust in the Cloud: Implementation Guide
Implement zero trust security models in cloud environments with identity management.
Understanding Zero Trust: Core Principles
Before diving into implementation details, let’s establish a clear understanding of Zero Trust principles and how they apply to cloud environments.
What is Zero Trust?
Zero Trust is a security model that assumes no user or system should be inherently trusted, whether inside or outside the traditional network perimeter. Instead, verification is required from everyone trying to access resources in the network.
Infrastructure as Code with Terraform: From Basics to Best Practices
In today’s cloud-centric world, managing infrastructure manually is no longer feasible. As organizations scale their cloud presence, the complexity of managing resources across multiple providers and environments becomes overwhelming. Infrastructure as Code (IaC) has emerged as the solution to this challenge, with Terraform standing out as one of the most powerful and flexible IaC tools available.
This comprehensive guide will take you through the journey of mastering Terraform—from understanding core concepts to implementing advanced techniques and best practices that enable you to manage infrastructure at scale with confidence and efficiency.
Cloud-Native Security: Modern Protection Strategies
Implement comprehensive security for cloud-native applications including container security.
Cloud-Native Security Fundamentals
The Cloud-Native Security Landscape
Understanding the unique security challenges:
Cloud-Native Architecture Characteristics:
- Distributed and decentralized
- Ephemeral and immutable
- API-driven and programmable
- Highly automated
- Dynamically orchestrated
- Microservices-based
- Infrastructure as code
Security Implications:
- Expanded attack surface
- Dynamic trust boundaries
- Short-lived resources
- Increased complexity
- Shared responsibility model
- Infrastructure as code vulnerabilities
- Supply chain risks
The 4C’s of Cloud-Native Security:
┌───────────────────────────────────────────────────────────┐ │ │ │ Cloud │ │ │ │ ┌───────────────────────────────────────────────────┐ │ │ │ │ │ │ │ Cluster │ │ │ │ │ │ │ │ ┌───────────────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ Container │ │ │ │ │ │ │ │ │ │ │ │ ┌───────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ Code │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └───────────────────────────────────┘ │ │ │ │ │ │ │ │ │ │ │ └───────────────────────────────────────────┘ │ │ │ │ │ │ │ └───────────────────────────────────────────────────┘ │ │ │ └───────────────────────────────────────────────────────────┘Cloud-Native Security Principles:
Python Web Development: Building Modern Applications
Build modern web applications using Python frameworks like Flask and Django with database integration.
Setting Up Your Python Web Development Environment
When I first started building web applications with Python, I made the classic mistake of jumping straight into Django without understanding the fundamentals. Three weeks later, I was drowning in middleware, models, and migrations without grasping why any of it mattered. That’s why we’re starting this guide with the foundation—understanding what Python web development actually means and setting up an environment that’ll serve you well throughout your journey.
Essential Policies for Administering an AWS EKS Cluster
So, what policies does my role need to create an AWS EKS cluster and be the admin?
-
AmazonEKSClusterPolicy: This policy grants permissions to create and manage EKS clusters. It includes actions like
eks:CreateCluster,eks:DescribeCluster,eks:UpdateClusterConfig,eks:DeleteCluster, etc. -
AmazonEKSServicePolicy: This policy allows the necessary permissions for the EKS service to manage resources on your behalf. It includes actions like
eks:DescribeUpdates,eks:ListClusters,eks:ListUpdates, etc. -
AmazonEKSServiceRolePolicy: This policy is attached to the IAM role assumed by the EKS service. It allows the service to perform necessary operations within your AWS account. This policy is typically managed by AWS and attached to the service role.
Show the Top 10 Largest Directories on Linux
If you need to see the top 10 largest directories on your Linux system, you can use the following command:
du -h --max-depth=1 / | sort -rh | head -n 11Alternative
If you are okay to install additional software, then you can use a tool like
ncduto do the same, but with a lot more options and more features.Installing
ncduncduis a software package that standards for “NCurses Disk Usage” and is a disk utility tool for Unix based systems.Cloud Cost Optimization Strategies: Maximizing ROI in the Cloud
As organizations continue to migrate workloads to the cloud, many are experiencing the phenomenon known as “cloud shock”—the realization that cloud costs are significantly higher than anticipated. While the cloud offers tremendous benefits in terms of agility, scalability, and innovation, these advantages can come at a substantial cost if not managed properly. According to Gartner, through 2024, nearly 60% of organizations will encounter public cloud cost overruns that negatively impact their budgets.
Retrieve the Latest Versioned Tag from AWS ECR in Bash
Managing Docker images in Amazon Elastic Container Registry (ECR) is a common task for many developers and DevOps practitioners. Often, you need to retrieve the latest versioned tag from a repository to streamline deployment processes or ensure compatibility with the most recent features or fixes.
In this post, we’ll explore a simple Bash command using the AWS CLI and
jqto fetch the latest versioned tag from an ECR repository.Designing Scalable Systems in AWS: Architecture Patterns for Growth
In today’s digital landscape, building systems that can scale effectively is no longer a luxury—it’s a necessity. Whether you’re launching a startup that might experience overnight success or managing enterprise applications with predictable but substantial growth, your architecture must be designed to scale seamlessly. Amazon Web Services (AWS) provides a rich ecosystem of services and tools to build highly scalable systems, but knowing how to leverage these resources effectively requires understanding key architectural patterns and best practices.
How to install MySQL on AmazonLinux2023
If you are using Amazon Linux 2023 base-image, and you have tried to run
yum install -y mysql, you will soon realize that it doesn’t work.Instead install MySQL on Amazon Linux 2023 like this:
sudo dnf update -y sudo dnf install mariadb105-serverFor advanced use-cases where you are installing this in a Docker-in-Docker environment, do it without the
sudo, as follows:dnf update -y dnf install mariadb105-serverNow if you run
mysql, you will no longer get themysql: command not foundmessage.Object-Oriented Programming in Python
Master OOP concepts in Python including classes.
Introduction and Setup
When I first started programming in Python, I thought object-oriented programming was just a fancy way to organize code. I couldn’t have been more wrong. After years of building everything from web applications to data processing pipelines, I’ve learned that OOP isn’t just about organization—it’s about modeling real-world problems in ways that make your code more maintainable, reusable, and intuitive.
Python Testing and Debugging: Quality Assurance
Master testing frameworks.
Understanding the Testing Mindset and Environment Setup
I’ve seen countless developers jump straight into writing tests without understanding why they’re doing it. They treat testing like a checkbox exercise—something to appease their team lead or satisfy code coverage metrics. But here’s what I’ve learned after years of debugging production failures at 3 AM: testing isn’t about proving your code works; it’s about discovering how it fails.
The mindset shift from “my code is perfect” to “my code will break in ways I haven’t imagined” is fundamental. When you write tests, you’re not just verifying functionality—you’re documenting your assumptions, creating safety nets for future changes, and building confidence in your system’s behavior under stress.
Choosing the Right Cloud Architecture: A Decision Framework for Modern Applications
In today’s rapidly evolving technology landscape, selecting the right cloud architecture is one of the most consequential decisions that organizations face. The architecture you choose not only impacts your application’s performance, scalability, and reliability but also significantly affects your development velocity, operational overhead, and total cost of ownership. With multiple architectural patterns available—from traditional monoliths to microservices, serverless, and various hybrid approaches—making an informed decision requires a structured approach that considers your specific business context, technical requirements, and organizational constraints.
Python Data Science: Analytics and Machine Learning
Master Python for data science with NumPy.
Setting Up Your Data Science Environment and Understanding the Ecosystem
Environment setup might seem boring, but I’ve learned it’s where most data science projects succeed or fail. You can have the best analysis in the world, but if your colleagues can’t reproduce it because of dependency conflicts, your work becomes worthless. Getting this foundation right from the start saves enormous headaches later.
The Python data science ecosystem has evolved dramatically over the past decade. What started as a collection of separate tools has become an integrated platform that rivals specialized statistical software. Understanding how these pieces fit together will make you more effective at solving real problems.
Python Data Structures: Algorithms and Implementation
Master Python’s built-in data structures and implement custom algorithms for efficient data manipulation and problem-solving.
Introduction and Fundamentals
Last month, I watched a developer spend three hours debugging why their web application was timing out. The culprit wasn’t a complex algorithm or a database issue - it was using a list to check if user IDs were valid. With 50,000 users, each login attempt was checking potentially all 50,000 entries. A simple change to a set reduced login time from 2 seconds to 2 milliseconds.
Asynchronous Programming in Python: Building High-Performance Applications
Master Python’s asynchronous programming capabilities to build fast, scalable applications that handle thousands of concurrent operations efficiently.
Why Async Programming Matters
Asynchronous programming can seem like magic when you see a single Python process handle 10,000 concurrent connections. How can one thread outperform traditional multi-threaded servers? The answer lies in efficiency and smart resource management.
Think of a restaurant where waiters take one order, go to the kitchen, wait for the food to cook, bring it back, then serve the next customer. If your meal takes 20 minutes, other customers wait 20 minutes just to place their order.
Python Fundamentals: Complete Programming Foundation
Build a solid foundation in Python programming with comprehensive coverage of syntax.
Introduction and Setup
Python has earned its reputation as one of the most approachable programming languages. What takes 20 lines of code in other languages often requires just 3 lines in Python. This simplicity isn’t accidental—it’s the result of deliberate design choices that prioritize readability and developer productivity.
When Guido van Rossum created Python, he built it around a philosophy of clean, readable code. The result is a language that reads almost like English, making it perfect for beginners while remaining powerful enough for complex applications. This guide will take you from Python basics to building real-world applications.
Run any version of Terrform using Docker
So our friend Docker comes around for another usecase.
Run Terraform (any version) from Docker
In this example, we will try and configure Terraform 1.4.0 through Docker, so that we don’t need to install it on our host system.
alias terraform14='docker run --rm -it -w $PWD:$PWD -v $PWD:$PWD hashicorp/terraform:1.4.0'To use it, we simply run a Terraform command:
terraform14 -versionNext let’s try another Terraform version as well
alias terraform15='docker run --rm -it -w $PWD:$PWD -v $PWD:$PWD hashicorp/terraform:1.5.0'To use it, like before:
Select * to Show Database Table Sizes MariaDB
In database management, understanding the size of your tables is crucial for optimizing performance and ensuring efficient resource utilization. If you’re a technical enthusiast or a seasoned database administrator working with MariaDB, this blog post is tailored just for you. Today, we’ll unravel the mystery behind MariaDB database table sizes using a powerful SQL query.
SELECT table_schema AS DB_NAME, TABLE_NAME, (DATA_LENGTH+INDEX_LENGTH)/1024/1024/1024 AS TABLE_SIZE_in_MB FROM information_schema.TABLES ORDER BY TABLE_SIZE_in_MB DESCExploring MariaDB Table Sizes
MariaDB stands out as a robust and reliable option. To gain insights into your database’s table sizes, we’re going to wield the mighty SQL language. Our tool of choice is a concise yet potent query that taps into the depths of MariaDB’s information schema.
Graceful Shutdown Patterns in Go
Implement proper shutdown procedures for Go applications.
Signal Handling Fundamentals
At the core of graceful shutdown is the ability to detect and respond to termination signals. Before diving into complex implementations, let’s establish a solid understanding of signal handling in Go.
Understanding OS Signals
Operating systems communicate with processes through signals. The most common signals relevant to application lifecycle management include:
- SIGINT (Ctrl+C): Interrupt signal, typically sent when a user presses Ctrl+C
- SIGTERM: Termination signal, the standard way to request graceful termination
- SIGKILL: Kill signal, forces immediate termination (cannot be caught or ignored)
- SIGHUP: Hangup signal, traditionally used to indicate a controlling terminal has closed
In Go, we can capture and handle these signals using the
os/signalpackage and channels:Rate Limiting Strategies in Go
Implement sophisticated rate limiting algorithms and patterns in Go for API protection.
Rate Limiting Fundamentals
Rate limiting is a strategy to control the rate at which a user, service, or system can access a resource or perform operations. Before diving into complex implementations, let’s establish a solid understanding of the core concepts and basic approaches.
Core Concepts and Terminology
Rate limiting involves several key concepts:
- Request Rate: The number of requests per unit time (e.g., 100 requests per second)
- Burst: A temporary spike in request rate
- Quota: The maximum number of requests allowed in a given time window
- Throttling: The act of delaying or rejecting requests that exceed defined limits
- Rate Limiter: The component that enforces rate limits
Simple Counter-Based Rate Limiter
Let’s start with a basic implementation—a fixed window counter rate limiter:
Advanced Go Reflection and Code Generation
Master Go’s reflection capabilities and code generation techniques for building flexible.
#Go is known for simplicity, but sometimes you need more flexibility. Reflection lets you inspect types and values at runtime, while code generation creates Go code automatically. Both techniques help eliminate repetitive code and build more flexible systems.
When You Need These Techniques
Most Go code doesn’t need reflection or code generation. But they’re valuable when:
- Building frameworks: ORMs, web frameworks, and serialization libraries
- Eliminating boilerplate: Generating repetitive struct methods
- Dynamic behavior: Handling unknown types at runtime
- API tooling: Generating client libraries from definitions
- Testing utilities: Creating mocks and test helpers
Reflection vs Code Generation
Reflection happens at runtime:
The Future Prospects of DevOps in an AI World
Abstract
DevOps has become an integral part of modern software development, emphasizing communication and collaboration between software developers and IT operations professionals. However, with the rise of artificial intelligence (AI), the future role and necessity of devops has been brought into question. This paper explores the prospects for devops in an increasingly AI-driven world, including devops’ potential contributions to and collaboration with AI, as well as the possibility of eventual replacement by intelligent systems. Both theoretical analysis and real-world trajectory suggest devops retaining relevance, albeit with an evolving role and skillset demands.
Go Pipeline Patterns for Data Processing
Build efficient data processing pipelines in Go using channel patterns.
#Processing large amounts of data efficiently is a common challenge. Pipeline patterns break complex processing into stages, where each stage does one thing well and passes results to the next stage.
What Are Pipeline Patterns?
Think of an assembly line: each worker performs a specific task and passes the work to the next person. Pipeline patterns work similarly:
- Input Stage: Receives raw data
- Processing Stages: Transform, filter, or enrich data
- Output Stage: Sends results somewhere useful
Each stage runs concurrently, so while stage 1 processes item N, stage 2 can process item N-1, and stage 3 can process item N-2.
Event Sourcing Implementation in Go
Build event-sourced systems in Go with CQRS patterns.
#Most applications store only current state - when something changes, the old data is lost. Event sourcing takes a different approach: store every change as an immutable event, preserving the complete history.
The Problem with State-Based Storage
Traditional applications work like this:
// Traditional approach - only current state type Account struct { ID string Balance int Status string } // When balance changes, old value is lost func (a *Account) Withdraw(amount int) { a.Balance -= amount // History is gone }Problems with this approach:
Supercharge Your Code with Amazon CodeWhisperer
Amazon CodeWhisperer is a cutting-edge service that leverages advanced AI and machine learning to provide real-time code generation, recommendations, and security analysis. As a developer, CodeWhisperer can supercharge your productivity and code quality.
Key Capabilities
Neural Code Generation
CodeWhisperer utilizes powerful neural networks to generate code snippets and entire functions on demand. The advanced models are trained on millions of code samples and can produce idiomatic, human-readable code for a wide variety of programming languages.
A Deep Dive into Machine Learning Algorithms
Machine learning algorithms are the backbone of modern artificial intelligence. They enable computers to learn and make predictions or decisions without being explicitly programmed. In this comprehensive guide, we will delve into common machine learning algorithms, providing detailed explanations and code examples to help you understand their inner workings. Whether you’re a beginner or an experienced data scientist, this post will be a valuable resource to enhance your understanding of machine learning.
What is GitHub? A Comprehensive Guide from Basics to Advanced
GitHub is a platform that has revolutionized the world of software development, enabling individuals and teams to collaborate efficiently on projects of all sizes. In this comprehensive guide, we’ll explore GitHub from the very basics to the most advanced features. Whether you’re a novice or an experienced developer, you’ll find valuable insights and tips to enhance your understanding of GitHub.
Part 1: Git Basics
Before diving into GitHub, it’s essential to grasp the fundamental concepts of Git, the version control system that underlies GitHub.
Connect IPv4 and IPv6 Networks Seamlessly with Amazon VPC Lattice
As the internet continues to grow, the transition from IPv4 to IPv6 has become more critical. Organizations need to manage both IP stacks efficiently and ensure seamless connectivity. Amazon Web Services (AWS) offers a groundbreaking solution: Amazon VPC Lattice. In this advanced guide, we’ll delve deeper into Amazon VPC Lattice, its technical details, and provide code examples for advanced users.
A Lattice of Connectivity
Amazon VPC Lattice simplifies the coexistence of IPv4 and IPv6 stacks within your Virtual Private Cloud (VPC). The innovation lies in its ability to bridge the gap between these two IP versions without the need for Network Address Translation (NAT) devices. Let’s explore the capabilities of VPC Lattice and its significance in modern networking.
Building Event-Driven Architectures with Amazon EventBridge
In the realm of real-time data streaming applications, managing the routing and processing of events efficiently is a complex challenge. Amazon Web Services (AWS) has a powerful solution: Amazon EventBridge.
In the realm of real-time data streaming applications, managing the routing and processing of events efficiently is a complex challenge. Amazon Web Services (AWS) has a powerful solution: Amazon EventBridge. In this advanced guide, we’ll delve deeper into EventBridge, its key concepts, and provide code examples for advanced users.
Splitting Terraform Modules into Separate Git Repositories
In the world of Infrastructure as Code (IaC), Terraform has emerged as a powerful tool for managing infrastructure resources. As your Terraform codebase grows, managing monolithic code can become challenging. In this advanced-level blog post, we will explore the process of moving Terraform modules into separate Git repositories and referencing these modules across multiple repositories. This approach can help you achieve better code organization, reusability, and collaboration in your infrastructure provisioning projects.
Accelerating Machine Learning with SageMaker Jumpstart
Machine learning (ML) projects can be complex, time-consuming, and resource-intensive. Amazon SageMaker Jumpstart aims to change that by providing pre-built solutions, pre-trained models, and end-to-end ML capabilities. In this advanced guide, we’ll dive deep into SageMaker Jumpstart and provide code examples to illustrate its power.
Unleashing ML Potential
Amazon SageMaker Jumpstart is designed to accelerate your ML journey. It offers a wide range of pre-built solutions and pre-trained models for various ML use cases, including natural language processing, computer vision, and more. Let’s delve into the capabilities of SageMaker Jumpstart and how it can make your ML projects more efficient.
Understanding the AWS Well-Architected Framework
The AWS Well-Architected Framework is more than just a set of best practices; it’s a blueprint for success in the cloud. It offers a comprehensive guide to building high-quality, efficient, and cost-effective architectures on Amazon Web Services (AWS). In this blog post, we’ll delve into the key principles and pillars of the AWS Well-Architected Framework and explore how you can leverage it to ensure your cloud infrastructure is robust and resilient.
Mastering Advanced Networking in EKS and Kubernetes
Kubernetes has revolutionized container orchestration, and Amazon’s Elastic Kubernetes Service (EKS) is one of the most popular managed Kubernetes solutions available today. While getting started with EKS and Kubernetes is relatively straightforward, mastering advanced networking topics is essential for managing complex workloads and achieving optimal performance. In this comprehensive guide, we will explore advanced networking concepts in EKS and Kubernetes, accompanied by code examples and practical insights.
1. VPC Design and EKS Setup
When working with EKS, it’s crucial to have a well-architected VPC. This section will cover best practices for VPC design, creating EKS clusters, and securing them with security groups and Network ACLs. Let’s look at a snippet of Terraform code to create a VPC:
How to Ignore SSL Certificates Globally in Git
In the world of software development, Git is an indispensable tool for version control. However, when working with repositories that use SSL certificates, you might encounter situations where you need to ignore SSL certificate verification globally. Whether it’s for testing or debugging purposes, this guide will show you how to ignore SSL certificates globally in Git and even disable SSL certificate checks altogether. We’ll cover everything from the basics to advanced configurations to help you manage SSL certificates effectively in your Git workflow.
Semantic Versioning with npm
Semantic Versioning, often referred to as SemVer, is a crucial convention within the Node.js ecosystem. It provides a clear and structured way of versioning software, ensuring that developers can easily understand the impact of version changes. In this blog post, we’ll explore the principles of Semantic Versioning and how npm (Node Package Manager) leverages it to manage packages effectively.
Understanding Semantic Versioning
Semantic Versioning is based on a three-digit version number, often expressed as
x.y.z, where each digit has a specific meaning:Understanding Peer Dependencies in Node Modules
When working with Node.js and managing packages for your projects, you’re likely familiar with the
dependenciesanddevDependenciessections in apackage.jsonfile. These sections define the packages your project depends on for both production and development purposes. However, there’s another crucial field often overlooked but equally important:peerDependencies.In this blog post, we will delve into the concept of
peerDependenciesand how they differ from regular dependencies anddevDependencies.How to Programmatically get Amazon IP Ranges/CIDRs
Amazon Web Services (AWS) operates an extensive network infrastructure with a vast number of IP addresses and CIDR blocks. As a developer or network administrator, you may need to programmatically retrieve the IP ranges or CIDRs associated with AWS regions and services for various reasons, such as configuring firewall rules or network security groups. In this guide, we’ll show you how to accomplish this using Python.
Prerequisites
Before we dive into the code, make sure you have the following prerequisites in place:
The Ultimate Guide to Emacs: Mastering the Art of CLI Programming
In the realm of command-line interface (CLI) programming, Emacs stands as a legendary text editor, known for its immense power and unparalleled extensibility. For decades, Emacs has been the tool of choice for seasoned CLI programmers who demand efficiency and customization. In this ultimate guide, we will explore advanced and expert ways to harness the full potential of Emacs, helping you become an amazing CLI programmer.
Introduction to Emacs
What is Emacs?
Emacs is a highly extensible, open-source text editor with a rich history dating back to the 1970s. It’s renowned for its “everything is a buffer” philosophy, which means you can edit not only code but also emails, calendar events, and more from within Emacs.
The Ultimate Guide to VI: Mastering the Art of CLI Programming
In the world of command-line interface (CLI) programming, efficiency is paramount. And when it comes to text editing in the CLI, there’s no tool more legendary than VI. This powerful, yet enigmatic text editor has been the choice of seasoned CLI programmers for decades. In this ultimate guide, we will explore advanced and expert ways to harness the full potential of VI, helping you become an amazing CLI programmer.
Introduction to VI
What is VI?
VI, which stands for “Visual Editor,” is a highly efficient and lightweight text editor that comes pre-installed on most Unix-like systems. Its minimalist design and keyboard-centric interface make it a favorite among power users who spend a lot of time in the terminal.
AWS Assume to another role
OUT=$(aws sts assume-role --role-arn arn:aws:iam::0123456789:role/OrganizationAccountAccessRole --role-session-name test) export AWS_ACCESS_KEY_ID=$(echo $OUT | cut -d '"' -f 6 ) export AWS_SECRET_ACCESS_KEY=$(echo $OUT | cut -d '"' -f 10 ) export AWS_SESSION_TOKEN=$(echo $OUT | cut -d '"' -f 14 ) aws sts get-caller-identityService Discovery Patterns in Go
Implement service discovery mechanisms in Go microservices using various patterns and tools for dynamic service registration and lookup.
Service Discovery Fundamentals
Before diving into implementation details, let’s establish a solid understanding of service discovery concepts and their role in distributed systems.
The Service Discovery Problem
In a traditional monolithic application, components communicate through in-memory function calls or well-known local interfaces. In distributed systems, however, services run on different machines with their own network locations, creating several challenges:
Programming Languages Compared: Python, Rust, Go, Java & More (2023 Series)
1. Introduction
Welcome to our Programming Languages Series! In this series, we’ll explore various programming languages, understand their purposes, provide code examples, and discuss when to use each one. Let’s begin with an introduction to programming languages.
What Are Programming Languages?
Programming languages are a means of communication between humans and computers. They allow developers to instruct computers to perform specific tasks, ranging from simple calculations to complex data processing and application development.
Go Worker Pool Patterns: Scalable Concurrent Processing
Master worker pool patterns in Go for building scalable.
#Processing many tasks concurrently is a common need, but creating unlimited goroutines can overwhelm your system. Worker pools solve this by using a fixed number of workers to process tasks from a queue.
The Problem with Unlimited Goroutines
Consider processing 10,000 images:
// Don't do this - creates 10,000 goroutines for _, image := range images { go processImage(image) }This approach can:
- Exhaust memory with too many goroutines
- Overwhelm the CPU with context switching
- Crash your system under high load
- Make it hard to control resource usage
Worker Pool Solution
Instead, use a fixed number of workers:
Docker Deep Dive Series: From Install to Production (Complete Guide)
1. Getting Started
In this first part of the series, we will kick things off by getting Docker installed and running on your system. Docker makes it easy to package and distribute applications as containers, ensuring consistent environments across different stages of the development and deployment pipeline.
Let’s jump right in and get Docker up and running!
Prerequisites
Before we start, ensure that you have the following prerequisites installed on your system:
Go Atomic Operations: Lock-Free Programming
Master Go’s atomic operations for building high-performance.
Understanding Go’s Memory Model
Before diving into atomic operations, it’s essential to understand Go’s memory model, which defines the rules for how memory operations in one goroutine become visible to another. This understanding forms the foundation for correct concurrent programming in Go.
Memory Ordering and Visibility
Go’s memory model is based on the happens-before relationship, which determines when the effects of one goroutine’s memory operations become visible to another goroutine:
Machine Learning Mastery Series
Part 1. Introduction to Machine Learning
Welcome to the Machine Learning Mastery Series, a comprehensive journey into the exciting world of machine learning. In this first installment, we’ll lay the foundation by exploring the fundamentals of machine learning, its types, and the essential concepts that underpin this transformative field.
What is Machine Learning?
Machine learning is a subfield of artificial intelligence (AI) that focuses on developing algorithms and models that enable computers to learn from and make predictions or decisions based on data. Unlike traditional programming, where explicit instructions are provided to solve a specific task, machine learning systems learn patterns and relationships from data to make informed decisions.
Kubernetes Mastery
Part 1. Introduction
Welcome to the Kubernetes Mastery Series! In this first part, we’ll set up a Kubernetes cluster using KinD (Kubernetes in Docker). This series will build on concepts covered in our Ultimate Guide to Kubernetes Deployment Strategies and provide practical implementations of DevOps security best practices.
Prerequisites:
- Docker
- kubectl
- KinD
# Step 1: Install Docker # Step 2: Install kubectl # Step 3: Install KinD # Step 4: Create a KinD cluster kind create cluster --name my-cluster --config - <<EOF kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane - role: worker - role: worker EOF # Step 5: Set kubectl context kubectl cluster-info --context kind-my-cluster # Step 6: Verify cluster nodes kubectl get nodesPart 2. Deploying Your First App
In this second part, we’ll explore how to deploy your first application to the Kubernetes cluster you set up in Part 1.
Advanced Go Concurrency Patterns
Master sophisticated concurrency patterns in Go including worker pools.
#Go’s concurrency model is powerful, but building distributed systems requires more than basic goroutines and channels. You need patterns that handle coordination across services, manage failures gracefully, and scale under load.
Beyond Basic Concurrency
Most Go tutorials cover the basics: launching goroutines, sending values through channels, and using select statements. But real distributed systems face challenges like:
- Service coordination: Multiple services need to work together
- Failure handling: Networks partition, services crash, timeouts occur
- Load management: Systems must handle varying traffic patterns
- Resource coordination: Shared resources need careful management
Patterns You’ll Learn
This guide covers advanced concurrency patterns for distributed systems:
Managing Multiple Environments with Terraform Workspaces
Managing infrastructure across multiple environments such as development, staging, and production can be a daunting task. Terraform, a popular Infrastructure as Code (IaC) tool, offers a powerful feature known as workspaces that can help you efficiently manage and maintain separate environments within a single configuration. In this technical blog post, we’ll explore Terraform workspaces, how they work, and best practices for utilizing them effectively.
Understanding Terraform Workspaces
Terraform workspaces provide a way to manage distinct instances of the same infrastructure configuration. Each workspace maintains its state files and variables, allowing you to create isolated environments for different purposes. This isolation prevents potential conflicts and allows you to make changes to one environment without affecting others.
Controlling and Understanding Parallelism Impact on the DAG
When working with large-scale infrastructure deployments, managing the provisioning and orchestration of resources efficiently becomes crucial. Terraform, a widely-used Infrastructure as Code (IaC) tool, offers a feature known as parallelism to accelerate the deployment process. In this blog post, we’ll delve into parallelism in Terraform, how it affects the Directed Acyclic Graph (DAG), and how you can control and optimize its usage.
Understanding Parallelism and the DAG
Parallelism refers to the ability to execute multiple tasks simultaneously. In the context of Terraform, parallelism enables the provisioning of resources in parallel, speeding up the infrastructure deployment process. However, parallelism introduces complexities due to resource dependencies and potential conflicts.
How to add Payment Subscriptions with Stripe in Django
Integrating Stripe subscriptions into your Django site involves several steps. Here’s a high-level overview of the process. Please note that the exact implementation can vary based on your specific requirements.
Steps involved
Sign Up and Set Up Stripe Account
If you haven’t already, sign up for a Stripe account at https://stripe.com. Once you’ve signed up, you’ll need your API keys: a
Publishable Key(for the client-side) and aSecret Key(for server-side interactions).Private Application Load Balancer for EKS in Terraform
Amazon Web Services (AWS) provides a powerful combination of services for building, deploying, and managing applications. Amazon Elastic Kubernetes Service (EKS) is a managed Kubernetes service that simplifies the process of deploying, managing, and scaling containerized applications using Kubernetes. In certain scenarios, you might want to deploy a private Application Load Balancer (ALB) in front of your private EKS cluster to handle incoming traffic efficiently. In this guide, we’ll walk through the process of setting up a private ALB for your private EKS cluster using Terraform, along with best practices and intricate details.
Kubernetes vs Docker Swarm for Container Orchestration
Container orchestration has become a cornerstone of modern application deployment and management. Two prominent contenders in the realm of container orchestration are Kubernetes and Docker Swarm. Both offer powerful solutions for automating the deployment, scaling, and management of containerized applications. In this in-depth comparison, we’ll delve into the strengths, features, and nuances of Kubernetes and Docker Swarm to help you make an informed choice for your container orchestration needs.
Understanding Kubernetes
Kubernetes, often referred to as K8s, has emerged as a de facto standard for container orchestration. It provides an extensive set of features for managing containerized applications, ensuring high availability, scalability, and seamless deployments. Kubernetes excels in orchestrating complex microservices architectures and applications with intricate scaling requirements.
Setting Comprehensive CI/CD Pipeline with Jenkins and Docker
In today’s dynamic software landscape, the fusion of Continuous Integration and Continuous Deployment (CI/CD) pipelines with robust tools like Jenkins and Docker has emerged as a cornerstone of efficient and reliable application delivery. This detailed tutorial will provide you with an in-depth walkthrough, guiding you step by step through the intricate process of configuring a comprehensive CI/CD pipeline using Jenkins and Docker. By the end of this tutorial, you’ll be equipped to seamlessly incorporate DevOps practices, elevating your software delivery process to new heights.
Navigating Microsoft Azure for Seasoned AWS Experts
In the ever-evolving landscape of cloud computing, two mammoth players, Amazon Web Services (AWS) and Microsoft Azure, have emerged as titans, offering an extensive array of services that cater to a diverse spectrum of business needs. If you’ve already amassed a wealth of knowledge and experience in AWS and are now yearning to broaden your cloud horizons, this comprehensive guide is designed to be your compass. Together, we’ll embark on a journey to seamlessly transition your AWS proficiency into the realm of Microsoft Azure, unraveling parallels between their services and enriching your cloud expertise.
Advanced Go Memory Management
Master Go’s memory model.
Understanding Go’s Memory Model
Before diving into optimization techniques, it’s essential to understand how Go manages memory at a fundamental level. Go’s memory model defines not just how memory is allocated and freed, but also the guarantees around memory access in concurrent programs.
Stack vs. Heap Allocation
Go uses a hybrid approach to memory allocation, utilizing both stack and heap:
package main import ( "fmt" "runtime" ) func main() { // Stack allocation - x doesn't escape to the heap x := 42 // Heap allocation - y escapes to the heap y := &x // Force GC to demonstrate the concept runtime.GC() // Print memory statistics var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Printf("Stack variable: %d\n", x) fmt.Printf("Heap reference: %d\n", *y) fmt.Printf("Heap allocations: %d bytes\n", m.HeapAlloc) }The Go compiler uses escape analysis to determine whether a variable should be allocated on the stack or heap. Variables allocated on the stack are automatically freed when the function returns, while heap allocations are managed by the garbage collector.
Navigating Google Cloud Platform (GCP) for AWS Experts
In today’s rapidly evolving landscape of cloud computing, Amazon Web Services (AWS) and Google Cloud Platform (GCP) have emerged as prominent contenders, furnishing an extensive array of services tailored to cater to the dynamic requirements of modern businesses. If you’re already versed in the intricacies of AWS and are now seeking to broaden your cloud horizons, this comprehensive guide is poised to be your beacon. We’ll embark on a journey of bridging the gap between your existing AWS proficiency and your newfound GCP expertise, ensuring your transition is not just smooth, but also illuminating.
Create a slug from a name in MySQL/MariaDB
How to create a
slugfrom thenameof an item in MySQL/MariaDB.UPDATE my_table SET slug = LOWER(REGEXP_REPLACE(REPLACE(REPLACE(REPLACE(name, ' ', '-'), 'and', '-'), '[^a-zA-Z0-9-]', ''), '-+', '-'));Secure Efficient Server Management with AWS Systems Manager
In the ever-evolving landscape of cloud computing, AWS (Amazon Web Services) continually introduces innovative solutions to enhance operational efficiency, security, and ease of management. One such powerful tool is AWS Systems Manager (SSM), which empowers users to manage their server infrastructure without the need for SSH access and traditional EC2 key pairs. In this comprehensive guide, we’ll delve into setting up AWS SSM, exploring its advanced use cases, and demonstrating how it can transform your workflow.
How to Get a List of Available Regions from AWS CLI
AWS (Amazon Web Services) is a prominent cloud service provider that offers a wide range of services to businesses and individuals worldwide. One of the fundamental concepts in AWS is regions, which are distinct geographical locations hosting AWS infrastructure. Understanding regions is crucial for optimizing your cloud infrastructure’s performance, data residency, and compliance requirements. In this blog post, we’ll dive into the world of AWS regions, learn how to list available regions using the AWS CLI, and explore a handy command to fetch region details in a more reader-friendly format.
[Solved] A Number After a Double Reversal in Python
The problem
Reversing an integer means to reverse all its digits.
For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.
Example 1:
Input: num = 526 Output: true Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.Example 2:
Input: num = 1800 Output: false Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.Example 3:
Input: num = 0 Output: true Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.Constraints:
`0 <= num <= 106``
Common Issues and Mastering Effective Debugging Techniques
While Kubernetes offers a powerful platform for deploying containerized applications, managing complex clusters can sometimes lead to challenges and errors. In this comprehensive blog post, we will delve into common issues that arise in Kubernetes clusters and equip you with effective troubleshooting and debugging methodologies. By the end, you’ll be empowered to unravel the mysteries of Kubernetes troubleshooting and confidently resolve issues to ensure the seamless operation of your clusters.
K8s CI/CD: GitOps with Jenkins, GitLab, Argo CD
Continuous Integration and Continuous Deployment (CI/CD) pipelines are fundamental to the success of Kubernetes deployments, enabling fast and reliable application delivery. In this comprehensive blog post, we will explore CI/CD pipelines customized for Kubernetes, including the GitOps approach, and how to leverage popular tools like Jenkins, GitLab, and Argo CD. By the end, you’ll be equipped with actionable insights to build efficient CI/CD pipelines that seamlessly integrate with your Kubernetes ecosystem.
K8s Monitoring & Logging: Best Practices & Top Tools
Monitoring and logging are critical components of a successful Kubernetes deployment, providing insights into the health, performance, and behavior of your clusters and applications. In this comprehensive blog post, we will cover best practices for monitoring Kubernetes, including node and pod metrics, as well as exploring popular monitoring and logging tools such as Prometheus, Grafana, and Elasticsearch. By the end, you’ll be equipped with actionable knowledge to set up robust observability for your Kubernetes ecosystem, enabling you to detect issues proactively and ensure smooth operations.
K8s Upgrades & Rollbacks Guide to Compatibility & Strategies
Keeping your Kubernetes cluster up-to-date is crucial for security, performance, and accessing the latest features. However, orchestrating Kubernetes upgrades and rollbacks can be a challenging endeavor. In this all-encompassing blog post, we will dive into the complexities of Kubernetes upgrades, exploring version compatibility considerations, the power of rolling updates, and the importance of robust rollback strategies. By the end, you’ll be equipped with actionable insights to navigate Kubernetes upgrades and rollbacks with confidence, ensuring your cluster remains resilient and always up-to-date.
K8s Pod Scheduling: Node & Pod Affinity Demystified
Efficient pod scheduling is essential to achieving high performance and resource utilization in a Kubernetes cluster. Understanding the intricacies of pod scheduling, particularly node affinity, pod affinity, and anti-affinity rules, empowers you to distribute workloads effectively. In this comprehensive blog post, we will explore the art of pod scheduling in Kubernetes, shedding light on the power of node affinity, enhancing resource allocation with pod affinity, and ensuring fault tolerance through anti-affinity. By the end, you’ll be equipped to fine-tune pod placement and optimize the distribution of workloads within your Kubernetes ecosystem.
Securing Kubernetes: Guarding Against Container Threats
Kubernetes has become the de facto platform for deploying containerized applications, revolutionizing software development. However, with great power comes great responsibility, and security is paramount in a Kubernetes environment. In this comprehensive blog post, we will delve into the critical security concerns in Kubernetes, covering the protection of the API server, implementing Role-Based Access Control (RBAC), fortifying with Network Policies, and mitigating container vulnerabilities. By the end, you’ll have actionable tips to build a robust Kubernetes fortress, protecting your applications and data from potential security risks.
K8s Cluster Performance: Resource Optimization Guide
Efficiently managing resources in a Kubernetes cluster is crucial to achieving peak performance and cost-effectiveness. Resource allocation, utilization, and handling resource-intensive applications demand careful consideration. In this comprehensive blog post, we will delve into best practices for resource management, exploring resource allocation techniques, monitoring, and optimizing resource-hungry applications. By the end, you’ll be armed with the knowledge to optimize your Kubernetes cluster for maximum productivity and resource efficiency.
Understanding Resource Management in Kubernetes
Resource management involves allocating CPU, memory, and other resources to applications running in a Kubernetes cluster. Properly managing these resources ensures that applications receive the necessary compute power while avoiding resource contention that can lead to performance bottlenecks.
K8s Scaling Mastery: Manual, HPA & Metrics APIs
Kubernetes has revolutionized application deployment by providing a scalable and efficient container orchestration platform. However, as your applications grow, you’ll encounter the challenge of efficiently scaling them to meet varying demands. In this in-depth blog post, we will explore the intricacies of scaling applications in Kubernetes, discussing manual scaling, Horizontal Pod Autoscalers (HPA), and harnessing the power of Kubernetes Metrics APIs. By the end, you’ll be equipped with the knowledge to elegantly scale your applications, ensuring they thrive under any workload.
K8s Storage Demystified: Persistent Volumes & Classes
Kubernetes has become the go-to platform for deploying scalable, containerized applications. However, managing persistent data in a dynamic container environment presents unique challenges. In this comprehensive blog post, we’ll delve into the world of Kubernetes persistent storage, exploring the various approaches like Persistent Volumes (PVs) and Storage Classes (SCs). We’ll also shed light on common issues such as data loss and performance bottlenecks, equipping you with the knowledge to ensure data integrity and optimal storage performance within your Kubernetes clusters.
K8s Networking: Pod Communication and Ingress Demystified
Kubernetes has revolutionized the way we deploy and manage containerized applications. However, with the increasing complexity of distributed systems, networking and communication between pods within a Kubernetes cluster can become a daunting challenge. In this blog post, we will delve into the common networking issues that arise in Kubernetes and explore effective solutions using Service Discovery and Ingress controllers. By the end, you’ll have a clearer understanding of how to ensure seamless communication between your pods, enabling your applications to thrive in the Kubernetes ecosystem.
React State Balancing: A Guide to State Management
As React apps grow, managing shared and app-wide state can become challenging. Dedicated state management libraries help tackle these complexities.
Let’s compare popular options:
Redux
Redux uses a centralized store for state:
// Store with root reducer const store = createStore(rootReducer); // Dispatch actions store.dispatch(addTodo(text)); // Selectors const todos = useSelector(state => state.todos);Redux enforces unidirectional data flow inspired by functional programming.
MobX
MobX uses observable variables that update reactively:
// Observable store const store = observable({ todos: [] }); // Computed values derived from store const completedTodos = computed(() => { return store.todos.filter(todo => todo.complete); });MobX automatically tracks dependencies and re-renders on changes.
React + Node: Beginner's Guide to Full Stack Dev
React excels at building fast, dynamic frontends. Node.js shines for server-side APIs and microservices. Together, they make a powerful stack for full stack apps.
Let’s walk through integrating React with Node.js:
Serving React Builds
Use Node.js middleware like Express to serve the React app:
// server.js app.use(express.static(path.join(__dirname, 'client/build'))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html)); });This serves the React build from the
/buildfolder.Proxying API Requests
Proxy frontend requests to the backend API:
Optimal React Patterns: Beginner's Guide
As with any framework, React comes with its own set of best practices and optimal patterns. Let’s explore some tips for writing robust React code:
Modular Components
Break components into reusable, composable units:
// Bad function App() { return ( <header> <nav> <logo> <links> </nav> <h1>Welcome!</h1> <footer> <copyright> </footer> </header> ); } // Good function Nav() { return ( <nav> <Logo /> <Links /> </nav> ); } function Header() { return ( <header> <Nav /> <h1>Welcome!</h1> <Footer /> </header> ); }This encourages reusability.
Debugging React Apps: Beginner's Guide
Bugs are inevitable in complex React applications. Thankfully, React provides great tools to squash bugs quickly.
Let’s look at some key techniques for debugging React apps:
React Developer Tools
The React DevTools Chrome extension lets you inspect React component hierarchies, props, state and more in Chrome:
DevTools: <App> <Navbar /> <Profile name="Jane" imageUrl="https://..." /> </App>This provides invaluable visibility into React apps.
Error Boundaries
Error boundaries catch errors and display fallbacks:
Go WebAssembly: High-Performance Web Applications
Build high-performance web applications using Go and WebAssembly with advanced optimization techniques and JavaScript interoperability.
Understanding the Foundation
WebAssembly represents a fundamental shift in web development capabilities. For years, JavaScript was the only option for client-side computation, which worked fine for most applications but hit performance walls with computationally intensive tasks like data processing, image manipulation, or complex algorithms.
WebAssembly changes this by allowing languages like Go, Rust, and C++ to run in the browser at near-native speeds. This opens up possibilities that were previously impossible or impractical in web applications—real-time data processing, complex simulations, and performance-critical applications that would have required desktop software.
Advanced React Patterns: Compound Components & More
As React apps scale, you’ll want to structure components for greater reusability and composability. Here are some powerful React patterns:
Compound Components
The compound components pattern creates component APIs with shared context:
// Parent exposes context through 'Box' component function Layout({children}) { return <Box>{children}</Box> } // Children access shared context via Box function Profile() { return ( <Layout> <Box p={2}> <h1>Jane Doe</h1> </Box> </Layout> ); }This provides more flexible APIs than just props.
React Animation Guide: Libraries and Techniques
Animation brings interfaces to life. Thankfully, React has great open source libraries for animation. Let’s compare some popular options:
Framer Motion
Framer Motion uses declarative props for animation:
import { motion } from 'framer-motion'; const boxVariants = { hidden: { opacity: 0 }, visible: { opacity: 1 }, } function MyComponent() { return ( <motion.div initial="hidden" animate="visible" variants={boxVariants} /> ); }Framer Motion allows CSS, SVG, gesture, and physics animations.
React Transition Group
React Transition Group offers class-based transitions:
Testing React Apps: Beginner's Guide to TDD
Testing is crucial for ensuring React apps are stable and bug-free. Popular tools like Jest and React Testing Library make testing React components simple.
Let’s look at how to write great tests for React:
render Component
Render the component into a test environment using
renderfrom React Testing Library:import { render } from '@testing-library/react'; import Button from './Button'; test('displays button text', () => { const { getByText } = render(<Button>Click</Button>); expect(getByText('Click')).toBeInTheDocument(); });This renders the component virtually for testing.
Data Fetched Fast - A Beginner's Guide to React Query
Fetching data in React often means using stale state and complex caching logic.
React Query simplifies data fetching with powerful features like automatic caching, deduplication, and background updates.
Let’s explore some key features of React Query:
Declarative Data Fetching
Fetch data with the
useQueryhook:import { useQuery } from 'react-query'; function MyComponent() { const { data, error, isLoading } = useQuery('posts', fetchPosts); // use data }useQueryhandles declaring cache keys, performing fetches, and more.background Refetching
React Query automatically refetches “inactive” queries in the background:
Forms Simplified, A Beginner's Guide to Managing React Forms
Forms are a common need for many React apps. However, managing form state and validation can be tricky.
Thankfully, React provides great libraries to simplify complex forms. Let’s explore some helpful tools:
Formik for Form State
Formik handles common form tasks:
import { Formik } from 'formik'; const MyForm = () => ( <Formik initialValues={{ email: '' }} onSubmit={values => console.log(values)} > {formik => ( <form onSubmit={formik.handleSubmit}> <input name="email" onChange={formik.handleChange} value={formik.values.email} /> <button type="submit">Submit</button> </form> )} </Formik> )Formik reduces boilerplate for:
Go Performance Profiling and Optimization
Master Go’s profiling tools.
Understanding Go Performance Fundamentals
Before diving into specific profiling tools, it’s essential to understand the key factors that influence Go application performance and the metrics that matter most when optimizing.
Performance Metrics and Objectives
Performance optimization should always begin with clear objectives and metrics:
package main import ( "fmt" "time" ) // PerformanceMetrics tracks key performance indicators type PerformanceMetrics struct { Latency time.Duration // Time to complete a single operation Throughput int // Operations per second MemoryUsage uint64 // Bytes allocated CPUUsage float64 // CPU utilization percentage GCPause time.Duration // Garbage collection pause time ResponseTime time.Duration // Time to first byte (for servers) ErrorRate float64 // Percentage of operations that fail SaturationPoint int // Load at which performance degrades } // Example performance objectives for different application types func definePerformanceObjectives() { // Low-latency trading system tradingSystemObjectives := PerformanceMetrics{ Latency: 100 * time.Microsecond, // 99th percentile Throughput: 100000, // 100K trades per second MemoryUsage: 1 * 1024 * 1024 * 1024, // 1GB max heap CPUUsage: 80.0, // 80% max CPU utilization GCPause: 1 * time.Millisecond, // 1ms max GC pause ErrorRate: 0.0001, // 0.01% max error rate SaturationPoint: 120000, // Handles 20% over target load } // Web API service webAPIObjectives := PerformanceMetrics{ Latency: 50 * time.Millisecond, // 99th percentile Throughput: 5000, // 5K requests per second MemoryUsage: 2 * 1024 * 1024 * 1024, // 2GB max heap ResponseTime: 20 * time.Millisecond, // 20ms time to first byte ErrorRate: 0.001, // 0.1% max error rate SaturationPoint: 7500, // Handles 50% over target load } // Batch processing system batchProcessingObjectives := PerformanceMetrics{ Throughput: 10000, // 10K records per second MemoryUsage: 8 * 1024 * 1024 * 1024, // 8GB max heap CPUUsage: 95.0, // 95% max CPU utilization ErrorRate: 0.0005, // 0.05% max error rate } fmt.Printf("Trading system 99th percentile latency target: %v\n", tradingSystemObjectives.Latency) fmt.Printf("Web API throughput target: %v requests/second\n", webAPIObjectives.Throughput) fmt.Printf("Batch processing memory usage target: %v bytes\n", batchProcessingObjectives.MemoryUsage) }Performance Bottleneck Categories
Understanding the different types of bottlenecks helps guide your profiling approach:
Optimizing React Performance: Beginner's Guide
As React apps grow, you may notice performance starting to lag - sluggish interactions, choppy animations, janky scrolling.
Luckily, there are many great techniques to optimize React app performance. Let’s look at some top tips:
Use React.memo for Component Memoization
The
React.memoAPI can memoize component outputs:const MyComponent = React.memo(function MyComponent(props) { /* only rerenders if props change */ });This prevents unnecessary re-renders if props stay the same.
Virtualize Long Lists
Rendering thousands of rows kills performance. Virtualize rendering instead:
State Management 101 - A Beginner's Guide to React State
State management is a crucial concept in React. State allows components to dynamically update UI based on data changes.
However, managing state properly takes some practice. Let’s walk through the basics of handling state in React:
Creating State
The
useStatehook defines state variables:import { useState } from 'react'; function Example() { const [count, setCount] = useState(0); }useStateaccepts the initial state value and returns:- The current state
- A function to update it
Reading State
To display state in UI, simply reference the variable:
Accessible React Apps: Beginner's Guide to Accessibility
Accessibility is an important consideration when building modern web apps. React provides useful tools to make accessible, inclusive products.
Let’s look at some best practices for web accessibility with React:
Semantic HTML
Use proper HTML semantics. For example:
// Good <button>Save</button> // Avoid <div onclick="save">Save</div>Semantic HTML is parsed correctly by screen readers.
alt Text
Images should have
alttext describing content/purpose:<img src="logo.png" alt="Company logo" />Screen readers can’t interpret images.
alttext substitutes meaning.Mystery Boxes - A Beginner's Guide to React Fragments
When returning multiple elements from a component’s render method, they must be wrapped in a single parent DOM node:
// Needs a <div> wrapper return ( <div> <ChildA /> <ChildB /> </div> );This extra wrapper
<div>in the DOM is often unwanted. Enter React fragments - a way to group elements without adding extra nodes.Short Syntax
The simplest fragment syntax is:
return ( <> <ChildA /> <ChildB /> </> );The
<></>syntax declares a React fragment. Fragments let you skip the wrapper<div>.Unidirectional Data Flow in React: Beginner's Guide
A key advantage of React is its unidirectional data flow. This makes the flow of data predictable, and helps avoid unexpected side effects from data changing unexpectedly.
But what exactly does “unidirectional data flow” mean in React? Let’s break it down:
The Data Flows Down
In React, parent components pass data to children via props:
// Parent function Parent() { const [value, setValue] = useState('Hello'); return <Child value={value} />; } // Child function Child({value}) { return <h1>{value}</h1>; }The parent’s
valuestate is passed down into theChildvia a prop. This is the “data down” part.Advanced Go Channel Patterns: Mastering Communication in Concurrent Systems
Explore sophisticated channel patterns that enable elegant, efficient communication between goroutines in complex concurrent applications.
#Channels are Go’s primary tool for goroutine communication. Most developers know the basics - sending and receiving values - but advanced patterns unlock much more powerful concurrent designs.
Beyond Basic Channels
Basic channel operations are straightforward:
ch := make(chan int) go func() { ch <- 42 }() value := <-chBut real systems need more sophisticated coordination:
- Pipeline Processing: Chain operations together
- Fan-Out/Fan-In: Distribute work and collect results
- Rate Limiting: Control operation flow
- Timeouts: Handle operations that take too long
- Cancellation: Stop work when it’s no longer needed
Common Channel Pitfalls
Before diving into patterns, understand the traps:
Event Handling in React: Beginner's Guide
Responding to user events is a crucial part of building interactive UIs. In React, you can pass event handlers as props to components to run code when events occur.
Let’s look at how to listen and react to common events in React:
Binding to Events
Pass an event handler function to a component to subscribe to events:
function Button({ onClick }) { return ( <button onClick={onClick}> Click Me </button> ); } function App() { const handleClick = () => { console.log('Clicked!'); }; return ( <Button onClick={handleClick} /> ); }When the button is clicked,
handleClickwill be called.Circuit Breaker Patterns in Go
Implement robust circuit breaker patterns in Go for building resilient microservices that handle failures gracefully and prevent cascade failures.
Understanding Circuit Breaker Patterns
Before diving into implementation details, it’s crucial to understand the core concepts behind circuit breakers and how they fit into a broader resilience strategy.
The Circuit Breaker State Machine
At its core, a circuit breaker is a state machine with three distinct states:
package circuitbreaker // State represents the current state of the circuit breaker type State int const ( // Closed means the circuit breaker is allowing requests through Closed State = iota // Open means the circuit breaker is preventing requests from going through Open // HalfOpen means the circuit breaker is allowing a limited number of test requests HalfOpen ) // CircuitBreaker represents a basic circuit breaker type CircuitBreaker struct { state State failureCount int failureThreshold int resetTimeout time.Duration lastFailureTime time.Time mutex sync.RWMutex }The circuit breaker operates as follows:
Hooked on React - A Beginner's Guide to React Hooks
When React was first released, class components were the standard way to build complex UIs. However, classes can be cumbersome for some use cases.
Enter React hooks - a way to use React features like state and lifecycle methods without classes.
Hooks provide a more direct API for React concepts you already know. Let’s dive into some commonly used hooks:
Managing State with useState
The
useStatehook lets components use state without a class:Lifting State in React: Beginner's Guide
As React apps grow in complexity, managing shared state between components can become tricky. Oftentimes, several child components may need to reflect the same data in the UI.
The React solution is to lift the state up to a common ancestor component. The parent component can manage the state, and pass it down to the children via props.
Let’s look at how to lift state for easier data sharing:
The Problem with Local State
Imagine we have a
<Toolbox>component that contains some<Tool>components:Looping in JSX with React Keys: Beginner's Guide
Looping over arrays to render lists of elements is a common need in React apps. However, there are some special considerations when rendering lists in JSX.
One important aspect is the
keyprop. React uses keys to uniquely identify list elements and optimize performance.Let’s look at how to loop through arrays in JSX, and why keys are important:
Rendering Arrays in JSX
JSX makes looping straightforward - you can use JavaScript’s
map()function directly:Conditional Rendering in React
In React apps, you’ll often need to render different UI components conditionally based on certain state. For example, showing a login form if a user is not authenticated, or displaying different content based on configurable settings.
Here are useful patterns for conditional rendering in React:
If/Else Statements
The standard JS if/else statement works in JSX too:
function App() { const loggedIn = false; if (loggedIn) { return <WelcomeMessage />; } else { return <LoginForm />; } }This will render either the
WelcomeMessageorLoginFormcomponent based on the value ofloggedIn.Passing Data Between React Components with Props
One of React’s core concepts is reusability through composable components. Components allow splitting complex UI into separate, reusable pieces. However, for components to communicate, they need a way to pass data to each other. Enter props.
Props allow passing data from a parent component to a child component. They are like function parameters, but for React components.
Let’s look at a simple example:
// Parent component const Parent = () => { return ( <Child color="blue" onClick={handleClick} /> ); } // Child component const Child = (props) => { return <div>{props.color}</div> }The parent component
Parentpasses two props to the child componentChild- acolorstring and anonClickevent handler.Fostering DevOps Learning Culture: Lifelong Learning
Introduction
In the fast-evolving world of technology, where advancements and innovations are a constant, staying ahead of the curve is paramount for any DevOps team. One of the most effective ways to achieve this is by fostering a continuous learning culture. Embracing a mindset of lifelong learning not only empowers individuals to enhance their skills and knowledge but also drives collective growth and innovation within the organization. In this blog post, we will explore the significance of building a continuous learning culture in DevOps, its impact on team performance, and practical strategies to implement and sustain such a culture. Join us on this journey as we discover how to unleash the power of continuous learning in DevOps.
DevOps' Role in AI: Enhancing Intelligent Systems
Introduction
The world of technology is witnessing a remarkable fusion of two transformative disciplines: DevOps and Artificial Intelligence (AI). DevOps has revolutionized software development, emphasizing collaboration, automation, and continuous delivery, while AI has pushed the boundaries of what machines can achieve, enabling intelligent decision-making and automation. In this blog post, we will explore the symbiotic relationship between DevOps and AI, the challenges and opportunities it presents, and how organizations can leverage this powerful combination to unlock the full potential of intelligent systems. Join us on this journey as we delve into the role of DevOps in the realm of Artificial Intelligence.
DevOps and Microservices: Scalable, Agile Software Delivery
Introduction
In the fast-paced world of software development, two crucial methodologies have emerged as game-changers for modern development teams: DevOps and Microservices. DevOps is a cultural and technical movement that emphasizes collaboration, automation, and continuous delivery, while Microservices is an architectural style that structures applications as a collection of loosely coupled, independently deployable services. Combining these methodologies can empower organizations to achieve scalable, agile, and efficient software delivery. In this blog post, we will explore the intersection of DevOps and Microservices, their synergies, and how they complement each other. Additionally, we will dive into practical examples with code to demonstrate their seamless integration.
Nature-Inspired Problem Solving: Genetic Algorithms
Introduction
Genetic Algorithms (GAs) and Evolutionary Computation (EC) are powerful optimization techniques inspired by the process of natural selection and evolution. These algorithms mimic the principles of genetics and survival of the fittest to find high-quality solutions to complex problems. In this blog post, we will dive into the world of Genetic Algorithms and Evolutionary Computation, exploring their underlying concepts and demonstrating how they can be implemented in Python to tackle a variety of real-world challenges.
Python Dynamic Programming: Mastering Optimization
Introduction
Dynamic programming is a powerful algorithmic technique that allows developers to tackle complex problems efficiently. By breaking down these problems into smaller overlapping subproblems and storing their solutions, dynamic programming enables the creation of more adaptive and resource-efficient solutions. In this comprehensive guide, we will explore dynamic programming in-depth and learn how to apply it in Python to solve a variety of problems.
1. Understanding Dynamic Programming
Dynamic programming is a method of solving problems by breaking them down into smaller, simpler subproblems and solving each subproblem only once. The solutions to subproblems are stored in a data structure, such as an array or dictionary, to avoid redundant computations. Dynamic programming is particularly useful when a problem exhibits the following characteristics:
Python Reflection & Metaprogramming: Advanced Power
Introduction
Python is a versatile programming language that offers powerful features and capabilities. For advanced users, understanding and harnessing the potential of reflection and metaprogramming can open up a whole new world of possibilities. In this blog post, we’ll dive deep into the concepts of reflection and metaprogramming in Python, exploring their definitions, use cases, and implementation techniques. By mastering reflection and metaprogramming, you can build resilient, scalable, and highly adaptable applications. Get ready to elevate your Python skills as we unravel the magic of reflection and metaprogramming!
Go Context Patterns: Advanced Request Lifecycle Management
Master advanced Go context patterns for sophisticated request lifecycle management, cancellation, and deadline handling in concurrent applications.
Context Fundamentals
Why Context Matters More Than You Think
When I first encountered Go’s context package, I’ll be honest—I thought it was just another way to pass around cancellation signals. Boy, was I wrong. After years of debugging production issues and watching teams struggle with request lifecycle management, I’ve come to realize that context is actually the backbone of well-architected Go applications.
Kubernetes ReplicaSets: Scalability & Fault Tolerance
Introduction
In Kubernetes, ReplicaSets are a vital resource that enables scalable and fault-tolerant deployments of pods. They provide the ability to ensure a desired number of pod replicas are running at all times, allowing applications to handle increased traffic and recover from failures. In this blog post, we will delve into the world of ReplicaSets, exploring their functionalities, use cases, and best practices. By mastering ReplicaSets, you can build resilient and scalable deployments in Kubernetes.
Kubernetes Namespaces: Isolation & Resource Management
Introduction
In Kubernetes, namespaces provide a powerful abstraction that allows you to partition and isolate resources within a cluster. In this blog post, we’ll explore Kubernetes namespaces in detail and discuss their importance in achieving effective resource management and isolation. By understanding namespaces and leveraging their capabilities, you can enhance the security, scalability, and manageability of your Kubernetes deployments. Let’s dive into the world of namespaces and unlock their potential!
Understanding Kubernetes Namespaces
Kubernetes namespaces provide a virtual clustering mechanism that allows you to divide a cluster into multiple logical units. Each namespace acts as a separate virtual cluster, providing isolation and resource segmentation. This ensures that resources within a namespace are isolated from resources in other namespaces, providing a boundary for managing applications and their associated components.
K8s Cluster Resiliency: Advanced High Availability
Introduction
In today’s technology landscape, ensuring the resiliency and high availability of Kubernetes clusters is crucial for maintaining the availability of applications and business continuity. In this blog post, we will explore advanced techniques and best practices for building cluster resiliency in Kubernetes. By implementing these strategies, you can ensure that your applications remain highly available, even in the face of failures or disruptions. Let’s dive into the world of cluster resiliency and learn how to build rock-solid, resilient clusters!
K8s Networking Mastery: Advanced Cluster Communication
Introduction
Kubernetes has revolutionized container orchestration, enabling the efficient management of complex applications. As an advanced user, you’re likely already familiar with the basics of Kubernetes networking. In this blog post, we’ll dive deeper into advanced networking concepts, exploring techniques and best practices to optimize cluster communication, enhance security, and troubleshoot network-related issues. Get ready to level up your networking skills in Kubernetes!
Network Models in Kubernetes
In Kubernetes, network models play a crucial role in facilitating communication between pods. One commonly used model is the overlay network. This model allows pods to communicate seamlessly across different nodes by encapsulating network packets within an overlay network. Understanding how overlay networks work and how they enable efficient pod-to-pod communication is essential for advanced networking in Kubernetes.
Blue-Green Deployments in Kubernetes: Production & DR
Introduction
In today’s fast-paced and highly competitive digital landscape, organizations strive to deliver seamless and uninterrupted services to their customers. To achieve this, a robust production strategy combined with a solid disaster recovery (DR) plan is crucial. In the realm of Kubernetes, one powerful technique for achieving these goals is the implementation of blue-green deployments. This blog post will explore the concept of blue-green deployments, their benefits, and how they can be effectively leveraged in Kubernetes environments to streamline production and disaster recovery strategies.
AWS Production-DR Failover: Advanced Strategies
Introduction
Implementing failover between a production (Prod) account and a disaster recovery (DR) account is a critical aspect of ensuring high availability and business continuity in AWS. While DNS-based failover is a common approach, advanced users can explore additional strategies that provide enhanced control, automation, and scalability for failover scenarios. In this comprehensive guide, we will delve into advanced techniques that go beyond DNS, enabling advanced users to build robust failover architectures in AWS.
Python Context Managers Mastery: Resource Management
Introduction
Python context managers provide a convenient and reliable way to manage resources and ensure proper setup and teardown actions. Whether dealing with file operations, database connections, or any resource that needs to be acquired and released, context managers offer a clean and concise approach. This comprehensive blog post will explore the concept of context managers in Python, starting from the fundamentals and gradually progressing to more advanced techniques.
Understanding Context Managers
The Context Management Protocol
The Context Management Protocol defines the interface that objects must implement to be used as context managers. It requires the implementation of
__enter__()and__exit__()methods. The__enter__()method sets up the context, while the__exit__()method handles the cleanup actions.Python Decorators Mastery: Advanced Usage Guide
Introduction
Python decorators are a powerful feature that allows you to modify the behavior of functions or classes dynamically. Decorators provide a way to add functionality to existing code without modifying the original source. This blog post will delve into the concept of decorators in Python, starting from the basics and gradually progressing to more advanced techniques.
Understanding Decorators
Function Decorators
Function decorators are a way to modify the behavior of a function by wrapping it inside another function. The decorator function takes the original function as an argument, adds some functionality, and returns a modified function. This allows you to enhance or extend the behavior of functions without modifying their source code.
Python's Yield Mastery: Advanced Usage Guide
Introduction
Python’s
yieldstatement is a powerful feature that allows you to create generator functions. Generators provide an efficient way to generate a sequence of values without storing them all in memory at once. This blog post will delve into the concept ofyieldin Python, starting from the basics and gradually progressing to more advanced techniques.Understanding the Basics
Yield vs. Return
In Python, the
yieldstatement is used within a function to create a generator. Unlike thereturnstatement, which terminates the function and returns a single value,yieldallows the function to produce a sequence of values, one at a time. This is what differentiates generator functions from regular functions.Python: Unleashing the Power of Simplicity and Versatility
Getting Started with Python
Python is a versatile and popular programming language known for its simplicity and readability. It is widely used in various fields, including web development, data analysis, artificial intelligence, and automation. If you’re new to Python, this guide will help you get started with the basics and provide some code examples to illustrate key concepts.
Installing Python
To begin, you need to install Python on your computer. Python is available for multiple platforms, including Windows, macOS, and Linux. You can download the latest version of Python from the official website (https://www.python.org/downloads/) and follow the installation instructions specific to your operating system.
Python's Advanced Features: Empowering Programmers
Introduction:
In the vast realm of programming, Python stands tall as a language that caters to developers of all levels. Beyond its beginner-friendly syntax, Python harbors a treasure trove of advanced features that can elevate your coding prowess to new heights. In this blog post, we embark on an exhilarating journey to explore the depths of Python’s advanced features, unleashing their full potential. Brace yourself as we delve into the world of decorators, context managers, metaclasses, multiple inheritance, generators, coroutines, dynamic typing, duck typing, and functional programming tools. Get ready to unlock the true power of Python!
Advanced Go Testing Strategies and Benchmarking
Master comprehensive testing approaches in Go including unit testing.
#In the world of Go development, writing code is only half the battle. The other half—often more challenging and equally critical—is ensuring that your code works correctly, performs efficiently, and remains resilient under all conditions. As Go continues to power mission-critical systems across industries, from financial services to cloud infrastructure, the importance of comprehensive testing strategies cannot be overstated.
This guide explores advanced testing techniques that go beyond basic unit tests to help you build truly bulletproof Go applications. We’ll dive deep into sophisticated testing patterns, benchmarking strategies, and quality assurance practices that experienced Go developers use to ensure their systems perform reliably at scale.
Python's Yield: Unleashing Generator Magic
Introduction
Python, being a versatile language, offers numerous tools and features to streamline our coding experience. One such powerful feature is the
yieldkeyword. In this blog post, we will embark on an exciting journey to explore the hidden potential of Python’syieldstatement and dive into the realm of generators. Buckle up and get ready to witness the magic unfold!Section 1: Understanding the Basics of Yield
At its core,
yieldis used in Python to create generator functions. Generators are special functions that can pause and resume their execution, allowing us to iterate over a sequence of values without creating them all at once. Let’s take a look at a simple example to grasp the concept:GitOps Rising: Transforming DevOps for Streamlined Delivery
Introduction
In today’s fast-paced digital landscape, where businesses strive to deliver high-quality software products with agility and efficiency, DevOps practices have become indispensable. DevOps aims to bridge the gap between software development and operations, enabling seamless collaboration, faster deployments, and improved overall software delivery. One of the most prominent trends revolutionizing the DevOps world is GitOps. In this blog post, we will explore the concept of GitOps, its benefits, and why it has gained significant traction in the industry.
Enhancing Security: How DevOps Mitigates Cyber Threats
Introduction
In today’s digital landscape, where cyber threats are prevalent and evolving, organizations must adopt robust security measures to safeguard their sensitive data and systems. In this pursuit, DevOps practices have emerged as a powerful ally, enabling organizations to build secure and resilient software solutions. By integrating security into every stage of the software development lifecycle, DevOps plays a crucial role in preventing, detecting, and responding to cyber attacks. In this blog post, we will explore how DevOps helps organizations fend off hackers and enhance their overall security posture.
Site Reliability Engineering (SRE) in Modern Organizations
Introduction
In today’s fast-paced and technology-driven world, organizations heavily rely on digital services to deliver their products and serve their customers. With the increasing complexity of modern infrastructure and the need for high availability and reliability, Site Reliability Engineering (SRE) has emerged as a critical discipline. SRE combines software engineering principles with operations expertise to ensure the smooth functioning of complex systems. In this blog post, we will explore the importance of SRE in organizations and how it contributes to their success.
DevOps & DevSecOps: Bridging Dev-Security Gap
Introduction
In today’s fast-paced digital landscape, where software development cycles are becoming increasingly rapid and security threats are ever-present, organizations are seeking effective ways to align development and security practices. Two prominent approaches that have gained significant attention are DevOps and DevSecOps. While these terms may sound similar, there are crucial distinctions between them. In this blog post, we will explore the differences between DevOps and DevSecOps, their goals, and how they contribute to efficient and secure software delivery.
Unleashing the Power: Lambda - A Killer Feature in AWS
In the world of cloud computing, Amazon Web Services (AWS) has long been a dominant player, providing a comprehensive suite of services to meet the diverse needs of businesses. Among its vast array of offerings, one particular service stands out as a true game-changer: AWS Lambda. Lambda is a serverless computing platform that has revolutionized the way developers build and deploy applications. In this blog post, we’ll explore why Lambda is rightly hailed as a killer feature in AWS.
Python vs Java Performance: Programming Powerhouses
In the vast landscape of programming languages, Python and Java have emerged as titans, offering robust solutions for a wide range of applications. When it comes to performance, developers often find themselves pondering which language reigns supreme. In this blog post, we will delve into the world of Python and Java, exploring their performance characteristics, strengths, and weaknesses, and ultimately helping you make an informed choice for your next project.
Teach me the Basics of Data Science in Python
An overview of Data Science in Python
This is an overview of the basics of data science in Python. Data science involves extracting knowledge and insights from data using various techniques such as data cleaning, visualization, statistical analysis, and machine learning. Python is a popular programming language in the data science community due to its rich ecosystem of libraries and tools. Let’s go through the key components of data science in Python.
How to Share a VPC from one AWS Account to Another
To share a Virtual Private Cloud (VPC) from one AWS account to another, you can use the AWS Resource Access Manager (RAM) service. RAM allows you to securely share your AWS resources with other AWS accounts while maintaining control over the resource permissions.
Here’s a step-by-step guide on how to share a VPC from one AWS account to another:
1. Set up the necessary permissions
In the account that owns the VPC (the sharing account), ensure that you have the required permissions to share the VPC. You need to have the
ram:CreateResourceShareandec2:DescribeVpcIAM permissions.[Solved] Set CloudWatch Logs role ARN in account settings
The error message you mentioned, “CloudWatch Logs role ARN must be set in account settings to enable logging,” typically occurs when you’re trying to enable logging for an AWS service that requires a CloudWatch Logs role, but the necessary role hasn’t been set up or configured correctly in your account settings. To resolve this issue, you can follow these steps:
-
Sign in to the AWS Management Console.
-
Open the AWS CloudTrail console at https://console.aws.amazon.com/cloudtrail/.
How to Create CloudFormation with Multiple Files
To create a CloudFormation (CFN) stack with multiple files, you can follow these general steps:
-
Organize your resources: Divide your resources into logical groups or services. For example, you might have separate files for networking, storage, compute, and so on.
-
Create YAML or JSON templates: Create individual
YAMLorJSONtemplates for each group or service. Each template will define the resources specific to that group. For example, networking.yaml, storage.yaml, and compute.yaml.Teach me Hashicorp Vault
Introduction to Hashicorp Vault
HashiCorp Vault is a popular open-source tool designed for securely storing and managing secrets, such as API keys, passwords, certificates, and other sensitive information. It provides a centralized place to store secrets, access control mechanisms, and auditing capabilities. Vault ensures that only authorized applications and users can access the secrets they need, thus improving security in an organization.
Concepts
Here’s a high-level overview of the key concepts and components of HashiCorp Vault:
How to Generate Terraform using a Bash Shell script
To generate Terraform code using a Bash shell script, you can utilize Python within the script. Here’s an example of how you can achieve this:
1. Create a new Bash script file
Open a text editor and create a new file, for example,
generate_terraform.sh.2. Add the shebang line
Start the script with the shebang line to specify that it should be interpreted using Bash:
#!/bin/bash3. Install Required Libraries
Since you’ll be using Python within the script, ensure that Python and
pipare installed on your system. You also need to install thehclwriterlibrary. To do this, you can include the installation commands within the script:How to Generate Terraform using Python
To generate Terraform code using Python, you can utilize the power of the language and various libraries to dynamically create and manipulate the Terraform configuration files. Here’s a step-by-step guide on how to get started:
1. Install Required Libraries
Make sure you have Python installed on your system. Additionally, install the hclwriter library, which simplifies the process of generating HCL (HashiCorp Configuration Language) code, the language used by Terraform. You can install it using pip:
Make EKS cluster private with NodeGroup access
The Theory
To make an Amazon Elastic Kubernetes Service (EKS) cluster private and allow nodes to join through a node group, you need to follow a few steps. By default, EKS creates a public cluster, but you can configure it to make it private for enhanced security. Here’s an overview of the process:
- Create a VPC: Start by creating a Virtual Private Cloud (VPC) in your AWS account if you haven’t already. This VPC will be used to host your private EKS cluster.
- Create private subnets: Within the VPC, create one or more private subnets. These subnets will provide the network isolation required for a private cluster. Make sure the subnets have no direct internet access and that their route tables do not have an internet gateway attached.
- Create security groups: Create security groups to define the inbound and outbound traffic rules for your EKS cluster and nodes. These security groups should allow communication between the control plane and the worker nodes, as well as any other necessary network traffic.
- Create a NAT gateway: Since the private subnets don’t have direct internet access, you need to set up a Network Address Translation (NAT) gateway in a public subnet to enable outbound internet connectivity for resources in the private subnets.
- Configure VPC endpoints: Create VPC endpoints for EKS and EC2 to allow private communication between your EKS cluster control plane and the worker nodes. These endpoints will ensure that the control plane and nodes can communicate without requiring access to the public internet.
- Create a private EKS cluster: Now, create a private EKS cluster using the AWS Management Console, AWS CLI, or AWS SDKs. During the cluster creation, specify the private subnets, security groups, and VPC endpoints you created earlier. This will ensure that the cluster is deployed within the private subnets and can communicate with the nodes via the VPC endpoints.
- Create a node group: Once the cluster is created, you can proceed to create a node group. When creating the node group, specify the private subnets and security groups that you set up earlier. The node group will be deployed in the private subnets and join the private EKS cluster.
Following these steps will result in a private EKS cluster where the control plane and worker nodes communicate privately through the VPC endpoints. The private nature of the cluster enhances security by reducing exposure to the public internet.
Which is the best language to use in DevOps
In DevOps, there isn’t a single “best” language that universally applies to all situations. The choice of programming language depends on various factors, including the specific requirements of your project, existing infrastructure, team’s expertise, and the ecosystem surrounding the tools and technologies you plan to use. However, here are some commonly used languages in different areas of DevOps:
Automation and Configuration Management
- Ansible: Ansible uses a declarative YAML syntax for defining configurations and automation tasks. It is known for its simplicity and ease of use.
- Python: Python is a versatile language widely used in DevOps. It has a rich ecosystem of libraries and frameworks, making it suitable for automation, scripting, and building infrastructure tools.
- Ruby: Ruby is the language used by Chef, another popular configuration management tool. If you plan to use Chef, having knowledge of Ruby can be beneficial.
Infrastructure as Code
- Terraform: Terraform, a tool for provisioning and managing infrastructure, uses its own domain-specific language (DSL). Although it has its own DSL, it is worth noting that Terraform configurations can be written using JSON or HCL (HashiCorp Configuration Language), which is similar to JSON.
- Cloud-specific languages: Cloud providers often provide their own specific languages or SDKs for infrastructure provisioning and management. For example, AWS provides AWS CloudFormation (JSON/YAML-based) and AWS SDKs for various languages such as Python, Java, and JavaScript.
Continuous Integration/Continuous Deployment (CI/CD)
- Jenkinsfile (Groovy): Jenkins, a popular CI/CD tool, uses a Groovy-based DSL for defining pipelines and workflows.
- YAML: Many CI/CD tools, including GitLab CI/CD and GitHub Actions, use YAML-based configuration files for defining CI/CD pipelines.
Monitoring and Data Analysis
- Python: Python is often used for scripting and building monitoring tools. It has libraries like Pandas, NumPy, and matplotlib that are useful for data analysis and visualization.
- Go: Go (Golang) is gaining popularity for building high-performance and scalable monitoring systems and data processing pipelines.
Moreover
In the world of DevOps, the choice of programming language plays a crucial role in effectively managing and automating various tasks. However, it’s worth noting that many DevOps tasks involve using multiple languages and tools together, rather than relying on a single language. This approach allows DevOps teams to leverage the strengths and capabilities of different languages and tools to meet their specific requirements.
How is Ansible different from Chef or Puppet
Ansible, Chef, and Puppet are all popular configuration management and automation tools, but they differ in their approach and architecture. Here’s a comparison of Ansible with Chef and Puppet:
Architecture
- Ansible: Ansible follows a simple agentless architecture. It uses SSH or WinRM to connect to managed nodes and executes tasks remotely without the need for installing any agent software on the nodes.
- Chef: Chef uses a client-server architecture. It requires a Chef client agent to be installed on each managed node, which communicates with a central Chef server.
- Puppet: Puppet also follows a client-server architecture. It requires the installation of the Puppet agent on each managed node, which communicates with a central Puppet master.
Configuration Language
- Ansible: Ansible uses YAML, a human-readable language, for defining playbooks and configurations. YAML has a simpler syntax and is easy to understand and write.
- Chef: Chef uses a Ruby-based DSL (Domain-Specific Language) called the Chef DSL. It allows for more flexibility and extensibility but has a steeper learning curve for users not familiar with Ruby.
- Puppet: Puppet uses its own declarative language called Puppet DSL or Puppet language. It is designed to be readable and expressive, although some users find it more complex than Ansible’s YAML.
Agent-based vs. Agentless
- Ansible: Ansible is agentless, meaning it does not require a separate agent to be installed on the managed nodes. This simplifies the setup and maintenance process.
- Chef: Chef and Puppet both require agents to be installed on the managed nodes, which adds an extra step and potential overhead.
- Puppet: Puppet also requires agent installation on managed nodes.
Ease of Use
- Ansible: Ansible is known for its simplicity and ease of use. Its YAML syntax and agentless architecture make it accessible to users with varying levels of experience.
- Chef: Chef offers a higher level of flexibility but may have a steeper learning curve, especially for users who are not familiar with Ruby or DSLs.
- Puppet: Puppet has a reputation for being powerful but also having a steeper learning curve due to its language and architecture.
Community and Ecosystem
- Ansible: Ansible has a large and active community with extensive documentation and a wide range of community-contributed modules and playbooks available for various use cases.
- Chef: Chef also has an active community and offers a rich ecosystem of cookbooks (equivalent to Ansible’s roles) available in the Chef Supermarket.
- Puppet: Puppet has a well-established community and ecosystem, with a central repository called Puppet Forge that provides a collection of modules.
Making the correct choice
Overall, the choice between Ansible, Chef, or Puppet depends on your specific requirements, familiarity with different languages, preferences, and the existing infrastructure in your environment. Each tool has its strengths and can be effective for automating configuration management tasks, but Ansible’s simplicity and agentless architecture make it a popular choice for many users.
Teach me the basics of Ansible
Ansible is an open-source automation tool that allows you to manage and configure computer systems. It uses a declarative language called YAML (Yet Another Markup Language) for defining configurations and tasks. Ansible follows a client-server architecture, where the controlling machine (the Ansible server) manages and communicates with the target machines (managed nodes) over SSH.
The basics of Ansible
Inventory
An inventory file in Ansible contains a list of target hosts (managed nodes) on which Ansible performs operations. You can define the inventory in a simple text file or in dynamic inventory scripts. Each host entry can have associated variables like IP address, username, and SSH key.
How do you create an EKS cluster using CloudFormation
The steps to achieve this
To create an Amazon Elastic Kubernetes Service (EKS) cluster using CloudFormation, you can follow these steps:
-
Create a CloudFormation template: Start by creating a CloudFormation template in YAML or JSON format. This template will define the resources required for your EKS cluster, including the cluster itself, worker nodes, and other necessary components.
-
Define the EKS cluster resource: Within your CloudFormation template, define an AWS::EKS::Cluster resource. Specify the desired configuration for your EKS cluster, such as the version, name, and role-based access control (RBAC) configuration.
How to connect an API Gateway to Inline Lambda in Terraform
To connect an API Gateway to an inline Lambda function using Terraform, you can follow these steps:
- Define your API Gateway and Lambda function resources in your Terraform configuration. Here’s an example:
resource "aws_api_gateway_rest_api" "my_api_gateway" { name = "MyApiGateway" } resource "aws_api_gateway_resource" "my_api_gateway_resource" { rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id parent_id = aws_api_gateway_rest_api.my_api_gateway.root_resource_id path_part = "myresource" } resource "aws_api_gateway_method" "my_api_gateway_method" { rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id resource_id = aws_api_gateway_resource.my_api_gateway_resource.id http_method = "GET" authorization = "NONE" integration { type = "AWS_PROXY" http_method = "POST" uri = "arn:aws:apigateway:${var.region}:lambda:path/2015-03-31/functions/${aws_lambda_function.my_lambda_function.arn}/invocations" } } resource "aws_api_gateway_deployment" "my_api_gateway_deployment" { rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id stage_name = "prod" } resource "aws_lambda_function" "my_lambda_function" { function_name = "MyLambdaFunction" runtime = "python3.8" handler = "index.lambda_handler" inline_code = <<EOF def lambda_handler(event, context): return { 'statusCode': 200, 'body': 'Hello from Lambda!' } EOF } resource "aws_lambda_permission" "my_lambda_permission" { statement_id = "AllowAPIGatewayInvoke" action = "lambda:InvokeFunction" function_name = aws_lambda_function.my_lambda_function.arn principal = "apigateway.amazonaws.com" source_arn = "arn:aws:execute-api:${var.region}:${data.aws_caller_identity.current.account_id}:${aws_api_gatewayIn the above example, the Lambda function is defined inline using the
inline_codeproperty. The code inside thelambda_handlerfunction can be customized according to your requirements.gRPC Microservices with Go
Build high-performance microservices using gRPC and Go with advanced patterns for service communication.
Advanced gRPC Service Design
Before diving into optimization techniques, it’s essential to establish a solid foundation with well-designed gRPC services that follow best practices and leverage the full power of Protocol Buffers.
Domain-Driven Service Boundaries
When designing gRPC services, aligning service boundaries with domain contexts helps create cohesive, maintainable APIs:
// user_service.proto syntax = "proto3"; package user; option go_package = "github.com/example/user"; import "google/protobuf/timestamp.proto"; service UserService { // User lifecycle operations rpc CreateUser(CreateUserRequest) returns (User); rpc GetUser(GetUserRequest) returns (User); rpc UpdateUser(UpdateUserRequest) returns (User); rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse); // Domain-specific operations rpc VerifyUserEmail(VerifyUserEmailRequest) returns (VerifyUserEmailResponse); rpc ResetPassword(ResetPasswordRequest) returns (ResetPasswordResponse); // Batch operations for efficiency rpc GetUsers(GetUsersRequest) returns (GetUsersResponse); } message User { string id = 1; string email = 2; string display_name = 3; bool email_verified = 4; google.protobuf.Timestamp created_at = 5; google.protobuf.Timestamp updated_at = 6; } // Other message definitions...Versioning Strategies
Proper versioning is crucial for maintaining backward compatibility while evolving your APIs:
API Gateway to Inline Lambda in CloudFormation
To connect an API Gateway to an inline Lambda function using CloudFormation, you can follow these steps:
- Define your API Gateway and Lambda function resources in your CloudFormation template. Here’s an example:
Resources: MyApiGateway: Type: AWS::ApiGateway::RestApi Properties: Name: MyApiGateway MyApiGatewayResource: Type: AWS::ApiGateway::Resource Properties: RestApiId: !Ref MyApiGateway ParentId: !GetAtt MyApiGateway.RootResourceId PathPart: myresource MyApiGatewayMethod: Type: AWS::ApiGateway::Method Properties: RestApiId: !Ref MyApiGateway ResourceId: !Ref MyApiGatewayResource HttpMethod: GET AuthorizationType: NONE Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:MyLambdaFunction/invocations" MyApiGatewayDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: !Ref MyApiGateway MyApiGatewayStage: Type: AWS::ApiGateway::Stage Properties: StageName: prod RestApiId: !Ref MyApiGateway DeploymentId: !Ref MyApiGatewayDeployment MyLambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: MyLambdaFunction Runtime: python3.8 Handler: index.lambda_handler Code: ZipFile: | def lambda_handler(event, context): return { 'statusCode': 200, 'body': 'Hello from Lambda!' }In the above example, the Lambda function is defined inline using the
ZipFileproperty. The code inside thelambda_handlerfunction can be customized according to your requirements.How to connect an API Gateway to Lambda in CloudFormation
To connect an API Gateway to a Lambda function using CloudFormation, you can follow these steps:
- Define your API Gateway and Lambda function resources in your CloudFormation template. Here’s an example:
Resources: MyLambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: MyLambdaFunction Runtime: python3.8 Handler: index.handler Code: S3Bucket: my-lambda-code-bucket S3Key: lambda-code.zip MyApiGateway: Type: AWS::ApiGateway::RestApi Properties: Name: MyApiGateway- Create a resource of type
AWS::ApiGateway::Resourceto define the resource path for your API Gateway:
MyApiGatewayResource: Type: AWS::ApiGateway::Resource Properties: RestApiId: !Ref MyApiGateway ParentId: !GetAtt MyApiGateway.RootResourceId PathPart: myresource- Create a method on the resource to define the HTTP method (e.g., GET, POST) and integration details:
MyApiGatewayMethod: Type: AWS::ApiGateway::Method Properties: RestApiId: !Ref MyApiGateway ResourceId: !Ref MyApiGatewayResource HttpMethod: GET AuthorizationType: NONE Integration: Type: AWS IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocationsIn the above example, the
Uriproperty references the ARN of the Lambda function.Create DynamoDB Table & Add Items using Python 3 from Lambda
To create a DynamoDB table and add items to it using Python 3 from AWS Lambda, you can use the AWS SDK for Python, also known as Boto3. Here’s a step-by-step guide:
- Set up your AWS environment:
- Install Boto3 by running
pip install boto3in your local development environment. - Set up your AWS credentials and configure your AWS CLI or environment variables. You can find detailed instructions in the AWS documentation.
- Install Boto3 by running
- Create a Lambda function in the AWS Management Console:
- Go to the AWS Management Console and navigate to the Lambda service.
- Click on “Create function” and follow the instructions to create a new Lambda function.
- Choose the desired runtime as Python 3.x.
- Write the Python code to create the DynamoDB table and add items:
- In the Lambda function code editor, enter the following code:
import boto3 def lambda_handler(event, context): # Create a DynamoDB client dynamodb = boto3.client('dynamodb') # Define the table name and schema table_name = 'YourTableName' table_schema = [ { 'AttributeName': 'ID', 'AttributeType': 'N' }, { 'AttributeName': 'Name', 'AttributeType': 'S' } ] # Create the DynamoDB table dynamodb.create_table( TableName=table_name, KeySchema=[ { 'AttributeName': 'ID', 'KeyType': 'HASH' } ], AttributeDefinitions=table_schema, ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) # Wait for the table to be created dynamodb.get_waiter('table_exists').wait(TableName=table_name) # Add items to the table items = [ { 'ID': {'N': '1'}, 'Name': {'S': 'Item 1'} }, { 'ID': {'N': '2'}, 'Name': {'S': 'Item 2'} } ] with dynamodb.batch_writer(TableName=table_name) as batch: for item in items: batch.put_item(Item=item) return { 'statusCode': 200, 'body': 'DynamoDB table created and items added successfully.' }- Configure the Lambda function:
- In the AWS Lambda function configuration, specify the following:
- Handler: Enter the name of the Python file and the lambda_handler function. For example,
filename.lambda_handler. - Runtime: Python 3.x.
- Timeout: Set an appropriate timeout based on the expected execution time of your code.
- Role: Choose or create an execution role with appropriate DynamoDB permissions.
- Handler: Enter the name of the Python file and the lambda_handler function. For example,
- In the AWS Lambda function configuration, specify the following:
- Save and test the Lambda function:
- Save the Lambda function by clicking on the “Save” button.
- Test the function by clicking on the “Test” button and configuring a test event.
- Monitor the execution logs and check for any errors or exceptions.
When you invoke the Lambda function, it will create a DynamoDB table with the specified schema and add the items to it using a batch write operation. Make sure to replace
'YourTableName'with the desired name for your DynamoDB table.How to create a Site-to-Site VPN in Boto3 Python
To create a site-to-site VPN using the Boto3 library in Python, you can utilize the
boto3.client('ec2')client to interact with the AWS EC2 service. Here’s an example code snippet to create a site-to-site VPN:import boto3 ec2_client = boto3.client('ec2') # Create VPN Gateway vpn_gateway_response = ec2_client.create_vpn_gateway(Type='ipsec.1', TagSpecifications=[{ 'ResourceType': 'vpn-gateway', 'Tags': [{'Key': 'Name', 'Value': 'SiteToSiteVPN'}] }]) vpn_gateway_id = vpn_gateway_response['VpnGateway']['VpnGatewayId'] # Create VPN Connection vpn_connection_response = ec2_client.create_vpn_connection( Type='ipsec.1', CustomerGatewayId='<CUSTOMER_GATEWAY_ID>', VpnGatewayId=vpn_gateway_id, Options={ 'StaticRoutesOnly': True }, TagSpecifications=[{ 'ResourceType': 'vpn-connection', 'Tags': [{'Key': 'Name', 'Value': 'SiteToSiteVPNConnection'}] }] ) vpn_connection_id = vpn_connection_response['VpnConnection']['VpnConnectionId'] # Create VPN Connection Route ec2_client.create_vpn_connection_route( DestinationCidrBlock='<DESTINATION_CIDR_BLOCK>', VpnConnectionId=vpn_connection_id )In the above code, you need to replace
<CUSTOMER_GATEWAY_ID>with the ID of the customer gateway representing the remote site, and<DESTINATION_CIDR_BLOCK>with the CIDR block of the remote network you want to connect to.How to create a Site-to-Site VPN in Terraform
To create a site-to-site VPN using Terraform, you can use the
aws_vpn_gatewayandaws_vpn_connectionresources from the AWS provider. Here’s an example Terraform configuration to create a site-to-site VPN:resource "aws_vpn_gateway" "vpn_gateway" { vpc_id = "<VPC_ID>" tags = { Name = "SiteToSiteVPN" } } resource "aws_vpn_connection" "vpn_connection" { customer_gateway_id = "<CUSTOMER_GATEWAY_ID>" vpn_gateway_id = aws_vpn_gateway.vpn_gateway.id type = "ipsec.1" static_routes_only = true tags = { Name = "SiteToSiteVPNConnection" } } resource "aws_vpn_connection_route" "vpn_connection_route" { destination_cidr_block = "<DESTINATION_CIDR_BLOCK>" vpn_connection_id = aws_vpn_connection.vpn_connection.id }In the above Terraform configuration, you need to replace
<VPC_ID>with the ID of the VPC where the VPN gateway will be attached,<CUSTOMER_GATEWAY_ID>with the ID of the customer gateway representing the remote site, and<DESTINATION_CIDR_BLOCK>with the CIDR block of the remote network you want to connect to.How to create a Site-to-Site VPN in CloudFormation
To create a site-to-site VPN (Virtual Private Network) using AWS CloudFormation, you can use the
AWS::EC2::VPNGatewayandAWS::EC2::VPNConnectionresources. Here’s an example CloudFormation template to create a site-to-site VPN:AWSTemplateFormatVersion: '2010-09-09' Resources: VpnGateway: Type: AWS::EC2::VPNGateway Properties: Type: ipsec.1 Tags: - Key: Name Value: SiteToSiteVPN VpnConnection: Type: AWS::EC2::VPNConnection Properties: Type: ipsec.1 CustomerGatewayId: <CUSTOMER_GATEWAY_ID> VpnGatewayId: !Ref VpnGateway StaticRoutesOnly: true Tags: - Key: Name Value: SiteToSiteVPNConnection VpnConnectionRoute: Type: AWS::EC2::VPNConnectionRoute Properties: DestinationCidrBlock: <DESTINATION_CIDR_BLOCK> VpnConnectionId: !Ref VpnConnectionIn the above template, you need to replace
<CUSTOMER_GATEWAY_ID>with the ID of the customer gateway representing the remote site, and<DESTINATION_CIDR_BLOCK>with the CIDR block of the remote network you want to connect to.How to AWS sts assume role in one command - without jq
The issue - what it takes to assume a role
To assume an AWS role in the CLI, you will have to do something like this:
aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test --region eu-central-1This will give you the following output:
{ "Credentials": { "AccessKeyId": "someAccessKeyId", "SecretAccessKey": "someSecretAccessKey", "SessionToken": "someSessionToken", "Expiration": "20203-01-02T06:52:13+00:00" }, "AssumedRoleUser": { "AssumedRoleId": "idOfTheAssummedRole", "Arn": "theARNOfTheRoleIWantToAssume" } }But then you will have to manually copy and paste the values of
AccessKeyId,SecretAccessKeyandSessionTokenin a bunch of exports like this:How to create a Lambda in CloudFormation
You can create a Lambda in CloudFormation as follows:
Option 1 - Inline code
Resources: MyLambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: MyLambdaFunction Runtime: python3.8 Handler: index.lambda_handler Code: ZipFile: | import json def lambda_handler(event, context): # Your Lambda function code here return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } Role: !GetAtt MyLambdaExecutionRole.ArnIn this example, instead of specifying the
S3BucketandS3Keyproperties under theCodesection, you use theZipFileproperty to provide the actual code as a multiline string. The code is written in Python and includes a simple Lambda handler function.How to create a Lambda in Terraform
To create an AWS Lambda function using Terraform, you need to define the necessary resources in a Terraform configuration file. Here’s an example of how you can create a Lambda function using Terraform:
Option 1 - Seperate Lambda Source
- Create a new directory for your Terraform configuration and navigate to it in your terminal.
- Create a new file with a
.tfextension, such aslambda.tf, and open it in a text editor. - In the lambda.tf file, add the following code:
provider "aws" { region = "us-east-1" # Replace with your desired AWS region } resource "aws_lambda_function" "my_lambda" { function_name = "my-lambda-function" role = aws_iam_role.lambda_role.arn handler = "index.handler" runtime = "nodejs14.x" # Replace with your desired runtime // Replace with the path to your Lambda function code filename = "path/to/lambda/code.zip" // Replace with the appropriate values for your Lambda function environment { variables = { KEY = "VALUE" KEY2 = "VALUE2" } } } resource "aws_iam_role" "lambda_role" { name = "my-lambda-role" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } EOF } resource "aws_iam_role_policy_attachment" "lambda_policy_attachment" { role = aws_iam_role.lambda_role.name policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }- In the above code, you can customize the following parts:
region: Specify the AWS region where you want to create the Lambda function.runtime: Specify the runtime environment for your Lambda function (e.g.,nodejs14.x,python3.8, etc.).filename: Update the path to your Lambda function code. Ensure that the code is packaged in a ZIP file.
You can also modify the environment variables section (
KEYandVALUE) according to your requirements.How to create a Bastion server in Terraform
To create a Bastion server using Terraform, you need to define the necessary resources in a Terraform configuration file. Here’s an example of how you can create a Bastion server using Terraform:
# Define the security group resource "aws_security_group" "bastion_sg" { name = "bastion-security-group" description = "Bastion Security Group" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } vpc_id = "your-vpc-id" } # Define the Bastion instance resource "aws_instance" "bastion_instance" { ami = "your-ami-id" instance_type = "t2.micro" # Update with the desired instance type key_name = "your-key-pair-name" security_group_ids = [aws_security_group.bastion_sg.id] user_data = <<-EOF #!/bin/bash echo "AllowTcpForwarding yes" >> /etc/ssh/sshd_config service sshd restart iptables -t nat -A PREROUTING -p tcp --dport 22 -j REDIRECT --to-port 2222 iptables-save > /etc/sysconfig/iptables systemctl enable iptables systemctl restart iptables EOF } # Allocate an Elastic IP and associate it with the Bastion instance resource "aws_eip" "bastion_eip" { instance = aws_instance.bastion_instance.id }In the Terraform configuration:
How to create a Bastion server in CloudFormation
To create a Bastion server using AWS CloudFormation, you need to define the necessary resources in a CloudFormation template. Here’s an example of how you can create a Bastion server using CloudFormation:
AWSTemplateFormatVersion: "2010-09-09" Resources: BastionSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Bastion Security Group SecurityGroupIngress: - IpProtocol: tcp FromPort: 22 ToPort: 22 CidrIp: 0.0.0.0/0 VpcId: "your-vpc-id" BastionInstance: Type: AWS::EC2::Instance Properties: ImageId: "your-ami-id" InstanceType: "t2.micro" # Update with the desired instance type SecurityGroupIds: - !Ref BastionSecurityGroup KeyName: "your-key-pair-name" UserData: Fn::Base64: !Sub | #!/bin/bash echo "AllowTcpForwarding yes" >> /etc/ssh/sshd_config service sshd restart iptables -t nat -A PREROUTING -p tcp --dport 22 -j REDIRECT --to-port 2222 iptables-save > /etc/sysconfig/iptables systemctl enable iptables systemctl restart iptables BastionEIP: Type: AWS::EC2::EIP Properties: InstanceId: !Ref BastionInstanceIn the CloudFormation template:
How to you create a Cross Account Role in Terraform
To create a cross-account role in Terraform, you need to perform the following steps:
1. Define the IAM role
Define the IAM role in the Terraform configuration
resource "aws_iam_role" "cross_account_role" { name = "CrossAccountRole" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::<ACCOUNT_ID>:root" }, "Action": "sts:AssumeRole" } ] } EOF }In the
assume_role_policysection, replace<ACCOUNT_ID>with the AWS account ID of the target account that will assume this role.How to you create a Cross Account Role in CloudFormation
To create a cross-account role in CloudFormation, you can follow these steps:
1. Create a CloudFormation template
Create a new CloudFormation template in YAML or JSON format. This template will define the resources, including the cross-account role, that you want to create.
2. Define the cross-account role
Within your CloudFormation template, define the cross-account role using the
AWS::IAM::Roleresource type. Specify the necessary properties such asRoleName,AssumeRolePolicyDocument, andManagedPolicyArns.How to create Public and Private Subnets in CloudFormation
To create public and private subnets in AWS CloudFormation, you can use the AWS CloudFormation Template Language (CFT) to define your network configuration. Here’s an example CloudFormation template that demonstrates how to create public and private subnets within a Virtual Private Cloud (VPC) in AWS:
Resources: MyVPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 Tags: - Key: Name Value: my-vpc PublicSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.0.0/24 AvailabilityZone: us-west-2a Tags: - Key: Name Value: public-subnet PrivateSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.1.0/24 AvailabilityZone: us-west-2b Tags: - Key: Name Value: private-subnetIn this example, the
AWS::EC2::VPCresource creates a VPC with the specified CIDR block. TheAWS::EC2::Subnetresources create the public and private subnets within the VPC, using different CIDR blocks and availability zones.How to create Public and Private Subnets in Terraform
To create public and private subnets in Terraform, you can use the AWS provider to define your network configuration. Here’s an example configuration that demonstrates how to create public and private subnets within a Virtual Private Cloud (VPC) in AWS:
# Define your AWS provider configuration provider "aws" { region = "us-west-2" # Update with your desired region } # Create the VPC resource "aws_vpc" "my_vpc" { cidr_block = "10.0.0.0/16" # Update with your desired VPC CIDR block tags = { Name = "my-vpc" } } # Create the public subnet resource "aws_subnet" "public_subnet" { vpc_id = aws_vpc.my_vpc.id cidr_block = "10.0.0.0/24" # Update with your desired public subnet CIDR block availability_zone = "us-west-2a" # Update with your desired availability zone tags = { Name = "public-subnet" } } # Create the private subnet resource "aws_subnet" "private_subnet" { vpc_id = aws_vpc.my_vpc.id cidr_block = "10.0.1.0/24" # Update with your desired private subnet CIDR block availability_zone = "us-west-2b" # Update with your desired availability zone tags = { Name = "private-subnet" } }In this example, the
aws_vpcresource creates a VPC with the specified CIDR block. Theaws_subnetresources create the public and private subnets within the VPC, using different CIDR blocks and availability zones.Create Internet Gateway & Assign to EC2 in CloudFormation
To create an Internet Gateway and associate it with an EC2 instance using AWS CloudFormation, you can follow these steps:
Step 1: Create a CloudFormation template
Create a new YAML or JSON file with a
.yamlor.jsonextension (e.g.,template.yaml), and add the following contents:AWSTemplateFormatVersion: "2010-09-09" Resources: MyVPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 # Replace with your desired VPC CIDR block MyInternetGateway: Type: AWS::EC2::InternetGateway MyVPCGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: !Ref MyVPC InternetGatewayId: !Ref MyInternetGateway MySubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.0.0/24 # Replace with your desired subnet CIDR block AvailabilityZone: us-west-2a # Replace with your desired availability zone MyRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref MyVPC MyDefaultRoute: Type: AWS::EC2::Route DependsOn: MyVPCGatewayAttachment Properties: RouteTableId: !Ref MyRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref MyInternetGateway MyEC2Instance: Type: AWS::EC2::Instance Properties: ImageId: ami-0123456789abcdef0 # Replace with your desired AMI ID InstanceType: t2.micro # Replace with your desired instance type SubnetId: !Ref MySubnetMake sure to replace the placeholder values (
CidrBlock,AvailabilityZone,ImageId, etc.) with your desired values.Create Internet Gateway & Assign to EC2 in Terraform
To create an Internet gateway and assign it to an EC2 instance using Terraform, you can follow these steps:
Step 1: Set up your Terraform environment
- Install Terraform: Download and install Terraform from the official website (https://www.terraform.io/downloads.html) based on your operating system.
- Configure AWS credentials: Set up your AWS access key and secret access key as environment variables or use an AWS profile configured on your system.
Step 2: Create a Terraform configuration file
Create a new file with a
.tfextension (e.g.,main.tf) and add the following contents:How to configure Terraform to use Local Providers from Nexus
If your organization has blocked
registry.terraform.ioand has instead downloaded the provider binaries to Nexus, then you can do the following to still make your Terraform execute correctly.Step 1 - Download the Required Providers
In our example, we need the following providers:
- AWS
- Archive
These commands below are running directly from the pipeline that executes the Terraform:
# Download the providers from the Nexus repository - curl -u ${Nexus_REPO_USER}:${Nexus_REPO_PASS} -o terraform-provider-aws4.65.0linuxamd64.zip https://nexus.example.com/repository/some-local-mirror/registry.terraform.io/hashicorp/aws/terraform-provider-aws_4.65.0_linux_amd64.zip - curl -u ${Nexus_REPO_USER}:${Nexus_REPO_PASS} -o terraform-provider-archive_2.3.0_linux_amd64.zip https://nexus.example.com/repository/local-mirror/registry.terraform.io/hashicorp/archive/terraform-provider-archive_2.3.0_linux_amd64.zip # Make a local directory to store these providers - mkdir -p $HOME/.terraform.d/plugins/registry.terraform.io/hashicorp/aws/ - mkdir -p $HOME/.terraform.d/plugins/registry.terraform.io/hashicorp/archive/ # Move the downloaded zip files to these directories - mv terraform-provider-aws_4.65.0_linux_amd64.zip $HOME/.terraform.d/plugins/registry.terraform.io/hashicorp/aws/ - mv terraform-provider-archive_2.3.0_linux_amd64.zip $HOME/.terraform.d/plugins/registry.terraform.io/hashicorp/archive/ # Give the permissions (not always required) - chmod 777 -R $HOME/.terraform.d/plugins/Step 2 - Run the Terraform code with a Plugin Directory
The following code continues the pipeline from above where we left off:
[Solved] Fargate Can't Read Secrets from Secret Manager
If you’re running a Fargate task and it’s not able to read secrets from AWS Secret Manager, there are a few things you can check:
-
Verify that the Fargate task has the correct IAM permissions to access the secret. You need to grant the task the secretsmanager:GetSecretValue permission for the specific secret that it needs to access. You can do this by adding the necessary permission to the task execution role, or by creating a separate IAM role and attaching it to the task.
Golang vs Python: The Ultimate Battle in DevOps
In the world of DevOps, two programming languages are often pitted against each other: Golang and Python. Both languages have their own strengths and weaknesses, and choosing the right one for your DevOps needs can be a tough decision. In this blog post, we will take a closer look at Golang and Python, and compare their capabilities in the DevOps landscape.
Golang
Golang is a language that has gained immense popularity in recent years, especially in the field of DevOps. One of the key reasons behind its success is its simplicity, which makes it easier to learn and use. The language was designed to be fast, efficient, and reliable, with a focus on minimizing dependencies and maximizing performance. Golang’s popularity in the DevOps landscape is due to its ability to build high-performance, networked services and web applications with ease.
Why DevOps and Python are Amazing Together
In today’s software development world, DevOps and Python are two of the most essential elements for building high-quality software. DevOps has transformed the way software is developed, tested, and deployed, while Python has become a popular programming language for automation and scripting.
The combination of DevOps and Python is particularly powerful because it provides developers with the necessary tools to automate, test, and deploy software efficiently. Here are some of the reasons why DevOps and Python are such a great match:
Python & DevOps: Transforming Software Development
Introduction:
In recent years, the software industry has witnessed a remarkable shift towards DevOps and Python. DevOps has become a vital part of software development, and Python is now one of the most popular programming languages used by developers. In this blog post, we’ll explore why DevOps and Python are so amazing together, and how they can help revolutionize software development.
DevOps: A Game Changer in Software Development
DevOps is a software development methodology that aims to bridge the gap between development and operations teams. It involves collaboration, automation, and continuous delivery of software. DevOps practices have gained popularity in recent years due to their ability to improve the efficiency, quality, and speed of software development.
DevOps: The Ultimate Secret Weapon for High-Tech Success
DevOps has been a buzzword in the tech industry for some time now. While some companies have embraced the DevOps methodology, others are still lagging behind. If you’re wondering what all the hype is about and why DevOps is so amazing, then read on! Here are ten reasons why DevOps is the ultimate secret weapon for high-tech success.
1. Improved Collaboration and Communication
Improved collaboration and communication are critical benefits of DevOps that can have a significant impact on the success of software development projects. In traditional software development approaches, different teams often work in silos, with little communication or coordination between them. This can lead to delays, misunderstandings, and errors.
How to Deploy a Java Application in AWS ECS using Terraform
In order to deploy a Java application into AWS ECS (Elastic Container Service) using Terraform, we need to consider a few different things.
Step 1 - Java Application
Create a file called
HelloWorld.javaand add the following code to it:public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }We now need to build our class as follows:
javac HelloWorld.javaOnce this is done, we can package our application into a
jarfile:How to set the Hostname on a Linux server with Terraform
If you need to set the hostname on a linux server, and you are using Terraform, then you can do the following:
Include the
provisionerblock and set it toremote-exec:provisioner "remote-exec" { inline = ["sudo hostnamectl set-hostname friendly.example.com"] }Go Sync Package Mastery: Synchronization Primitives
Master Go’s synchronization primitives including mutexes.
#Go’s sync package contains the building blocks for safe concurrent programming. When multiple goroutines access shared data, you need synchronization to prevent race conditions and data corruption.
The sync package provides several key primitives:
- Mutex: Mutual exclusion locks for protecting shared resources
- RWMutex: Reader-writer locks for read-heavy workloads
- WaitGroup: Waiting for a collection of goroutines to finish
- Once: Ensuring a function runs exactly once
- Cond: Condition variables for complex coordination
- Pool: Object pools for reducing garbage collection pressure
When to Use Sync Primitives
Go’s philosophy is “Don’t communicate by sharing memory; share memory by communicating.” Channels are often the right choice for goroutine coordination. However, sync primitives are essential when:
What are the different types of AWS API Gateway Protocols?
Amazon API Gateway supports various protocols for exposing APIs, including:
1. RESTful API
This is the most common and widely used protocol for web APIs. Amazon API Gateway allows you to create and manage RESTful APIs, where you define API resources, methods (such as GET, POST, PUT, DELETE, etc.), and HTTP request and response mappings using API Gateway’s REST API model.
Primary use-cases include
- Building traditional web APIs with standard HTTP methods (GET, POST, PUT, DELETE, etc.) and resource-based URLs.
- Exposing APIs for legacy systems or third-party integrations that follow RESTful principles.
- Building APIs that are consumed by a wide range of clients, such as web browsers, mobile apps, and IoT devices.
2. WebSocket API
WebSocket is a protocol that enables bidirectional communication between web clients and servers over a single, long-lived connection. With Amazon API Gateway’s WebSocket API, you can create real-time, interactive APIs that support two-way communication between clients and servers, making it suitable for use cases like chat applications, gaming, and notifications.
IaC: A Guide to Modern Software Development
In the world of software development, efficiency, scalability, and repeatability are paramount. Enter Infrastructure as Code (IaC), a revolutionary approach to managing infrastructure in the cloud era. In this definitive guide, we will dive deep into the concept of IaC, explore its benefits, best practices, and how it is reshaping the way modern software is built and deployed. Join us on this journey as we unlock the power of IaC and uncover its secrets to successful software development.
DevOps and Microservices: How They Complement Each Other
In today’s fast-paced world of software development, DevOps and microservices have emerged as two powerful methodologies that enable organizations to build and deploy applications with speed, agility, and reliability. While DevOps and microservices are distinct concepts, they often go hand in hand, complementing each other to create a seamless and efficient software development and deployment process. In this blog post, we will explore how DevOps and microservices fit together and how organizations can leverage them to accelerate their software delivery pipelines and achieve business success.
IaC Unlock: Maximize Potential with Ansible
In today’s fast-paced world of software development and IT operations, the need for efficient and scalable infrastructure management has become more critical than ever. Enter Infrastructure as Code (IaC), a game-changing approach that allows organizations to automate their infrastructure provisioning and management, making it more agile, scalable, and reliable. And when it comes to IaC, Ansible stands out as a top choice for many IT teams due to its simplicity, versatility, and robustness. In this blog post, we will explore the power of IaC with Ansible and how it can revolutionize your IT operations.
GitOps: Managing Infrastructure as Code with Git
Introduction
In today’s fast-paced world of software development and operations, managing infrastructure efficiently and securely is crucial for organizations to deliver reliable and scalable applications. Traditional methods of managing infrastructure can be time-consuming, error-prone, and lack visibility, making it challenging to keep up with the demands of modern software development practices. However, with the emergence of GitOps, organizations now have a powerful and efficient way to manage infrastructure as code, leveraging the familiar and widely adopted Git version control system. In this blog post, we will explore the concept of GitOps, its benefits, and how organizations can implement GitOps practices to streamline their infrastructure management while adhering to popular SEO tactics.
DevOps Synergy: Boosting Cybersecurity
As organizations increasingly rely on technology to power their operations, the need for robust cybersecurity measures becomes more critical than ever. Cyber threats are constantly evolving, and traditional security approaches are no longer sufficient to protect against sophisticated attacks. This is where DevOps, a collaborative approach to software development and operations, can play a significant role in enhancing cybersecurity defenses. In this blog post, we will explore the powerful synergy between DevOps and cybersecurity, and how organizations can leverage this approach to strengthen their security posture.
The Role of DevOps in Blockchain
Blockchain technology is gaining traction across various industries for its ability to provide transparency, security, and immutability. However, implementing blockchain solutions requires a robust and efficient software development process, which is where DevOps comes in. In this blog post, we will explore the role of DevOps in blockchain development and how it can help organizations deploy blockchain solutions seamlessly.
What is DevOps?
DevOps is a software development methodology that emphasizes collaboration, automation, and continuous delivery to ensure faster and more reliable software delivery. The approach combines the practices of agile software development, continuous integration, and continuous delivery/deployment. DevOps focuses on breaking down the silos between development and operations teams, enabling seamless collaboration and communication.
The Importance of Testing in DevOps: Strategies and Tools
Introduction
In today’s fast-paced digital world, software development has become an essential part of business operations. With the adoption of DevOps practices, organizations can build and deploy software applications more efficiently and effectively. However, with faster release cycles, it becomes increasingly important to ensure that software is thoroughly tested before release. In this blog post, we will explore the importance of testing in DevOps, strategies for successful testing, and tools that can help streamline the testing process.
Docker Production Deployment Strategies
Deploy Docker containers to production with security.
Introduction and Setup
My first production Docker deployment was a disaster. I thought running containers in production would be as simple as
docker runwith a few extra flags. Three hours into the deployment, our application was down, the database was corrupted, and I was frantically trying to figure out why containers kept restarting in an endless loop.That painful experience taught me that production Docker deployments are fundamentally different from development. The stakes are higher, the complexity is greater, and the margin for error is essentially zero.
DevOps Impact on Customer Experience
DevOps has revolutionized the way organizations develop, deploy, and manage software applications. It has brought about a cultural shift that emphasizes collaboration, automation, and continuous improvement. While DevOps has many benefits for software development teams, it also has a significant impact on customer experience and business success.
In this blog post, we will explore how DevOps can improve customer experience and lead to business success.
Key Points
Faster Time-to-Market
One of the key benefits of DevOps is that it enables teams to release software faster and more frequently. This means that organizations can quickly respond to changing market demands and customer needs. By delivering new features and updates in a timely manner, organizations can improve customer satisfaction and increase their competitive edge.
Building a DevOps Culture from the Ground Up
DevOps has become a crucial aspect of software development, enabling teams to deliver software more efficiently and with higher quality. However, implementing DevOps is not just a matter of adopting tools and processes; it requires a cultural shift in the organization. In this blog post, we will explore the steps organizations can take to build a DevOps culture from the ground up.
1. Define the vision and goals
The first step in building a DevOps culture is to establish a clear vision and goals. This includes defining the purpose of DevOps and how it aligns with the organization’s overall strategy. This vision should be communicated clearly to all stakeholders to ensure that everyone is working towards the same goal.
Scaling DevOps for Enterprise Organizations
Introduction
DevOps has become a popular approach for software development in recent years, enabling teams to collaborate more effectively, increase efficiency, and deliver high-quality software faster. However, scaling DevOps for enterprise organizations can be challenging due to the size and complexity of their operations. In this blog post, we will explore the key considerations for scaling DevOps in an enterprise context and provide practical tips for success.
1. Establish a Clear Vision and Strategy
Before scaling DevOps, it’s crucial to establish a clear vision and strategy that aligns with the organization’s business objectives. This should include defining key performance indicators (KPIs) to measure success and outlining the roles and responsibilities of different teams. The strategy should also incorporate feedback loops to ensure continuous improvement and flexibility to adapt to changing business needs.
The Benefits of Infrastructure as Code in DevOps
Introduction
The increasing complexity of software systems requires a flexible, scalable, and reliable infrastructure. This is where infrastructure as code (IaC) comes in, providing a way to automate the management of infrastructure through code. In DevOps, IaC is a critical component that helps teams achieve continuous delivery and deployment, reduce errors, improve collaboration and communication, and ensure consistency and repeatability. In this blog post, we will explore the benefits of infrastructure as code in DevOps.
DevOps for Legacy Systems: Challenges and Solutions
As organizations continue to evolve and embrace digital transformation, they often encounter legacy systems that are critical to their business operations. These systems may be outdated and require modernization, but they still need to be maintained and supported in the meantime. This is where DevOps for legacy systems comes in, offering new opportunities for agility, innovation, and efficiency. In this blog post, we will explore the challenges and solutions for implementing DevOps practices for legacy systems.
DevOps Risk Management: Security & Compliance
DevOps has transformed software development, enabling teams to build, test, and deploy applications faster and more efficiently. However, the speed and agility of DevOps also bring new risks, particularly in the areas of security and compliance. To mitigate these risks, DevOps teams need to adopt strategies that incorporate security and compliance into the development process from the start. In this blog post, we will discuss some of the key strategies for managing risk in DevOps.
Why DevOps is Critical for Digital Transformation
Digital transformation is the process of adopting and implementing digital technologies to improve business operations, increase efficiency, and enhance customer experience. The adoption of digital technologies has become essential for businesses to remain competitive in today’s fast-paced environment. However, implementing digital transformation is not just about technology, it requires a significant cultural shift in the organization. One of the key elements of digital transformation is the implementation of DevOps. In this blog post, we will explore why DevOps is critical for digital transformation.
The Role of Microservices in DevOps
In recent years, microservices have become a popular architectural style for building software applications. Microservices are small, independent services that work together to form a larger application. Each microservice is responsible for a specific task, and they communicate with each other through well-defined APIs. This approach offers many benefits, including scalability, resilience, and flexibility. In this blog post, we’ll explore the role of microservices in DevOps and how they contribute to a successful software development process.
Docker Image Management and Optimization
Learn advanced Docker image creation.
Introduction and Setup
Docker images are deceptively simple. You write a Dockerfile, run
docker build, and you have a container image. But there’s a big difference between images that work and images that work well in production. A poorly optimized image can turn a 30-second deployment into a 20-minute ordeal, making hotfixes impossible and frustrating your entire team.Building efficient Docker images requires understanding layers, caching strategies, and the subtle art of Dockerfile optimization. The techniques in this guide will help you create images that are fast to build, quick to deploy, and secure by default.
Achieving Continuous Delivery with DevOps and Automation
Continuous delivery is a DevOps practice that aims to automate the entire software delivery process, from code commit to production deployment. With continuous delivery, teams can deliver software faster and with greater reliability. By automating many of the manual steps involved in software delivery, teams can reduce the risk of errors and increase the speed of deployment.
To achieve continuous delivery, DevOps teams must prioritize automation. Here are some best practices for achieving continuous delivery with DevOps and automation:
The Importance of Collaboration in DevOps Culture
Collaboration is a key aspect of DevOps culture, and it plays a crucial role in driving success and delivering value to customers. In today’s fast-paced business environment, DevOps teams need to work together seamlessly to ensure that applications are developed and deployed quickly and efficiently, while maintaining high quality and security standards. In this blog post, we will discuss the importance of collaboration in DevOps culture and how it can lead to better outcomes for organizations.
Cloud-Native: Key to DevOps Success
In recent years, cloud-native architecture has become a buzzword in the world of DevOps. But what exactly does it mean, and why is it so important for DevOps success? In this blog post, we’ll explore the concept of cloud-native architecture and why it’s essential for DevOps teams to embrace it.
What is Cloud-Native Architecture?
Cloud-native architecture is an approach to building and running applications that takes advantage of the scalability and flexibility of cloud computing. It’s built around the idea of containerization, which means that applications are broken down into smaller, more manageable components that can be easily deployed and scaled as needed.
10 Best Practices for Continuous Integration in DevOps
Continuous Integration (CI) is an essential part of modern software development and is integral to the DevOps methodology. CI ensures that every code change made by developers is integrated and tested with the existing codebase, allowing teams to catch and fix issues early in the development cycle. In this blog post, we’ll explore the best practices for implementing Continuous Integration in DevOps.
1. Automate the build process
Automating the build process in CI involves using tools and scripts to build, package, and deploy software artifacts. The process should be designed to be repeatable and reliable so that the same results can be achieved consistently. Automating the build process not only reduces the risk of human error but also increases the speed and efficiency of the development process.
DevOps vs. Agile: What's the Difference and Why it Matters
Introduction
In the world of software development, there are two methodologies that are often mentioned: Agile and DevOps. While they share some similarities, they are distinct and have different goals. In this blog post, we’ll explore the differences between Agile and DevOps, why they matter, and how they can work together.
What is Agile?
Agile is a software development methodology that emphasizes collaboration, flexibility, and responsiveness. It was first introduced in 2001 with the publication of the Agile Manifesto, which outlined a set of guiding principles for software development. The Agile approach values working software over comprehensive documentation, customer collaboration over contract negotiation, and responding to change over following a plan.
The Future of DevOps: Emerging Trends and Technologies
In recent years, DevOps has emerged as a key practice for modern software development, helping organizations to achieve faster delivery of high-quality applications. However, as the technology landscape continues to evolve, DevOps itself is undergoing significant changes to keep pace with emerging trends and technologies. In this blog post, we will explore the future of DevOps and the emerging trends and technologies that are shaping its evolution.
Serverless computing
Serverless computing is an approach to cloud computing that allows developers to write and run code without having to manage the underlying infrastructure. In a serverless architecture, the cloud provider is responsible for managing the servers, storage, and networking, while the developer can focus solely on writing code to deliver business value.
Building Resilient Microservices with Istio and Envoy
As microservices architecture continues to grow in popularity, it’s becoming increasingly important to ensure that these distributed systems are reliable and resilient. Istio and Envoy are two tools that have emerged to help with this challenge. In this blog post, we’ll explore how Istio and Envoy can be used to build resilient microservices.
Introduction to Istio and Envoy
Istio is an open-source service mesh that provides a unified way to connect, manage, and secure microservices. Envoy is a high-performance proxy that can be used to manage and secure service-to-service communication. Together, these tools provide a powerful platform for building resilient microservices.
The Role of DevSecOps in Modern Software Development
As the world becomes increasingly digital, software development has become a critical aspect of business success. However, the rise in cybersecurity threats has made it imperative to ensure that software is developed securely. This is where DevSecOps comes in – it is the integration of security practices into the DevOps process, allowing for more secure and reliable software development. In this blog post, we will discuss the role of DevSecOps in modern software development.
5 Key Metrics to Measure DevOps Success
As DevOps continues to gain popularity and adoption, it is important for organizations to measure the success of their DevOps initiatives. While DevOps is about culture and collaboration, it is also about delivering value to customers quickly and reliably. In this blog post, we will discuss five key metrics that organizations can use to measure the success of their DevOps initiatives.
1. Lead Time for Changes
Lead time for changes is the amount of time it takes for a change to be implemented, from the moment it is requested to the moment it is deployed. This metric measures how quickly an organization can deliver new features or fix issues. A shorter lead time for changes means that an organization can respond to market demands more quickly, reducing time to market and increasing customer satisfaction.
The Importance of Infrastructure as Code in DevOps
Infrastructure as Code (IaC) is a methodology that involves managing and provisioning infrastructure through code rather than manually configuring hardware and software components. This approach is essential in DevOps because it enables teams to manage infrastructure at scale, improve collaboration, and reduce errors. In this blog post, we will explore the importance of IaC in DevOps and why it is critical for modern software development.
1. Consistency and Reproducibility
Manual infrastructure configuration is prone to errors and can be challenging to reproduce consistently. With IaC, teams can define infrastructure configurations in code and version control systems, ensuring that infrastructure is consistent across environments. This approach ensures that the infrastructure is reproducible, which reduces errors and saves time.
Docker Security and Performance Optimization
Implement Docker security best practices.
Introduction and Setup
Docker Security and Optimization: Introduction and Setup
Docker security and performance optimization are critical for production deployments. This guide covers comprehensive security hardening, performance tuning, and operational best practices for containerized environments.
Docker Security Fundamentals
Security Model Overview
┌─────────────────────────────────────────────────────────┐ │ Host Operating System │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Kernel │ │ Namespaces │ │ cgroups │ │ │ │ Capabilities│ │ │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ SELinux/ │ │ AppArmor │ │ seccomp │ │ │ │ AppArmor │ │ │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────┤ │ Docker Engine │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Container 1 │ │ Container 2 │ │ Container 3 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────────────────────────────────────────────────┘Basic Security Commands
# Run container with security options docker run --security-opt no-new-privileges:true \ --cap-drop ALL \ --cap-add NET_BIND_SERVICE \ --read-only \ --tmpfs /tmp:rw,noexec,nosuid,size=100m \ nginx # Run as non-root user docker run --user 1000:1000 \ -v /etc/passwd:/etc/passwd:ro \ -v /etc/group:/etc/group:ro \ alpine id # Limit resources docker run --memory=512m \ --cpus="1.5" \ --pids-limit=100 \ --ulimit nofile=1024:1024 \ myapp # Network security docker run --network none alpine docker run --network custom-network \ --ip 172.20.0.10 \ myappContainer Hardening Basics
Secure Dockerfile Practices
# Use specific versions, not latest FROM node:16.17.0-alpine3.16 # Create non-root user early RUN addgroup -g 1001 -S nodejs && \ adduser -S nextjs -u 1001 -G nodejs # Set working directory WORKDIR /app # Copy package files first for better caching COPY package*.json ./ # Install dependencies as root, then switch RUN npm ci --only=production && \ npm cache clean --force && \ chown -R nextjs:nodejs /app # Copy application files COPY --chown=nextjs:nodejs . . # Switch to non-root user USER nextjs # Remove unnecessary packages RUN apk del --purge \ && rm -rf /var/cache/apk/* \ && rm -rf /tmp/* # Set secure permissions RUN chmod -R 755 /app && \ chmod 644 /app/package.json # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 # Expose port EXPOSE 3000 # Use exec form for CMD CMD ["node", "server.js"]Runtime Security Configuration
# Comprehensive security flags docker run -d \ --name secure-app \ --user 1000:1000 \ --read-only \ --tmpfs /tmp:rw,noexec,nosuid,size=100m \ --tmpfs /var/run:rw,noexec,nosuid,size=50m \ --cap-drop ALL \ --cap-add CHOWN \ --cap-add SETGID \ --cap-add SETUID \ --security-opt no-new-privileges:true \ --security-opt apparmor:docker-default \ --security-opt seccomp:default \ --memory=512m \ --memory-swap=512m \ --cpu-shares=512 \ --pids-limit=100 \ --ulimit nofile=1024:1024 \ --ulimit nproc=64:64 \ --restart=unless-stopped \ myapp:latestPerformance Optimization Basics
Resource Management
# CPU optimization docker run -d \ --cpus="2.5" \ --cpu-shares=1024 \ --cpuset-cpus="0,1" \ --cpu-quota=50000 \ --cpu-period=100000 \ myapp # Memory optimization docker run -d \ --memory=2g \ --memory-swap=2g \ --memory-reservation=1g \ --oom-kill-disable=false \ --kernel-memory=500m \ myapp # I/O optimization docker run -d \ --device-read-bps /dev/sda:50mb \ --device-write-bps /dev/sda:50mb \ --device-read-iops /dev/sda:1000 \ --device-write-iops /dev/sda:1000 \ myapp # Network optimization docker run -d \ --sysctl net.core.somaxconn=65535 \ --sysctl net.ipv4.tcp_max_syn_backlog=65535 \ --sysctl net.core.rmem_max=134217728 \ --sysctl net.core.wmem_max=134217728 \ myappDocker Daemon Optimization
{ "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" }, "storage-driver": "overlay2", "storage-opts": [ "overlay2.override_kernel_check=true" ], "default-ulimits": { "nofile": { "Name": "nofile", "Hard": 64000, "Soft": 64000 } }, "max-concurrent-downloads": 10, "max-concurrent-uploads": 5, "default-shm-size": "128M", "userland-proxy": false, "experimental": false, "metrics-addr": "127.0.0.1:9323", "live-restore": true }Security Scanning and Assessment
Image Vulnerability Scanning
# Install and use Trivy curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin # Scan image for vulnerabilities trivy image nginx:latest # Scan with specific severity trivy image --severity HIGH,CRITICAL nginx:latest # Scan and output to file trivy image --format json --output results.json nginx:latest # Scan filesystem trivy fs . # Scan with ignore file trivy image --ignorefile .trivyignore nginx:latest.trivyignore example:
How to Build a Successful DevOps Toolchain
DevOps toolchains are essential for streamlining software delivery and ensuring that teams can work efficiently and collaboratively. However, building a successful DevOps toolchain requires careful planning, coordination, and evaluation. In this blog post, we will explore some strategies for building a successful DevOps toolchain that can help teams deliver software faster and more reliably.
1. Define the requirements
The first step in building a successful DevOps toolchain is defining the requirements. Teams should identify the key features and capabilities they need, such as continuous integration, automated testing, deployment automation, and monitoring. They should also consider factors such as integration with existing systems, scalability, and ease of use.
Scaling DevOps: Strategies for Managing Large Teams
DevOps has revolutionized software development and delivery, enabling teams to work collaboratively, automate processes, and deliver software faster and more reliably. However, as organizations grow and teams become larger, managing DevOps at scale becomes more challenging. In this blog post, we will explore some strategies for managing large DevOps teams and ensuring successful software delivery.
1. Embrace modular architecture
Modular architecture is a critical aspect of scaling DevOps. By breaking down applications into smaller, more manageable components, teams can work independently, reducing dependencies and improving agility. This approach also enables teams to adopt different technologies and tools, allowing for experimentation and innovation.
Docker Compose: Multi-Container Orchestration
Master Docker Compose for defining.
Introduction and Setup
Docker Compose Orchestration: Introduction and Setup
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services, networks, and volumes, then create and start all services with a single command.
What is Docker Compose?
Docker Compose solves the complexity of managing multiple containers by providing:
- Declarative Configuration: Define your entire application stack in a single YAML file
- Service Orchestration: Manage dependencies between containers
- Environment Management: Easy switching between development, testing, and production
- Scaling: Scale services up or down with simple commands
- Networking: Automatic network creation and service discovery
Installation and Setup
Installing Docker Compose
Linux:
Why DevOps Culture is Critical for Business Success
The DevOps movement has been gaining momentum in recent years as organizations realize the benefits of breaking down silos between development and operations teams. DevOps is not just a set of tools and practices; it’s a culture that emphasizes collaboration, communication, and continuous improvement. In this blog post, we will explore why DevOps culture is critical for business success.
1. Speed and agility
In today’s fast-paced business environment, organizations need to deliver software quickly and adapt to changing customer demands. DevOps culture emphasizes automation, continuous delivery, and feedback loops, enabling teams to deploy software faster and respond to market changes quickly. By breaking down silos between teams and fostering a culture of collaboration and communication, DevOps enables organizations to deliver software faster while maintaining quality.
The Ultimate Guide to Kubernetes Deployment Strategies
Kubernetes has become a popular choice for container orchestration, providing developers with a powerful platform for deploying, scaling, and managing containerized applications. However, with great power comes great responsibility, and choosing the right deployment strategy is essential for ensuring application availability, scalability, and performance. In this post, we will cover the ultimate guide to Kubernetes deployment strategies, including their benefits, drawbacks, and best practices.
1. Rolling updates
Rolling updates are the most common deployment strategy in Kubernetes, allowing you to update a running application without downtime. In this strategy, Kubernetes replaces old replicas with new ones, gradually rolling out updates while keeping the application running. This approach is useful for applications that require high availability and can handle small disruptions.
10 Best Practices for Container Security in DevOps
Containers have become a critical component of modern software development practices. They provide a lightweight, portable, and scalable way to package and deploy software applications. However, containers also introduce new security challenges, such as vulnerabilities in container images, insecure configurations, and compromised host environments. In this post, we will outline 10 best practices for container security in DevOps to help you mitigate these risks.
1. Use trusted base images
When building container images, it’s essential to use trusted base images from reputable sources. Avoid using unverified images from unknown sources, as they may contain hidden vulnerabilities or malware. Instead, use base images that have been thoroughly tested and validated by the community.
How to Implement CI/CD Pipelines with Jenkins
Continuous Integration and Continuous Deployment (CI/CD) pipelines are critical components of modern software development practices. They enable development teams to deliver high-quality software quickly and reliably by automating the build, test, and deployment process. Jenkins is a popular open-source automation tool that can help you implement CI/CD pipelines easily. In this post, we will guide you through the process of setting up a basic CI/CD pipeline with Jenkins.
Step 1: Install Jenkins
The first step is to install Jenkins on your system. You can download the latest version of Jenkins from the official website and follow the installation instructions. Once you have installed Jenkins, you can access it using the default URL http://localhost:8080.
[Solved] AWS Error: TooManyBuckets - Bucket Limit Exceeded
If you get the following error:
│ Error: creating Amazon S3 (Simple Storage) Bucket (<your-bucket-name): TooManyBuckets: You have attempted to create more buckets than allowed │ status code: 400, request id: 0P1TV2VCEDKGFQNY, host id: gc9di71ONabECoBYkkzc7Lmqs0DOo2DVhV2kqCgNruNO6Okm5K3EXzosdf5MCxP8uI= │
The reason for the problem
There is a soft limit of 100 S3 buckets per AWS account.
Find out more
https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
The solution to the problem
Option 1 - Quick fix
Remove unused S3 buckets.
How to check if a program exists from a Bash/Shell script
You can look to use:
command -v <the_command>There are also 2 other ways, that we will run through a little further down, but for now..
How to use the
commandif a conditionalif ! command -v <the_command> &> /dev/null then echo "<the_command> could not be found" exit fiTo summarize, there are 3 ways you can do this
Option 1 - Using
commandcommand -v foo >/dev/null 2>&1 || { echo >&2 "foo is not installed. Aborting."; exit 1; }Option 2 - Using
typetype foo >/dev/null 2>&1 || { echo >&2 "foo is not installed. Aborting."; exit 1; }Option 3 - Using
hashhash foo 2>/dev/null || { echo >&2 "foo is not installed. Aborting."; exit 1; }The DevOps Culture
DevOps is a software development approach that emphasizes collaboration and communication between development and operations teams. DevOps culture refers to the values, principles, and practices that foster this collaboration and enable teams to work together effectively.
Here are some key elements of DevOps culture:
Collaboration
DevOps culture emphasizes collaboration between development, operations, and other stakeholders involved in the software development process. This collaboration ensures that all team members are working towards the same goal and have a shared understanding of the project.
Teach me Kubernetes - Part 7 - Sidecar Containers
Looking for the entire 7 part guide? Start at the Overview
In Kubernetes, a sidecar container is a secondary container that runs in the same Pod as the primary container. The sidecar container runs alongside the primary container and shares the same network namespace, IPC namespace, and mount namespace.
Here are some key features of sidecar containers in Kubernetes:
Sidecar containers are used to enhance the functionality of the primary container: The sidecar container runs alongside the primary container and provides additional functionality that the primary container needs to function properly. This can include tasks such as logging, monitoring, or proxying traffic to the primary container.
Teach me Kubernetes - Part 6 - Deployments
Looking for the entire 7 part guide? Start at the Overview
In Kubernetes, a Deployment is a higher-level abstraction that manages the deployment and scaling of a set of Pods. Deployments provide a declarative way to manage the desired state of your application, making it easy to roll out updates and scale your application over time.
Here are some key features of Deployments in Kubernetes:
-
Deployments manage the desired state of your application: You can specify the desired state of your application (e.g., how many replicas of a Pod should be running, what image to use, etc.) in a Deployment configuration file. The Deployment controller then ensures that the actual state of your application matches the desired state.
Teach me Kubernetes - Part 5 - Services
Looking for the entire 7 part guide? Start at the Overview
In Kubernetes, a Service is an abstraction that provides a stable, IP address and DNS name for a set of Pods. Services allow you to decouple the logical representation of your application from the underlying infrastructure, making it easier to manage and scale your application over time.
Here are some key features of Services in Kubernetes:
-
Services provide a stable IP address and DNS name: A Service is assigned a static IP address and DNS name that remains the same even if the underlying Pods are recreated or rescheduled. This allows other components of your application to reliably connect to the Service, without having to know the details of the underlying Pod IP addresses.
Teach me Kubernetes - Part 4 - Replication Controllers
Looking for the entire 7 part guide? Start at the Overview
In Kubernetes, a ReplicationController (also known as a “ReplicaSet” in newer versions of Kubernetes) is a controller that ensures that a specified number of replicas of a Pod are running at any given time.
The ReplicationController is responsible for monitoring the state of the Pods it manages and taking corrective action if the desired state does not match the actual state. For example, if a Pod fails or is terminated, the ReplicationController will create a new Pod to replace it.
Teach me Kubernetes - Part 3 - Pods
Looking for the entire 7 part guide? Start at the Overview
In Kubernetes, a Pod is the smallest and simplest unit in the cluster. A Pod represents a single instance of a running process in a container, and it encapsulates one or more container images, storage resources, and network configurations. Pods are used to run and manage containerized applications in Kubernetes, and they provide a mechanism for managing and scaling containers.
Docker Networking and Storage Solutions
Master Docker networking modes.
Introduction and Setup
Docker Networking and Storage: Introduction and Setup
Docker networking and storage are fundamental concepts for building scalable, production-ready containerized applications. This guide covers everything from basic concepts to advanced patterns for managing container connectivity and data persistence.
Docker Networking Fundamentals
Network Types Overview
Docker provides several network drivers:
┌─────────────────────────────────────────────────────────┐ │ Docker Host │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Bridge │ │ Host │ │ None │ │ │ │ Network │ │ Network │ │ Network │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Overlay │ │ Macvlan │ │ Custom │ │ │ │ Network │ │ Network │ │ Network │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────────────────────────────────────────────────┘Basic Network Commands
# List networks docker network ls # Inspect network docker network inspect bridge # Create custom network docker network create mynetwork # Create network with specific driver docker network create --driver bridge mybridge # Create network with custom subnet docker network create --subnet=172.20.0.0/16 mysubnet # Connect container to network docker network connect mynetwork mycontainer # Disconnect container from network docker network disconnect mynetwork mycontainer # Remove network docker network rm mynetworkBridge Networks
Default bridge network:
Teach me Kubernetes - Part 2 - Nodes
Looking for the entire 7 part guide? Start at the Overview
In Kubernetes, a Node is a worker machine that runs containerized applications. Nodes are responsible for running Pods, which are the smallest deployable units in Kubernetes.
Nodes in a Kubernetes cluster can be physical or virtual machines, and they typically have multiple CPUs and large amounts of memory and storage. Each Node runs a container runtime, such as Docker or containerd, which is responsible for managing the containers that run on the Node.
Teach me Kubernetes - Part 1 - Overview
Kubernetes is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. With Kubernetes, you can manage containerized applications across multiple hosts, scale them up or down as needed, and even roll out updates without downtime.
Here are some key concepts you need to understand to get started with Kubernetes:
- Nodes: A node is a physical or virtual machine that runs your containerized applications. It can be a virtual machine running in a cloud provider or a physical server in your data center.
- Pods: A pod is the smallest deployable unit in Kubernetes. It’s a logical host for one or more containers, and it runs on a node. A pod can contain one or more containers that share the same network namespace, and can communicate with each other using local IP addresses.
- Replication Controllers: A replication controller ensures that a specified number of replicas of a pod are running at all times. If a pod goes down, the replication controller creates a new one to replace it.
- Services: A service is an abstraction layer that provides a stable IP address and DNS name for a set of pods. It acts as a load balancer, routing traffic to the appropriate pod based on a set of rules.
- Deployments: A deployment manages the rollout and updates of a set of pods. It’s a higher-level concept that allows you to declaratively manage the desired state of your application.
To get started with Kubernetes, you’ll need to install a Kubernetes cluster on your local machine or on a cloud provider. You can then use the Kubernetes command-line interface (kubectl) to create and manage resources in your cluster.
How to Create a Simple Chatbot in Python
This is a simple chatbot in Python using the NLTK library.
See the below example Python code:
# Import necessary libraries from nltk.chat.util import Chat, reflections # Define your chatbot's responses responses = { "hello": "Hello, how can I assist you?", "hi": "Hi there! How can I help you today?", "how are you": "I'm doing well, thank you for asking.", "what can you do": "I can help you with tasks such as finding information, setting reminders, and more!", "bye": "Goodbye, have a nice day!", } # Create a Chat instance with your responses chatbot = Chat(responses, reflections) # Start chatting! chatbot.converse()In this example, we’ve defined a dictionary of responses for our chatbot to use. The keys of the dictionary are the inputs that the user might enter, and the values are the chatbot’s responses. We then create a Chat instance with these responses and the reflections dictionary, which helps the chatbot handle variations of user input (such as changing “you are” to “I am” in responses).
Create Transit Gateway with Attachments in Terraform
The following example Terraform code snippet creates a Transit Gateway with VPC and VPN attachments:
provider "aws" { region = "us-west-2" } # Create a transit gateway resource "aws_ec2_transit_gateway" "example" { description = "Example transit gateway" } # Create a VPC attachment resource "aws_ec2_transit_gateway_vpc_attachment" "example_vpc_attachment" { subnet_ids = ["subnet-abc123", "subnet-def456"] # IDs of the subnets in the VPC to attach transit_gateway_id = aws_ec2_transit_gateway.example.id vpc_id = "vpc-xyz789" # ID of the VPC to attach } # Create a VPN attachment resource "aws_ec2_transit_gateway_vpn_attachment" "example_vpn_attachment" { transit_gateway_id = aws_ec2_transit_gateway.example.id vpn_connection_id = "vpn-123456" # ID of the VPN connection to attach }In this example, we’re using the aws_ec2_transit_gateway resource type to create a transit gateway in the us-west-2 region. We’re specifying a description parameter to provide a description for the transit gateway.
Docker and Kubernetes Integration
Seamlessly integrate Docker containers with Kubernetes for scalable.
Understanding the Foundation
Understanding Docker and Kubernetes Integration
When I first started working with containers, I thought Docker and Kubernetes were competing technologies. That couldn’t be further from the truth. They’re actually perfect partners in the container ecosystem, each handling different aspects of the containerization journey.
Think of Docker as your master craftsman - it builds, packages, and runs individual containers with precision. Kubernetes, on the other hand, is like an orchestra conductor, coordinating hundreds or thousands of these containers across multiple machines to create a harmonious, scalable application.
How to Create an AWS EC2 Instance in Terraform
The following Terraform code snippet creates an EC2 instance for you.
provider "aws" { region = "us-west-2" } resource "aws_instance" "example" { ami = "ami-0c94855ba95c71c99" # Amazon Linux 2 AMI instance_type = "t2.micro" key_name = "example-keypair" tags = { Name = "example-instance" } }In this example, we’re using the aws_instance resource type to create an EC2 instance in the us-west-2 region. We’re using the ami parameter to specify the Amazon Linux 2 AMI ID, and the instance_type parameter to specify a t2.micro instance type. We’re also specifying a key pair to use for SSH access with the key_name parameter.
A Primer on Terraform Concepts
Terraform is an open-source tool for building, changing, and versioning infrastructure safely and efficiently. It allows you to describe your infrastructure as code and manage it in a version-controlled way, just like you would with application code.
Here are the basic steps of how Terraform works:
-
Write your infrastructure code: You write infrastructure code in the Terraform configuration language (HCL) to describe the resources you want to create. You can define resources like servers, load balancers, databases, and more, as well as their configurations and relationships.
How to Learn Recursion by Example in Python
Here’s an example code in Python that demonstrates recursion:
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(5)) # Output: 120This code defines a function factorial that calculates the factorial of a given number n. The factorial of a number is the product of all positive integers up to and including that number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
Understanding Site Reliability Engineering (SRE)
Site Reliability Engineering (SRE) can also help organizations to be more proactive in identifying and addressing potential issues before they become major problems. By monitoring system performance and using data-driven insights, SRE teams can detect and respond to issues more quickly, reducing the impact on customers and the business. This can help to increase uptime and reduce the cost of downtime, which can have a direct impact on revenue and profitability.
What is DevOps?
DevOps is a term that combines “development” and “operations.” It is a methodology that aims to bridge the gap between the software development and IT operations teams. DevOps is a set of practices that focuses on automating the software development process, reducing the time between writing code and deploying it to production, and ensuring a high level of quality in the delivered software.
Introduction to DevOps
DevOps is a set of practices that combines software development and IT operations. The goal of DevOps is to shorten the system’s development cycle and provide more reliable software releases. It is a methodology that aims to bridge the gap between the software development and IT operations teams. DevOps is a culture that emphasizes communication and collaboration between teams.
How to Create a Password Generator in Golang
Introduction
In today’s digital age, password security is more important than ever before. Hackers can easily guess weak passwords, leading to identity theft and other cybersecurity breaches. To ensure our online safety, we need to use strong and secure passwords that are difficult to guess. A good password generator can help us create random and strong passwords. In this blog post, we’ll discuss how to create a password generator in Golang.
How does Disaster Recovery work in the Cloud?
Disaster Recovery (DR) in the cloud refers to the process of recovering IT infrastructure and data in the event of a disaster, such as a natural disaster or a cyber attack, in a cloud environment. Cloud-based Disaster Recovery (DR) is different from traditional DR because it utilizes cloud services and technologies to protect data and applications and minimize downtime.
Some key elements involved in implementing a Disaster Recovery plan in the cloud covers topics such as the following.
What is DevOps and why is it important?
DevOps is a software development methodology that emphasizes collaboration and communication between software developers and IT operations teams. It is a set of practices that seeks to streamline the software development lifecycle, from planning and coding to testing and deployment, through the use of automation, monitoring, and iterative development processes.
The primary goal of DevOps is to deliver software more quickly, reliably, and efficiently by breaking down silos between development and operations teams and encouraging continuous feedback and improvement. By aligning development and operations teams, DevOps seeks to reduce time-to-market, improve software quality, and enhance overall business agility.
Docker Fundamentals: Containerization Basics
Learn the essential concepts and practical skills needed to containerize applications using Docker, from basic commands to production-ready deployments.
Introduction and Setup
Introduction to Docker and Containerization
Docker revolutionizes application deployment by packaging applications and their dependencies into lightweight, portable containers that run consistently across different environments.
What is Docker?
Docker is a containerization platform that allows you to package applications with all their dependencies into portable containers. Think of containers as lightweight, standalone packages that include everything needed to run an application: code, runtime, system tools, libraries, and settings.
What is the Zen of Python?
The Zen of Python is an Easter Egg that long time Pythoneer (Tim Peters) channeled the guiding principals for the language’s design principals into 20 aphorisms, of which only 19 of them are written down.
How to access this
Zen of PythonEaster EggBy importing
thisinto your Python application, it will immediately print as follows:import thisWhat is the
Zen of Python?Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!Bash: Convert HTML to Markdown Recursively with Pandoc
You can recursively convert all your HTML files to Mardown format in Bash, by using Pandoc.
find . \-name "*.ht*" | while read i; do pandoc -f html -t markdown "$i" -o "${i%.*}.md"; doneHow to Create a Password Generator in C++
You can easily create a password generator in C++ with the following simple method.
How to create the Password Generator in C++
#include <iostream> #include <string> #include <algorithm> #include <random> std::string generate_password(int length = 16) { std::string seed = string("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + string("0123456789") + string("!@#$%^&*()_+=-{}[]\\|:;<>,.?/"); std::string password_string = seed; std::shuffle(password_string.begin(), password_string.end(), std::mt19937{std::random_device{}()}); return password_string.substr(0, length); } int main() { std::cout << generate_password() << std::endl; std::cout << generate_password(28) << std::endl; return 0; }How do you architect Disaster Recovery in AWS?
Disaster recovery (DR) in AWS involves creating a plan and set of procedures to help your organization recover from a catastrophic event, such as a natural disaster, power outage, or cyber attack, that could impact your business operations. AWS provides a range of tools and services to help you architect an effective DR solution in the cloud.
Here are the high-level steps to architect a Disaster Recovery solution in AWS:
What options exist for Infrastructure as Code (IaC)
There are several options for Infrastructure as Code (IaC) tools that can help automate the provisioning and management of infrastructure resources, such as servers, networks, and storage, in a reliable and reproducible way. Here are some of the most popular IaC options:
-
Terraform: An open-source tool by HashiCorp that supports a wide range of infrastructure providers, including AWS, Azure, Google Cloud, and more. Terraform uses a declarative language to describe infrastructure as code and can manage both low-level and high-level resources.
How to learn Java in 1 day
Learning Java in one day is not a realistic goal, as Java is a complex programming language that requires time and practice to master. However, here are some tips to get you started:
-
Start with the basics: Before diving into complex topics, learn the basics of Java, such as variables, data types, control structures, and object-oriented programming principles.
-
Watch tutorials and read documentation: There are many resources available online that can help you learn Java quickly. Watch video tutorials and read documentation to gain a basic understanding of the language.
How to read user input as numbers in Python
In Python 3 onwards, the
inputfunction returns astringtype..intvalueYou can explicitly convert this into an
inttype.val = int(input("Enter a number: "))floatvalueIf you need to accept fractional components, then simply swap this out with a
floattype:val = float(input("Enter a number:"))mapmultiple valuesIf you have multiple integers in a single line, then you can use
mapto extract them into alist:Capitalize First Letter of Each Word in Python
If you have a sentence containing multiple words, and you want each of the words to start with a capital letter, then you can do one of the following:
Option 1 - using
string.capwords()import string string.capwords('this is a test!')Output:
'This Is A Test!'Option 2 - using
title()'this is a test!'.title()Output:
'This Is A Test!'Option 3 - using
join(),split()andlist comprehensions" ".join(w.capitalize() for w in 'this is a test!'.split())Output:
'This Is A Test!'How to Create a Password Generator in Python
You can easily create a password generator in Python with the following simple method.
How to create the Password Generator in Python
import string import random def generate_password(length=16): seed = f"{string.ascii_letters}{string.ascii_lowercase}{string.ascii_uppercase}{string.punctuation}" password_string = [x for x in seed] random.shuffle(password_string) return ''.join(password_string[:length])How to use the Password Generator in Python
With this function, you can either call the
generate_password()function without any arguments, and it will generate a16digit long password, unless you need a longer one, then pass in an integer to specify the lengh of the password you would like. e.g.generate_password(28).Post 3
Occaecat aliqua consequat laborum ut ex aute aliqua culpa quis irure esse magna dolore quis. Proident fugiat labore eu laboris officia Lorem enim. Ipsum occaecat cillum ut tempor id sint aliqua incididunt nisi incididunt reprehenderit. Voluptate ad minim sint est aute aliquip esse occaecat tempor officia qui sunt. Aute ex ipsum id ut in est velit est laborum incididunt. Aliqua qui id do esse sunt eiusmod id deserunt eu nostrud aute sit ipsum. Deserunt esse cillum Lorem non magna adipisicing mollit amet consequat.
GitOps Workflow Implementation
Implement GitOps practices for infrastructure and application deployment using Git as the single source of truth for declarative infrastructure and applications.
Understanding GitOps: Core Principles and Benefits
Before diving into implementation details, let’s establish a clear understanding of GitOps principles and benefits.
Core GitOps Principles
GitOps is built on four fundamental principles:
-
Declarative Configuration: The entire system is described declaratively, typically using YAML or JSON files that specify the desired state.
How to Convert Bytes to a String in Python
If you need to convert bytes to a string in Python, then you can do the following:
your_string = b'This works \xE2\x9C\x85'.decode("utf-8") print(your_string)Output:
This works ✅Note that in the above example, we have converted a
utf-8string to.How to measure the elapsed time in Python
Option 1 - using the
timemoduleimport time start = time.time() print(23*2.3) end = time.time() print(end - start)Output:
52.9 3.600120544433594e-05Option 2 - using the
timeitmodulefrom timeit import default_timer as timer start = timer() print(23*2.3) end = timer() print(end - start)Output:
52.9 6.355400000000039e-05How to Change a MariaDB/MySQL Data Directory to a New Location on Linux
Step 1 — Moving the MariaDB Data Directory
mysql -u root -pselect @@datadir;Output: +-----------------+ | @@datadir | +-----------------+ | /var/lib/mysql/ | +-----------------+ 1 row in set (0.00 sec)exitsudo systemctl stop mariadb sudo systemctl status mariadbOutput: mysql systemd[1]: Stopped MariaDB database server.sudo rsync -av /var/lib/mysql /mnt/my-volume-01sudo mv /var/lib/mysql /var/lib/mysql.bakStep 2 — Pointing to the New Data Location
sudo vi /etc/my.cnf[mysqld] . . . datadir=/mnt/my-volume-01/mysql socket=/mnt/my-volume-01/mysql/mysql.sock . . . [client] port=3306 socket=/mnt/my-volume-01/mysql/mysql.sock !includedir /etc/my.cnf.dStep 3 — Restarting MariaDB
sudo systemctl start mariadb sudo systemctl status mariadbmysql -u root -pselect @@datadir;Output +----------------------------+ | @@datadir | +----------------------------+ | /mnt/my-volume-01/mysql/ | +----------------------------+ 1 row in set (0.01 sec)exitCleanup
sudo rm -Rf /var/lib/mysql.bak[Solved] Docker Daemon Connection Error: Daemon Running?
If you get the following error when trying to run a Docker container:
Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?Then you can resolve it by running the following:
systemctl start dockerIf this doesn’t work because of a
rootuser issue, then you can do the following first:gpasswd -a $USER dockerAdditional issues?
Issue 1
If you have tried the above, and get this error:
[Solved] M1 Docker Image Platform Mismatch with Host (ARM64)
If you get the following error when trying to run a Docker container that was built on an M1 mac:
M1 docker preview and keycloak 'image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)' IssueThe solution
Then you can do simply add the following argument to your
docker buildcommand.--platform linux/amd64Where this goes
docker build --platform linux/amd64 -t your_docker_item .How to get the SHA512 sum of a string using Python
If you need to get the SHA512 sum of a string using Python, then you can do the following.
Step 1
Firstly, we need to use the
hashlibmodule:import hashlibStep 2
Now make sure that the input string is encoded correctly.
your_input = "this is your input string".encode('utf-8')Step 3
Finally use the
sha512function of thehashlibmodule, and get thehexdigest()value from it:hashlib.sha512(your_input).hexdigest()Putting it all together
import hashlib your_input = "this is your input string".encode('utf-8') hashed = hashlib.sha512(your_input).hexdigest() print(hashed) # --> 74cf60b5a22c401454e36193a65e7efeb5a7d72db9e1f786975e7bd2b7bdd12dee83f99e78542d0eca5c9152f09f397d0ac8de68275ca353837b28f938e429f4How to get the SHA256 sum of a string using Python
If you need to get the SHA256 sum of a string using Python, then you can do the following.
Step 1
Firstly, we need to use the
hashlibmodule:import hashlibStep 2
Now make sure that the input string is encoded correctly.
your_input = "this is your input string".encode('utf-8')Step 3
Finally use the
sha256function of thehashlibmodule, and get thehexdigest()value from it:hashlib.sha256(your_input).hexdigest()Putting it all together
import hashlib your_input = "this is your input string".encode('utf-8') hashed = hashlib.sha256(your_input).hexdigest() print(hashed) # --> f7dc376447dcd13fdd6cb2aa20a2327bed1f8a1f3420d52c6fdb55b2b94d9b8eHow to get the MD5 sum of a string using Python
If you need to get the MD5 sum of a string using Python, then you can do the following.
Step 1
Firstly, we need to use the
hashlibmodule:import hashlibStep 2
Now make sure that the input string is encoded correctly.
your_input = "this is your input string".encode('utf-8')Step 3
Finally use the
md5function of thehashlibmodule, and get thehexdigest()value from it:hashlib.md5(your_input).hexdigest()Putting it all together
import hashlib your_input = "this is your input string".encode('utf-8') hashed = hashlib.md5(your_input).hexdigest() print(hashed) # --> af0874120fd6196ea1feeebdb6de0e54[Solved] TypeError: datetime Not JSON Serializable
If you get the following error:
TypeError: Object of type datetime is not JSON serializable..then you can solve it by using this trick:
json.dumps(your_dict, indent=4, sort_keys=True, default=str)Microservices Monitoring and Observability
Build comprehensive monitoring.
Understanding Microservices Observability
The Observability Challenge
Why monitoring microservices is fundamentally different:
Distributed Complexity:
- Multiple independent services with their own lifecycles
- Complex service dependencies and interaction patterns
- Polyglot environments with different languages and frameworks
- Dynamic infrastructure with containers and orchestration
- Asynchronous communication patterns
Traditional Monitoring Limitations:
- Host-centric monitoring insufficient for containerized services
- Siloed monitoring tools create incomplete visibility
- Static dashboards can’t adapt to dynamic environments
- Lack of context across service boundaries
- Difficulty correlating events across distributed systems
Observability Requirements:
How to Return a List of All AWS Lambda Function Names in CLI
If you would like to list all AWS Lambda Function Names in your CLI using the AWS CLI, then you can do this:
Get a List of all Lambda Functions
aws lambda list-functionsHowever, note that this will return a potentially large JSON payload back to your CLI. So what if you only want a list of the function names themselves?
You can couple the AWS command above, with the
jqcommand as follows:How much faster is Python code?
The speed of Python code compared to other programming languages depends on a variety of factors, such as the specific task being performed, the libraries and frameworks used, the quality of the code implementation, and the hardware on which the code is executed.
In general, Python is an interpreted language, which means that code is executed line-by-line by an interpreter, rather than being compiled into machine code beforehand. This can make Python code slower than compiled languages like C or C++ for some tasks.
Containerization Best Practices for DevOps
Master containerization strategies.
Container Fundamentals and Docker Basics
Containers transformed how I think about application deployment. After years of wrestling with “it works on my machine” problems, containers finally gave us a way to package applications with their entire runtime environment.
Why Containers Matter
Traditional deployment meant installing applications directly on servers, managing dependencies, and hoping everything worked together. I’ve seen production outages caused by a missing library version or conflicting Python packages. Containers solve this by packaging everything your application needs into a single, portable unit.
Zip & Encode Dict to String & Back in Python
If you have a Python dictionary, and want to encode it as a string and zip it to save space, perhaps for passing a dictionary through as an environment variable or similar, then you can do the following
Zip then Encode / Decode then Unzip Functions
import json, gzip, base64 from io import BytesIO def _zip_then_encode(data: dict) -> str: """Gzip and base64 encode a dictionary""" if type(data) != dict: raise TypeError("data must be a dictionary") compressed = BytesIO() with gzip.GzipFile(fileobj=compressed, mode="w") as f: json_response = json.dumps(data) f.write(json_response.encode("utf-8")) return base64.b64encode(compressed.getvalue()).decode("ascii") def _decode_then_unzip(data) -> dict: res = base64.b64decode(data) res = gzip.decompress(res) res = res.decode("utf-8") res = json.loads(res) return resTo use the
encodeanddecodefunctions, you can do the following:MLOps Best Practices: Operationalizing Machine Learning at Scale
Comprehensive guide to MLOps covering model development.
MLOps Fundamentals
The ML Lifecycle
Understanding the end-to-end machine learning process:
ML Lifecycle Stages:
- Problem definition and scoping
- Data collection and preparation
- Feature engineering and selection
- Model development and training
- Model evaluation and validation
- Model deployment and serving
- Monitoring and maintenance
- Continuous improvement
MLOps vs. Traditional DevOps:
- Data and model versioning (not just code)
- Experiment tracking and reproducibility
- Model-specific testing requirements
- Specialized deployment patterns
- Performance monitoring beyond uptime
- Retraining workflows
MLOps Maturity Levels:
What Categories of Websites are there?
There are many different categories of websites, but here are some of the most common:
-
E-commerce websites: These websites sell products or services online. Examples include Amazon, eBay, and Etsy.
-
News websites: These websites provide up-to-date news and information on a variety of topics. Examples include CNN, BBC, and The New York Times.
-
Blogging websites: These websites are used for personal or business blogs. Examples include WordPress, Blogger, and Medium.
How to Generate a Random Number between 2 numbers in Python
If you need to generate a random number between two (2) numbers in Python, then you can make use of the
randommodule.First, import the module:
import randomThen you can use it like this:
random.randint(0, 255)Another option is to use
randrangeanduniformas follows:from random import randrange, uniform # randrange gives you an integral value irand = randrange(0, 10) # uniform gives you a floating-point value frand = uniform(0, 10)Post 2
Anim eiusmod irure incididunt sint cupidatat. Incididunt irure irure irure nisi ipsum do ut quis fugiat consectetur proident cupidatat incididunt cillum. Dolore voluptate occaecat qui mollit laborum ullamco et. Ipsum laboris officia anim laboris culpa eiusmod ex magna ex cupidatat anim ipsum aute. Mollit aliquip occaecat qui sunt velit ut cupidatat reprehenderit enim sunt laborum. Velit veniam in officia nulla adipisicing ut duis officia.
Exercitation voluptate irure in irure tempor mollit Lorem nostrud ad officia. Velit id fugiat occaecat do tempor. Sit officia Lorem aliquip eu deserunt consectetur. Aute proident deserunt in nulla aliquip dolore ipsum Lorem ut cupidatat consectetur sit sint laborum. Esse cupidatat sit sint sunt tempor exercitation deserunt. Labore dolor duis laborum est do nisi ut veniam dolor et nostrud nostrud.
How to Install AWS SAM CLI on Mac
If you need to install AWS SAM CLI on a Mac, then the easiest option is to use Homebrew with the following commands:
brew tap aws/tap brew install aws-sam-cliNow you can validate the installation as follows:
sam --versionHow to count the amount of rows in MariaDB fast
If you need to find the fastest way to count the number of rows in a massive MariaDB, or MySQL table, then you can do the following instead of performing a
select count()query:show table status like '<TABLE_NAME>'This will provide you with a table of information about the table statistics, including the amount of rows.
How to find the Product of Consecutive Fib Numbers in Python
0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, …This is the Van Eck’s Sequence.
Let’s go through it step by step.
Term 1: The first term is 0. Term 2: Since we haven’t seen 0 before, the second term is 0. Term 3: Since we had seen a 0 before, one step back, the third term is 1 Term 4: Since we haven’t seen a 1 before, the fourth term is 0 Term 5: Since we had seen a 0 before, two steps back, the fifth term is 2. And so on…
How to Solve Van Eck's Sequence in Python
0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, …This is the Van Eck’s Sequence.
Let’s go through it step by step.
Term 1: The first term is 0. Term 2: Since we haven’t seen 0 before, the second term is 0. Term 3: Since we had seen a 0 before, one step back, the third term is 1 Term 4: Since we haven’t seen a 1 before, the fourth term is 0 Term 5: Since we had seen a 0 before, two steps back, the fifth term is 2. And so on…
How to Solve: Help the Bookseller Challenge in Python
A bookseller has lots of books classified in 26 categories labeled A, B, … Z. Each book has a code c of 3, 4, 5 or more characters. The 1st character of a code is a capital letter which defines the book category.
In the bookseller’s stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock.
How to solve AWS MediaPackage PackagingGroup Quota Limit
If you are using AWS Elemental MediaPackage and hit the following error, then you need to either do one of the following:
Error: error waiting for CloudFormation Stack (arn:aws:cloudformation:eu-west-1:800417762774:stack/dev-MediaPackage-Vod-1/511fc7a0-a092-11ed-b853-068baf6ac251) create: failed to create CloudFormation stack, delete requested (DELETE_COMPLETE): ["The following resource(s) failed to create: [PackagingGroup]. Delete requested by user." "Resource handler returned message: \"Limit exceeded for resource of type 'AWS::MediaPackage::PackagingGroup'. Reason: You reached the quota for resource=PackagingGroup. Delete the resources that you don?t need, or request a quota increase. (Service: MediaPackageVod, Status Code: 429, Request ID: bc7a5f31-463e-4ac6-a9a2-438111dd201c)\" (RequestToken: 135f9266-ddcd-1b8d-fdff-00e3837d5dc3, HandlerErrorCode: ServiceLimitExceeded)"]How to Run Cdk Bootstrap
To
bootstrapan AWS CDK environment, you simply need to do the following:npx aws-cdk bootstrap…for each environment that you would like the CD to operate within.
This will deploy all the required prerequisites to the AWS account, such as the:
- An Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments.
- The required resources are defined in an AWS CloudFormation stack, called the bootstrap stack, which is usually named CDKToolkit. Like any AWS CloudFormation stack, it appears in the AWS CloudFormation console once it has been deployed.
How to Get Account Number from AWS Lambda
If you need to get the current Account Number, or Account ID from within a Lambda execution, then you can access
invoked_function_arnfrom thecontextand return the associated value as follows:aws_account_id = context.invoked_function_arn.split(":")[4]Building Resilient Distributed Systems
Learn fault tolerance patterns.
Understanding Distributed Systems Failures
Failure Modes and Models
Recognizing what can go wrong:
Common Failure Modes:
- Hardware failures
- Network partitions
- Service dependencies failures
- Resource exhaustion
- Data corruption
- Clock skew
- Configuration errors
- Deployment failures
- Cascading failures
- Thundering herd problems
The Fallacies of Distributed Computing:
- The network is reliable
- Latency is zero
- Bandwidth is infinite
- The network is secure
- Topology doesn’t change
- There is one administrator
- Transport cost is zero
- The network is homogeneous
Failure Models:
Summary of the Frequently Used AWS STS API calls
AssumeRole – is useful for allowing existing IAM users to access AWS resources that they don’t already have access to. For example, the user might need access to resources in another AWS account. It is also useful as a means to temporarily gain privileged access—for example, to provide multi-factor authentication (MFA). You must call this API using existing IAM user credentials.
AssumeRoleWithWebIdentity – returns a set of temporary security credentials for federated users who are authenticated through a public identity provider. Examples of public identity providers include Login with Amazon, Facebook, Google, or any OpenID Connect (OIDC)-compatible identity provider.
Understanding Locking and Conditional Writes in AWS DynamoDB
Optimistic locking is a strategy to ensure that the client-side item that you are updating (or deleting) is the same as the item in DynamoDB. Optimistic concurrency depends on checking a value upon save to ensure that it has not changed. If you use this strategy, then your database writes are protected from being overwritten by the writes of others — and vice-versa.
By default, the DynamoDB write operations (
PutItem,UpdateItem,DeleteItem) are unconditional: each of these operations will overwrite an existing item that has the specified primary key.AWS CodeDeploy Deployment Type Options
CodeDeploy provides two (2) deployment type options:
Option 1 – In-place Deployment
In-place deployment: The application on each instance in the deployment group is stopped, the latest application revision is installed, and the new version of the application is started and validated. You can use a load balancer so that each instance is deregistered during its deployment and then restored to service after the deployment is complete. Only deployments that use the EC2/On-Premises compute platform can use in-place deployments. AWS Lambda compute platform deployments cannot use an in-place deployment type.
Defining Amazon ECS Task Placement Strategies
Amazon ECS supports the following task placement strategies:
binpack – Place tasks based on the least available amount of CPU or memory. This minimizes the number of instances in use.
random – Place tasks randomly.
spread – Place tasks evenly based on the specified value. Accepted values are attribute key-value pairs, instanceId, or host.
Post 1
Tempor proident minim aliquip reprehenderit dolor et ad anim Lorem duis sint eiusmod. Labore ut ea duis dolor. Incididunt consectetur proident qui occaecat incididunt do nisi Lorem. Tempor do laborum elit laboris excepteur eiusmod do. Eiusmod nisi excepteur ut amet pariatur adipisicing Lorem.
Occaecat nulla excepteur dolore excepteur duis eiusmod ullamco officia anim in voluptate ea occaecat officia. Cillum sint esse velit ea officia minim fugiat. Elit ea esse id aliquip pariatur cupidatat id duis minim incididunt ea ea. Anim ut duis sunt nisi. Culpa cillum sit voluptate voluptate eiusmod dolor. Enim nisi Lorem ipsum irure est excepteur voluptate eu in enim nisi. Nostrud ipsum Lorem anim sint labore consequat do.
Deployment methods in AWS Elastic Beanstalk
– All at once – Deploy the new version to all instances simultaneously. All instances in your environment are out of service for a short time while the deployment occurs.
– Rolling – Deploy the new version in batches. Each batch is taken out of service during the deployment phase, reducing your environment’s capacity by the number of instances in a batch.
– Rolling with additional batch – Deploy the new version in batches, but first launch a new batch of instances to ensure full capacity during the deployment process.
How to update NTP to sync clock on Linux
If you need to sync the clock on Linux using the central NTP clock service, you can do the following:
sudo service ntp stop sudo ntpd -gq sudo service ntp startThe
-ggflags do the following:- Tell
gflag tells the NTP Daemon to correct the time regardless of the offset - The
qflag tells it to exit immediately after setting the time
Data Partitioning Strategies for Distributed Systems
Master data partitioning techniques including sharding.
Understanding Data Partitioning
Data partitioning (also known as sharding) is the process of breaking a large dataset into smaller, more manageable pieces called partitions or shards. Each partition contains a subset of the data and can be stored on a separate database server or node.
Why Partition Data?
- Scalability: Overcome hardware limitations by distributing data across multiple machines
- Performance: Improve query performance through parallel processing across partitions
- Availability: Enhance system resilience by isolating failures to specific partitions
- Manageability: Make maintenance operations like backups and index rebuilds more efficient
- Data Locality: Store data close to the users or services that access it most frequently
Partitioning vs. Replication
It’s important to distinguish between partitioning and replication:
Distributed Consensus Algorithms: Building Fault-Tolerant Systems
Master the algorithms that enable distributed systems to agree on shared state despite failures and network partitions.
The Consensus Problem
Before diving into specific algorithms, let’s clearly define the consensus problem. In a distributed system with multiple nodes, consensus is the process of agreeing on a single value or state among all non-faulty nodes. A correct consensus algorithm must satisfy the following properties:
- Agreement: All non-faulty nodes decide on the same value.
- Validity: If all nodes propose the same value, then all non-faulty nodes decide on that value.
- Termination: All non-faulty nodes eventually decide on some value.
The challenge is achieving these properties in the presence of:
How to Find IP Address Ranges used by Amazon S3
You can query the
ip-rangesAmazon AWS URL, and parse the results throughjqas follows:Generic S3 IP Ranges
Query:
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.service=="S3")'Response:
{ "ip_prefix": "3.5.140.0/22", "region": "ap-northeast-2", "service": "S3", "network_border_group": "ap-northeast-2" } { "ip_prefix": "52.219.170.0/23", "region": "eu-central-1", "service": "S3", <truncated>Region Specific S3 IP Ranges
Query:
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="eu-west-1") | select(.service=="S3") | .ip_prefix'Response:
18.34.32.0/20 3.5.72.0/23 52.218.0.0/17 3.5.64.0/21 52.92.0.0/17 18.34.240.0/22 3.251.110.208/28 3.251.110.224/28How to Find the nth Reverse Number in Java
The challenge
Reverse Number is a number which is the same when reversed.
For example, the first 20 Reverse Numbers are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101Task
- You need to return the nth reverse number. (Assume that reverse numbers start from 0 as shown in the example.)
Notes
- 1 < n <= 100000000000
The solution in Java
Option 1:
How to Find the Sum of Intervals in Java
The challenge
Write a function called
sumIntervals/sum_intervals()that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.Intervals
Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example:
[1, 5]is an interval from 1 to 5. The length of this interval is 4.How to Find the Stray Number in Python
The challenge
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Examples
[1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3The solution in Python
Option 1:
def stray(arr): for x in arr: if arr.count(x) == 1: return xOption 2:
How to Find the EDID UUID of External Mac Monitors
You can issue the following command on an Apple Mac’s terminal to show the
EDID UUID(unique serial number) of all attached external monitors:ioreg -l | grep EDID[Solved] jsii.errors.JSIIError: docker exited with status 1
If you get the following error while running AWS CDK:
raise JSIIError(resp.error) from JavaScriptError(resp.stack) jsii.errors.JSIIError: docker exited with status 1Then you can resolve it as follows:
How to solve
docker exited with status 1errorMake sure that your local Docker client is running.
Start
dockeron the local machine and CDK will be able to make the Docker connections required.How to Filter a Number in C
The challenge
The number has been mixed up with the text. Your goal is to retrieve the number from the text, can you return the number back to its original state?
Task
Your task is to return a number from a string.
Details
You will be given a string of numbers and letters mixed up, you have to return all the numbers in that string in the order they occur.
How to Take a Ten Minute Walk in C
The challenge
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones — everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. [‘n’, ‘s’, ‘w’, ‘e’]). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don’t want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
How to Count Stats of a String in C
The challenge
You will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows.
Solve("*'&ABCDabcde12345") = [4,5,5,3]. --the order is: uppercase letters, lowercase, numbers and special characters.The solution in C
Option 1:
void count_char_types (const char *string, unsigned counts[4]) { char c; counts[0] = counts[1] = counts[2] = counts[3] = 0; while((c = *string++)) if(c >= 'A' && c <= 'Z') counts[0]++; else if(c >= 'a' && c <= 'z') counts[1]++; else if(c >= '0' && c <= '9') counts[2]++; else counts[3]++; }Option 2:
How to Convert a String to the NATO Phonetic Alphabet in C
The challenge
You’ll have to translate a string to Pilot’s alphabet (NATO phonetic alphabet).
Input:
If, you can read?Output:
India Foxtrot , Yankee Oscar Uniform Charlie Alfa November Romeo Echo Alfa Delta ?Note:
- There are preloaded dictionary you can use, named
NATO - The set of used punctuation is
,.!?. - Punctuation should be kept in your return string, but spaces should not.
- Xray should not have a dash within.
- Every word and punctuation mark should be seperated by a space ‘ ‘.
- There should be no trailing whitespace
The solution in C
Option 1:
How to Add 1 to the Value of each Array in C
The challenge
Given an array of integers of any length, return an array that has 1 added to the value represented by the array.
- the array can’t be empty
- only non-negative, single digit integers are allowed
Return
nil(or your language’s equivalent) for invalid inputs.Examples:
Valid arrays
[4, 3, 2, 5]would return[4, 3, 2, 6]
[1, 2, 3, 9]would return[1, 2, 4, 0]
[9, 9, 9, 9]would return[1, 0, 0, 0, 0]
[0, 1, 3, 7]would return[0, 1, 3, 8]How to Calculate the Sum of a Sequence in C
The challenge
Your task is to make function, which returns the sum of a sequence of integers.
The sequence is defined by 3 non-negative values: begin, end, step (inclusive).
If begin value is greater than the end, function should returns ****
Examples
2,2,2 --> 2 2,6,2 --> 12 (2 + 4 + 6) 1,5,1 --> 15 (1 + 2 + 3 + 4 + 5) 1,5,3 --> 5 (1 + 4)The solution in C
Option 1:
How to Solve the Sum of Triangular Numbers in C
The challenge
Your task is to return the sum of Triangular Numbers up-to-and-including the
nthTriangular Number.Triangular Number: “any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc.”
[01] 02 [03] 04 05 [06] 07 08 09 [10] 11 12 13 14 [15] 16 17 18 19 20 [21]e.g. If
4is given:1 + 3 + 6 + 10 = 20.How to Determine if a String Only Contains Unique Characters in C
The challenge
Write a program to determine if a string contains only unique characters. Return true if it does and false otherwise.
The string may contain any of the 128 ASCII characters. Characters are case-sensitive, e.g. ‘a’ and ‘A’ are considered different characters.
The solution in C
Option 1:
int has_unique_chars(const char *str) { int mask[128]={0}; while (*str) if (++mask[*str++]>1) return 0; return 1; }Option 2:
#include <limits.h> _Bool has_unique_chars(const char *str) { char hit[CHAR_MAX + 1] = {0}; while (*str) { if (*str < 0) { str++; continue; } if (hit[*str]) return 0; hit[*str++] = 1; } return 1; }Option 3:
How to Find the Maximum Multiple in C
The challenge
Given a Divisor and a Bound , Find the largest integer N , Such That ,
Conditions :
- N is divisible by divisor
- N is less than or equal to bound
- N is greater than 0.
Notes
- The parameters (divisor, bound) passed to the function are only positive values .
- It’s guaranteed that a divisor is Found .Input » Output Examples
maxMultiple (2,7) ==> return (6)Explanation:
(6) is divisible by (2) , (6) is less than or equal to bound (7) , and (6) is > 0 .
How to Assign a Digital Cypher in C
The challenge
Digital Cypher assigns to each letter of the alphabet unique number. For example:
a b c d e f g h i j k l m 1 2 3 4 5 6 7 8 9 10 11 12 13 n o p q r s t u v w x y z 14 15 16 17 18 19 20 21 22 23 24 25 26Instead of letters in encrypted word we write the corresponding number, eg. The word scout:
How to Check for All Inclusive in C
The challenge
Input:
- a string
strng - an array of strings
arr
Output of function
contain_all_rots(strng, arr) (or containAllRots or contain-all-rots):- a boolean
trueif all rotations ofstrngare included inarr falseotherwise
Examples:
contain_all_rots( "bsjq", ["bsjq", "qbsj", "sjqb", "twZNsslC", "jqbs"]) -> true contain_all_rots( "Ajylvpy", ["Ajylvpy", "ylvpyAj", "jylvpyA", "lvpyAjy", "pyAjylv", "vpyAjyl", "ipywee"]) -> false)Note:
Though not correct in a mathematical sense
- we will consider that there are no rotations of
strng == "" - and for any array
arr:contain_all_rots("", arr) --> true
The solution in C
Option 1:
How to Solve for Factorial in C
The challenge
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.
Write a function to calculate factorial for a given input. If input is below 0 or above 12 return
-1(C).How to Create an Incrementer in C
The challenge
Given an input of an array of digits, return the array with each digit incremented by its position in the array: the first digit will be incremented by 1, the second digit by 2, etc. Make sure to start counting your positions from 1 ( and not 0 ).
Your result can only contain single digit numbers, so if adding a digit with its position gives you a multiple-digit number, only the last digit of the number should be returned.
How to Return the Closest Number Multiple of 10 in C
The challenge
Given a number return the closest number to it that is divisible by 10.
Example input:
22 25 37Expected output:
20 30 40The solution in C
Option 1:
#include <math.h> int round_to_10 (int n) { return round(n / 10.0) * 10; }Option 2:
int round_to_10(int n) { return (n + 5) / 10 * 10; }Option 3:
int round_to_10 (int n) { int r = n % 10; if (r > 0) return r < 5 ? n - r : n - r + 10; else if (r < 0) return r > -5 ? n - r : n - r - 10; return n; }Test cases to validate our solution
#include <criterion/criterion.h> extern int round_to_10 (int n); static void do_test (int n, int expected); Test(tests_suite, sample_tests) { do_test(0, 0); do_test(10, 10); do_test(22, 20); do_test(25, 30); do_test(37, 40); } static void do_test (int n, int expected) { int actual = round_to_10(n); cr_assert_eq(actual, expected, "for n = %d, expected %d, but got %d", n, expected, actual ); }How to Reverse Every Other Word in a String in C
The challenge
Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this challenge.
The solution in C
Option 1:
#include <stddef.h> #include <stdbool.h> void reverse_alternate(const char *string, char *result) { bool is_word = false, is_second = false, not_first = false; for (const char *s = string; *s; ++s) { if (*s == ' ' && is_word) { is_word = false; is_second = !is_second; } else if (*s != ' ' && !is_word) { if (not_first) *result++ = ' '; is_word = not_first = true; } if (is_second && is_word) { size_t i = 0; for (const char *ss = s; *ss && *ss != ' '; ++ss, ++i) ; for (size_t j = 0; j < i; ++j) result[j] = s[i - j - 1]; s += i - 1; result += i; } else if (*s != ' ') *result++ = *s; } *result = '\0'; }Option 2:
How to Solve Simple Beads Count in C
The challenge
Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads.
@ @@ @ @@ @ @@ @ @@ @ @@ @
How to Solve the Maze Runner in C
The challenge
Introduction
Welcome Adventurer. Your aim is to navigate the maze and reach the finish point without touching any walls. Doing so will kill you instantly!
Task
You will be given a 2D array of the maze and an array of directions. Your task is to follow the directions given. If you reach the end point before all your moves have gone, you should return Finish. If you hit any walls or go outside the maze border, you should return Dead. If you find yourself still in the maze after using all the moves, you should return Lost.
The Maze array will look like
How to Take a Number and Sum It’s Digits Raied to the Consecutive Powers in C
The challenge
The number
89is the first integer with more than one digit that fulfills the property partially introduced in the title of this challenge. What’s the use of saying “Eureka”? Because this sum gives the same number.In effect:
89 = 8^1 + 9^2The next number in having this property is
135.See this property again:
135 = 1^1 + 3^2 + 5^3We need a function to collect these numbers, that may receive two integers
a,bthat defines the range[a, b](inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.How to Find the Middle Element in C
The challenge
You need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.
The input to the function will be an array of three distinct numbers (Haskell: a tuple).
For example:
gimme([2, 3, 1]) => 02 is the number that fits between 1 and 3 and the index of 2 in the input array is __.
How to Invite More Women in C
The challenge
Task
King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel.
To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year’s party. He gave you a list of integers of all the party goers.
How to Build a Tower in C
The challenge
Build a pyramid-shaped tower, as an array/list of strings, given a positive integer
number of floors. A tower block is represented with"*"character.For example, a tower with
3floors looks like this:[ " * ", " *** ", "*****" ]And a tower with
6floors looks like this:[ " * ", " *** ", " ***** ", " ******* ", " ********* ", "***********" ]The solution in C
Option 1:
How to Calculate A Rule of Divisibility by 7 in C
The challenge
A number m of the form 10x + y is divisible by 7 if and only if x − 2y is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a number known to be divisible by 7 is obtained; you can stop when this number has at most 2 digits because you are supposed to know if a number of at most 2 digits is divisible by 7 or not.
How to Categorize a New Member in C
The challenge
The Western Suburbs Croquet Club has two categories of membership, Senior and Open. They would like your help with an application form that will tell prospective members which category they will be placed.
To be a senior, a member must be at least 55 years old and have a handicap greater than 7. In this croquet club, handicaps range from -2 to +26; the better the player the lower the handicap.
Load Balancing Strategies for Distributed Systems
Master the art of distributing traffic efficiently across multiple servers and services in distributed architectures.
Understanding Load Balancing in Distributed Systems
Load balancing in distributed systems operates at multiple levels, from DNS-based global load balancing to application-level request distribution. Before diving into specific strategies, let’s understand the key objectives and challenges.
Key Objectives of Load Balancing
- Even Distribution: Spread workload evenly across available resources
- High Availability: Ensure service continuity even when some components fail
- Scalability: Accommodate growing workloads by adding resources
- Efficiency: Optimize resource utilization
- Latency Reduction: Minimize response times for end users
Load Balancing Layers
Load balancing can be implemented at different layers of the system:
How to Solve Deodorant Evaporator in C
The challenge
This program tests the life of an evaporator containing a gas.
We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive.
The program reports the nth day (as an integer) on which the evaporator will be out of use.
How to Find the Divisors in C
The challenge
Create a function named
divisors/Divisorsthat takes an integern > 1and returns an array with all of the integer’s divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string ‘(integer) is prime’ (nullin C#) (useEither String ain Haskell andResult<Vec<u32>, String>in Rust).Example:
divisors(12); // results in {2, 3, 4, 6} divisors(25); // results in {5} divisors(13); // results in NULLThe solution in C
Option 1:
Terraform State Management: Advanced Patterns and Best Practices
Terraform state is both the most critical and most dangerous aspect of infrastructure as code. It’s your source of truth for what exists, but it’s also a single point of failure that can lock teams out of their infrastructure or, worse, lead to accidental resource destruction.
This guide goes deep into state management patterns that work at scale, covering everything from basic remote backends to complex state migration strategies and disaster recovery procedures.
Solving Love vs Friendship in C
The challenge
If
a = 1, b = 2, c = 3 ... z = 26Then
l + o + v + e = 54and
f + r + i + e + n + d + s + h + i + p = 108So
friendshipis twice as strong aslove🙂Your task is to write a function which calculates the value of a word based off the sum of the alphabet positions of its characters.
Terraform Testing and Validation: Quality Infrastructure Code
Infrastructure code needs the same quality assurance practices as application code, but testing infrastructure presents unique challenges. How do you unit test a VPC? How do you validate that your security policies actually work? How do you catch configuration errors before they reach production?
This guide covers the complete spectrum of Terraform testing and validation, from static analysis and policy validation to integration testing with real cloud resources.
Static Analysis and Linting
Static analysis catches errors before you even run Terraform, identifying syntax issues, security problems, and style inconsistencies that could cause problems later. Unlike application code, infrastructure code mistakes can be expensive—literally. A misconfigured security group or an oversized instance type can cost money and create security vulnerabilities.
How to Bounce Balls in C
The challenge
A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.
He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).
His mother looks out of a window 1.5 meters from the ground.
How many times will the mother see the ball pass in front of her window (including when it’s falling and bouncing?
How to Find the Capitals in C
The challenge
Instructions
Write a function that takes a single string (
word) as argument. The function must return an ordered list containing the indexes of all capital letters in the string.Example
Test.assertSimilar( capitals('CodEStAr'), [0,3,4,6] );The solution in C
Option 1:
#include <stddef.h> #include <string.h> #include <stdlib.h> size_t *find_capitals(const char *word, size_t *nb_uppercase) { size_t n = strlen(word); size_t *arr = (size_t *) calloc(n, sizeof(size_t)); size_t j = 0; for(size_t i=0; i<n; i++) { if(word[i] >='A' && word[i] <='Z') { arr[j++] = i; } } *nb_uppercase = j; return realloc(arr, j * sizeof(size_t)); }Option 2:
How to Empty and Delete an S3 Bucket using the AWS CLI
Option 1 – Using
AWS CLIStep 1
export bucketname='your-bucket-here'Step 2
aws s3api delete-objects --bucket $bucketname --delete "$(aws s3api list-object-versions --bucket $bucketname --output=json --query='{Objects: *[].{Key:Key,VersionId:VersionId}}')";Step 3
aws s3 rb s3://$bucketnameOption 2 – Using
Python#!/usr/bin/env python BUCKET = 'your-bucket-here' import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket(BUCKET) bucket.object_versions.delete() bucket.delete()What ports to open for FSx connection to AWS Managed Active Directory
If you are creating a FSx file system, and want to connect it to AWS Managed Active Directory, then you will need to create a VPC Security Group with the following ports:
Inbound ports
Rules Ports UDP 53, 88, 123, 389, 464 TCP 53, 88, 123, 389, 445, 464, 636, 3268, 3269, 9389, 49152-65535 Outbound ports
All traffic,0.0.0.0/0Multi-Cloud Terraform: Managing Infrastructure Across Providers
Multi-cloud strategies are becoming increasingly common as organizations seek to avoid vendor lock-in, leverage best-of-breed services, and meet compliance requirements. However, managing infrastructure across multiple cloud providers introduces complexity in networking, identity management, monitoring, and operational processes.
This guide covers the patterns and practices for successfully implementing multi-cloud infrastructure with Terraform, from basic provider configuration to advanced cross-cloud networking and unified governance.
Multi-Provider Setup
Managing infrastructure across multiple cloud providers requires careful planning of provider configurations, authentication strategies, and resource organization. Each cloud provider has different authentication mechanisms, regional structures, and service offerings that need to be coordinated in a unified Terraform configuration.
How to Calculate Variance in Python
If you need to calculate
variancein Python, then you can do the following.Option 1 – Using
variance()fromStatisticsmoduleimport statistics list = [12,14,10,6,23,31] print("List : " + str(list)) var = statistics.variance(list) print("Variance: " + str(var))Option 2 – Using
var()fromnumpymoduleimport numpy as np arr = [12,43,24,17,32] print("Array : ", arr) print("Variance: ", np.var(arr))Option 3 – Using
sum()andList Comprehensionslist = [12,43,24,17,32] average = sum(list) / len(list) var = sum((x-average)**2 for x in list) / len(list) print(var)How to Calculate the Sum of a List in Python
If you need to calculate and get the sum of a list in Python, then you can do the following.
Option 1 – Using
sum()myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] listSum = sum(myList) print(f"Sum of list -> {listSum}")If you get a
TypeErrorthen you can do the following:myList = ["1", "3", "5", "7", "9"] myNewList = [int(string) for string in myList] sum1 = sum(myNewList) sum2 = sum(number for number in myNewList) print(f"Sum of list -> {sum1}") print(f"Sum of list -> {sum2}")Option 2 – Using
formyList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] length = len(myList) listSum = 0 for i in range(length): listSum += myList[i] print(f"Sum of list -> {listSum}")How to add a List to a Set in Python
If you need to add a
listto asetin Python, then you can do the following:Option 1 – Using
Tuplemyset = set((1,2,3,4)) mylist = list(1,2,3]) myset.add(tuple(mylist)) print(myset)Output:
{1, 2, 3, 4, (1, 2, 3)}Option 2 – Using
set.update()myset = set((1,2,3,4)) mylist = list(8,9,12]) myset.update(tuple(mylist)) print(myset)Output:
{1, 2, 3, 4, 8, 9, 12}How to Remove Punctuation from a List in Python
If you have a Python list, and want to remove all punctuation, then you can do the following:
First get all punctuation by using
string.punctuationimport string print(string.punctuation)Output:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Option 1 – Using
forimport string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] new_words = [] for word in words: if word == "": words.remove(word) else: for letter in word: if letter in string.punctuation: word = word.replace(letter,"") new_words.append(word) print(new_words)Option 2 – Using
List Comprehensionsimport string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] words = [''.join(letter for letter in word if letter not in string.punctuation) for word in words if word] print(words)Option 3 – Using
str.translate()import string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] words = [word.translate(string.punctuation) for word in words if word] print(words)How to Normalize a List of Numbers in Python
If you need to normalize a list of numbers in Python, then you can do the following:
Option 1 – Using
Native Pythonlist = [6,1,0,2,7,3,8,1,5] print('Original List:',list) xmin = min(list) xmax=max(list) for i, x in enumerate(list): list[i] = (x-xmin) / (xmax-xmin) print('Normalized List:',list)Option 2 – Using
MinMaxScalerfromsklearnimport numpy as np from sklearn import preprocessing list = np.array([6,1,0,2,7,3,8,1,5]).reshape(-1,1) print('Original List:',list) scaler = preprocessing.MinMaxScaler() normalizedlist=scaler.fit_transform(list) print('Normalized List:',normalizedlist)You can also specify the
rangeof theMinMaxScaler().How to Multiply a List by a Scalar in Python
If you need to multiply a list by a scalar in Python, then you can do one of the following:
Option 1 – Using
List Comprehensionsli = [1,2,3,4] multiple = 2.5 li = [x*multiple for x in li] print(li)Output:
[2.5, 5.0, 7.5, 10.0]Option 2 – Using
map()li = [1,2,3,4] multiple = 2.5 def multiply(le): return le*multiple li = list(map(multiply,li)) print(li)Output:
[2.5, 5.0, 7.5, 10.0]Option 3 – Using
Lambda Functionsli = [1,2,3,4] multiple = 2.5 li = list(map(lambda x: x*multiple, li)) print(li)Output:
[2.5, 5.0, 7.5, 10.0]How to Find the Index of the Minimum Element in a List in Python
If you need to find the
indexof the minimum element in a list, you can do one of the following:Option 1 – Using
min()andindex()lst = [8,6,9,-1,2,0] m = min(lst) print(lst.index(m))Output:
3Option 2 – Using
min()andforlst = [8,6,9,-1,2,0] m = min(lst) for i in range(len(lst)): if(lst[i]==m): print(i) breakOutput:
3Option 3 – Using
min()andenumerate()lst = [8,6,9,-1,2,0] a,i = min((a,i) for (i,a) in enumerate(lst)) print(i)Output:
3How to Convert a Set to a String in Python
If you need to convert a
setto astringin Python, then you can do one of the following:Option 1 – Using
map()andjoin()str_new = ', '.join(list(map(str, se)))You can confirm this worked as follows:
print(str_new) print(type(str_new)) # '1, 2, 3' # <class 'str'>Option 2 – Using
repr()r_str = repr(se)You can confirm this worked as follows:
print(r_str) print(type(r_str)) # {1, 2, 3} # <class 'str'>How to Decrement a Loop in Python
If you need to decrement a loop in Python, then you can do the following:
How to Decrement a loop in Python using
-1The optional third argument you can pass to the
rangefunction is the order.The default order is to count up / increment, while the
-1value, is to count down / decrement.for i in range(3, 0, -1): print(i)Output:
3 2 1How to Decrement a loop in Python using
whileYou can also use a
whileloop and set the value to the upper bound, and then decrement while in the loop itself.How to Create Zip Archive of Directory in Python
If you need to create a
zipof a directory using Python, then you can do the following:Create a Zip using
shutilin Pythonimport os import shutil filename = "compressed_archive" format = "zip" directory = os.getcwd() shutil.make_archive(filename, format, directory)How to Remove the Last Character of a String in PHP
If you need to remove the last character of a string in PHP, then you can do the following:
Option 1 – Using
rtrim()Syntax:
rtrim($string, $character)$mystring = "This is a PHP program!"; echo("Before Removal: $mystring\n"); # Before Removal: This is a PHP program! $newstring = rtrim($mystring, ". "); echo("After Removal: $newstring"); # After Removal: This is a PHP programOption 2 – Using
substr()Syntax:
substr($string, $start, $length)$mystring = "This is a PHP program!"; echo substr($mystring, 0, -1); # This is a PHP programHow to Create Function with Multiple Returns in PHP
If you need to create a PHP function that returns multiple values, then you can do one of the following.
Option 1 – Returning an
arrayfunction returnArray() { return array("one", "two"); } // call the function and print the response var_dump(returnArray());Option 2 – Returning a
conditionalfunction returnConditional($x = true) { if ($x) return "one"; else return "two"; } // call the function with a value and print the response var_dump(returnConditional(false));Option 3 – Using
generatortoyieldvaluesfunction multipleValues() { yield "one"; yield "two"; } $res = multipleValues(); foreach($res as $r) { echo $r; // first val=="one", second val=="two" }How to Download a File in NodeJS without any Third Party Libraries
If you need to download a file in NodeJS without using any third party libraries, then you can do the following.
The NodeJS ecosystem comes with a
fsmodule, this is to denote the FileSystem built in library.First declare your imports:
const http = require('https'); const fs = require('fs');Now you can use the
httpsmodule to download a file, and write it to a stream usingfs.const https = require("https"); const fs = require("fs"); const endpoint = "https://example/files/some_csv_file"; https.get(endpoint, (res) => { const file_name = "the_csv.csv"; const writeStream = fs.createWriteStream(file_name); });How to Execute a Shell Script in NodeJS
If you need to execute a shell script in NodeJS, then you can use the
execkeyword.Syntax:
exec(command [, options] [, callback]const shell = require('shelljs') shell.exec("npm --version")How to Print Multiple Arguments in Python
If you need to print out multiple arguments using Python, then you can do one of the following:
Option 1 – Using
printprint("Something", "Else", "Please")Output:
Something Else PleaseOption 2 – Using
String Formattingprint("Something {} {}".format("Else", "Please"))Output:
Something Else PleaseOr with explicit ordering:
print("Something {1} {0}".format("Else", "Please"))Output:
Something Please ElseOption 3 – Using
F-String Formattingone = "Something" two = "Else" three = "Please" print(f"{one} {two} {three}")Output:
Something Else PleaseHow to Delete all Resources Except One in Terraform
If you need to delete all resources created by Terraform, except for a single, specific one, then you can do the following:
Step 1 – Get the current
state listterraform state listStep 2 – Remove the exception resource
Remove the specific resource that you don’t want Terraform to track anymore.
terraform state rm <resource_to_be_removed>Step 3 – Destroy the resources
terraform destroyHow to Copy Files between Two Nodes using Ansible
If you need to copy files between two (2) nodes, using Ansible, then you can do the following:
This solution uses the
synchronizemodule, specifically using thedelegate_to:source-serverkeywords.- hosts: serverB tasks: - name: Copy Remote-To-Remote (from serverA to serverB) synchronize: src=https://andrewodendaal.com/copy/from_serverA dest=/copy/to_serverB delegate_to: serverAHow to Delete Files and Folders in a Directory using Ansible
If you need to delete files and folders in a directory using Ansible, then you can do the following:
- name: Delete content & entire directory file: state: absent path: /some/directory/path/How to Copy Multiple Files with Ansible
If you need to copy multiple files using Ansible, then you can do the following:
How to Copy Multiple Files with Ansible
Look into using the
with_fileglobloop as follows:- copy: src: "{{ item }}" dest: /etc/fooapp/ owner: root mode: 600 with_fileglob: - /playbooks/files/fooapp/*If you would like to do it as a task, then this could help:
- name: Your copy task copy: src={{ item.src }} dest={{ item.dest }} with_items: - { src: 'another_file', dest: '/etc/somewhere' } - { src: 'dynamic', dest: '{{ var_path }}' } # repeat for additional filesHow to Write Multiline Shell Scripts in Ansible
If you need to write a shell script in Ansible, you probably have something like this:
- name: iterate user groups shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} with_items: "{{ users }}"But how do you write multiline shell scripts with this format?
How to write Multiline shell scripts
- name: iterate user groups shell: | groupmod -o -g {{ item['guid'] }} {{ item['username'] }} do_some_stuff_here and_some_other_stuff with_items: "{{ users }}"Just note that Ansible can do some strange things with manipulations of arguments, so you may want to follow something like this:
How to Pass Variables to Ansible Playbook CLI
If you need to pass a variable to Ansible playbook, using the command line, then you can do the following:
Option 1 – Specifying command line arguments
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"N.B.
--extra-varsspecified variables will override any variables with the same name defined inside the playbook.You can also read up on Passing Variables On The Command Line (Wayback Machine link to maintain versioning)
Option 2 – Specify a YML file
You can also specify a
.ymlfile with the variables:How to Create a Directory using Ansible
If you need to create a directory using Ansible, then you can do the following:
Create a Directory in Ansible
You will need the
filemodule, then to create a directory you simply specify the optionstate=directory:- name: Creates a directory file: path: /src/www state: directoryNote that with
state=directory, all the immediate subdirectories will be created if they don’t already exist.Extending the
filemodule- name: Creates a directory file: path: /src/www state: directory owner: www-data group: www-data mode: 0775Create the Directories Recursively
- name: Creates directory file: path: /src/www state: directory owner: www-data group: www-data mode: 0775 recurse: yesThis is similar to the
recursiveargument used withmkdir -pHow to Disable Screensaver on Mac using the CLI
If you want to disable the Screensaver on your Mac, by using the Command Line Interface (CLI), then you can do the following:
Step 1 – See what is currently set
defaults read com.apple.screensaverStep 2 – Set the
idleTimedefaults -currentHost write com.apple.screensaver idleTime 0Step 3 – (Optional) – Undo the change
defaults -currentHost delete com.apple.screensaver idleTimeHow to Remove Old and Unused Docker Images
If you need to remove any old and unused Docker images, then you can do the following:
How to Remove Old and Unused Docker Images
Firstly you need to see all the images:
docker imagesYou can also use
lsto see the Docker Images:docker image lsHow to Remove a Single Docker Image
The
docker rmicommand will remove a single Docker image as follows:docker rmi <image_id>You can also use the Docker image names as follows:
How to Convert Milliseconds to Date in Javascript
If you need to convert Milliseconds to Date in Javascript, then you can do the following:
How to Convert Milliseconds to Date in Javascript
let date = new Date(milliseconds); date.toString();Common Date Conversions From Milliseconds in Javascript
let originalDate = new Date(milliseconds); // output: "D/MM/YYYY, H:MM:SS PM/AM" originalDate.toLocaleString(); //output: "D/MM/YYYY" originalDate.toLocaleDateString(); // output: "Day Month DD YYYY" originalDate.toDateString(); // output: "HH:MM:SS GMT+0530" originalDate.toTimeString(); // output: "Day Month DD YYYY HH:MM:SS GMT+0500" originalDate.toString(); // output: "H:MM:SS AM/PM" originalDate.toLocaleTimeString();How to Convert String to Title Case in Javascript
If you need to convert a String to Title Case in Javascript, then you can do one of the following:
Option 1 – Using a
forloopfunction titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); return str.join(' '); } console.log(titleCase("this is an example of some text!"));Output:
This Is An Example Of Some Text!Option 2 – Using
map()function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return (word.charAt(0).toUpperCase() + word.slice(1)); }).join(' '); } console.log(titleCase("this is an example of some text!"));Output:
This Is An Example Of Some Text!How to Compile Multiple Java Files from a Single Command in Java
If you need to compile multiple Java files using a single command, then you can do the following.
First, it’s good to learn how to compile a Java file.
How to Compile a Java File
Let’s take the following Java code:
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }To compile this, we simply do the following:
javac HelloWorld.javaThen when we need to run it, we do:
How to Convert JSON to a Java Object
If you need to convert JSON to a Java Object, then you can do one of the following:
Option 1 – Using
Gsonimport com.google.gson.Gson; public class SimpleTesting { public static void main(String[] args) throws InterruptedException { String json = """ { "firstName" : "Jane", "lastName" : "Doe", "dateOfBirth" : "1973-04-29", "address" : "81 Hype", "city" : "New York", "contact" : "0123456789" } """; Student data = new Gson().fromJson(json, Student.class); System.out.println(data.getFirstName()); System.out.println(data.getLastName()); System.out.println(data.getCity()); } } class Student { private String firstName; private String lastName; private String dateOfBirth; private String address; private String city; private String contact; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } }Option 2 – Using
Jacksonimport java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class SimpleTesting { public static void main(String[] args) throws InterruptedException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); try { Student student = mapper.readValue(new File("json-file.json"), Student.class); System.out.println("First Name: "+student.getFirstName()); System.out.println("Last Name: "+student.getLastName()); System.out.println("City: "+student.getCity()); System.out.println("Address: "+student.getAddress()); System.out.println("Contact: "+student.getContact()); System.out.println("Date of Birth: "+student.getDateOfBirth()); } catch(IOException e) { e.printStackTrace(); } } } class Student { private String firstName; private String lastName; private String dateOfBirth; private String address; private String city; private String contact; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } }How to Calculate Powers of Integers in Java
If you need to calculate the powers of Integers in Java, then you can do one of the following:
Option 1 – Using
forloopspublic class Power { public static void main(String args[]){ int number = 5; int power = 3; int result = calculatePower(number,power); System.out.println(number+"^"+power+"="+result); } static int calculatePower(int num, int power){ int answer = 1; if (num > 0 && power==0){ return answer; } else if(num == 0 && power>=1){ return 0; } else{ for(int i = 1; i<= power; i++) answer = answer*num; return answer; } } }Option 2 – Using Recursion
public class Power { public static void main(String args[]){ int number = 3; int power = 3; int result = CalculatePower(number,power); System.out.println(number+"^"+power+"="+result); } static int CalculatePower (int num, int pow){ if (pow == 0) return 1; else return num * CalculatePower(num, pow - 1); } }Option 3 – Using
Math.pow()import java.lang.Math; public class Power { public static void main(String args[]){ int number = 6; int power = 3; double result = CalculatePower(number,power); System.out.println(number+"^"+power+"="+result); } static double CalculatePower (int num, int pow){ return Math.pow(num,pow); } }How to Get Today’s Date in Java
If you need to get today’s date in Java, then you can do one of the following:
Option 1 – Using
LocalDateimport java.time.LocalDate; public class GetTodayDate { public static void main(String[] args) { LocalDate todaysDate = LocalDate.now(); System.out.println(todaysDate); } }Option 2 – Using
CalendarandSimpleDateFormatimport java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class GetTodayDate { public static void main(String[] args) { SimpleDateFormat dtf = new SimpleDateFormat("yyyy/MM/dd"); Calendar calendar = Calendar.getInstance(); Date dateObj = calendar.getTime(); String formattedDate = dtf.format(dateObj); System.out.println(formattedDate); } }Option 3 – Using
java.sql.Dateimport java.sql.Date; public class GetTodayDate { public static void main(String[] args) { long miliseconds = System.currentTimeMillis(); Date date = new Date(miliseconds); System.out.println(date); } }How to Copy Files from Docker Container to Host
If you need to copy files from a Docker Container to the Host, then you can do one of the following:
Option 1 – Using
docker cpSyntax:
docker cp [OPTIONS] CONTAINER: SRC_PATH DEST_PATHSetup the container:
# pull the ubuntu image docker pull ubuntu # run the container locally docker run -it -d ubuntu # connect to the container docker exec -it abcde123456 /bin/bashCreate a file from the container:
cd usr cd share touch some_file.txt lsCopy the file from the container to the host:
How to Get the IP Address of a Docker Container
If you need to get the IP Address of a Docker Container, then you can do the following:
Option 1 – Connect to the Bridge Network
Find out the network setup:
docker network lsCreate a docker container and assign it to the bridge network:
docker run -dt <nginx>Get the information about the container:
docker psInspect the network:
docker network inspect bridgeNow you can see the container IP Address.
Option 2 – Use
docker inspectUse the container id to get detailed information:
How to Convert Time to String in Golang
If you need to convert
Timeto aStringin Go, then you can do one of the following:Option 1 – Using
time.Nowpackage main import ( "fmt" "time" ) func main() { currentTime := time.Now() fmt.Println("Time: ", currentTime.String()) }Option 2 – Using
time.Time.String()package main import ( "fmt" "time" ) func main() { Time := time.Date(2022, 03, 28, 03, 50, 16, 0, time.UTC) t := Time.String() fmt.Printf("Time without the nano seconds: %v\n", t) }How to Perform a Deep Copy in Golang
To perform a
Deep Copyin Go, you can use astructtype as follows:Deep Copying using a
structin Gopackage main import ( "fmt" ) type Dog struct { age int name string friends []string } func main() { john := Dog{1, "Harry", []string{"Steve", "Matt", "Sarah"}} jack := john jack.friends = make([]string, len(john.friends)) copy(jack.friends, harry.friends) jack.friends = append(jay.friends, "Fred") fmt.Println(john) fmt.Println(jack) }How to Return Lambda Functions in Golang
Go doesn’t typically have Lambda Expressions, but synonymous to
Lambdas, orClosuresifAnonymous Functionsfor Go.How to return a value from an Anonymous Function in Go
package main import "fmt" func main() { var sum = func(n1, n2 int) int { sum := n1 + n2 return sum } result := sum(5, 3) fmt.Println("Sum is:", result) }How to return an Area from an Anonymous Function in Go
package main import "fmt" var ( area = func(l int, b int) int { return l * b } ) func main() { fmt.Println(area(10, 10)) }How to Create an Empty Slice in Golang
If you would like to create an empty slice in Go, then you can do the following:
Option 1 – Initialize an Empty Slice in Go
package main import "fmt" func main() { b := []string{} fmt.Println(b == nil) }Option 2 – Using
make()package main import "fmt" func main() { c := make([]string, 0) fmt.Println(c == nil) }How to Parallelize a for Loop in Python
If you need to run a for loop in parallel, then you can do one of the following:
Option 1 – Using
multiprocessingimport multiprocessing def sumall(value): return sum(range(1, value + 1)) pool_obj = multiprocessing.Pool() answer = pool_obj.map(sumall,range(0,5)) print(answer)Option 2 – Using
joblibmodulefrom joblib import Parallel, delayed import math def sqrt_func(i, j): time.sleep(1) return math.sqrt(i**j) Parallel(n_jobs=2)(delayed(sqrt_func)(i, j) for i in range(5) for j in range(2))Option 3 – Using
asyncioimport asyncio import time def background(f): def wrapped(*args, **kwargs): return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs) return wrapped @background def your_function(argument): time.sleep(2) print('function finished for '+str(argument)) for i in range(10): your_function(i) print('loop finished')How to Reverse an Integer in Python
If you need to reverse an integer using Python, then you can do the following:
Option 1 – Mathematical Palindrome Check
original_number = 123454321 copy_number = original_number reversed_number = 0 while original_number > 0: remainder = original_number % 10 reversed_number = reversed_number * 10 + remainder original_number = original_number // 10 if copy_number == reversed_number: print(copy_number, 'is a palindrome number') else: print(copy_number, 'is not a palindrome number')Option 2 – String Reversal Number Palindrome
number = 123454321 if number == int(str(number)[::-1]): print(number, 'is palindrome.') else: print(number, 'is not palindrome.')Option 3 – List Reversal Number Palindrome
original_number = 123454321 lst_number = list(str(original_number)) lst_number.reverse() reversed_number = ''.join(lst_number) if (original_number == int(reversed_number)): print(original_number, 'is palindrome.') else: print(original_number, 'is not palindrome.')Terraform for AWS: Cloud-Native Infrastructure
AWS and Terraform are a powerful combination, but AWS’s complexity means there are specific patterns, gotchas, and best practices that aren’t obvious from general Terraform knowledge. This guide bridges that gap, covering the AWS-specific techniques that separate basic resource creation from production-ready, well-architected infrastructure.
From VPC design patterns to multi-account strategies, this guide covers the real-world challenges you’ll face when managing AWS infrastructure at scale with Terraform.
AWS Provider Setup
The AWS provider is Terraform’s gateway to Amazon Web Services, but configuring it properly for production use involves more than just setting a region. Authentication strategies, provider aliases for multi-region deployments, and proper credential management are essential for building reliable, secure infrastructure automation.
How to Save a Python Dictionary to a File in Python
If you need to save a Python Dictionary object type to a file using Python, then you can do one of the following:
Option 1 – Using
picklemoduleimport pickle my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23} with open("dictionaryFile.pkl", "wb") as tf: pickle.dump(my_dict,tf)Then you can load the pickle file back as follows:
import pickle with open("dictionaryFile.pkl", "wb") as tf: new_dict = pickle.load(tf) print(new_dict)Option 2 – Using
numpyimport numpy as np my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23} np.save('dictionaryFile.npy', my_dict)Then you can load the file back as follows:
Terraform Fundamentals: Infrastructure as Code
Infrastructure as Code isn’t just a buzzword—it’s the difference between spending your weekend manually clicking through cloud consoles and having reproducible, version-controlled infrastructure that deploys consistently every time. Terraform has become the de facto standard for managing cloud resources, but mastering it requires understanding not just the syntax, but the patterns and practices that separate toy projects from production-ready infrastructure.
This guide takes you from writing your first Terraform configuration to architecting complex, multi-environment infrastructure with proper state management, security, and team collaboration patterns.
How to Move Files From One Directory to Another Using Python
If you need to move files from one directory to another directory, using Python, then you can do one of the following:
Option 1 – Using
shutil.move()import shutil import os file_source = 'source/directory' file_destination = 'destination/directory' get_files = os.listdir(file_source) for file in get_files: shutil.move(file_source + file, file_destination)Option 2 – Using
os.replace()import os file_source = 'source/directory' file_destination = 'destination/directory' get_files = os.listdir(file_source) for file in get_files: os.replace(file_source + file, file_destination + file)Option 3 – Using
pathlibfrom pathlib import Path import shutil import os file_source ='source/directory' file_destination ='destination/directory' for file in Path(file_source).glob('some_file.txt'): shutil.move(os.path.join(file_source,file), file_destination)How to Get the Number of Lines in a File in Python
If you need to get the number of lines in a file, or the line count total from a file, using Python, then you can use one of the following options:
Option 1 – Using
open()andsum()with open('directory/file.txt') as myfile: total_lines = sum(1 for line in myfile) print(total_lines)Option 2 – Using
mmapimport mmap with open('directory/file.txt', "r+") as myfile: mm = mmap.mmap(myfile.fileno(), 0) total_lines = 0 while mm.readline(): total_lines += 1 print(total_lines)Option 3 – Using
file.read()lines = 0 size = 1024 * 1024 with open(r'directory/file.txt', "r+") as myfile: read_file = myfile.read buffer = read_file(size) while buffer: lines += buffer.count('\n') buffer = read_file(size) if (lines != 0): lines += 1 print(lines)How to Read Specific Lines From a File in Python
If you need to read a specific line from a file using Python, then you can use one of the following options:
Option 1 – Using
fileobject.readlines()If you need to read
line 10:with open("file.txt") as f: data = f.readlines()[10] print(data)If you need to read
lines 10, to 20:with open("file.txt") as f: data = f.readlines()[10:20] print(data)Option 2 – Using
forinfileobjectlines =[10, 20] data = [] i = 0 with open("file.txt", "r+") as f: for line in f: if i in lines: data.append(line.strip) i = i + 1 print(data)Option 3 – Using
linecachemoduleimport linecache data = linecache.getline('file.txt', 10).strip()Option 4 – Using
enumeratewith open("file.txt") as f: for i, line in enumerate(f): pass # process line iHow to Get All Files in a Directory in Python
If you need to get all the files in a directory using Python, then you can do the following:
Option 1 – Using
os.listdir()import os dirPath = r"/your/directory/path/" result = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f))] print(result)Option 2 – Using
os.walk()import os dirPath = r"/your/directory/path/" result = next(os.walk(dirPath))[2] print(result)Option 3 – Using
glob.glob()import glob dirPathPattern = r"/your/directory/path/*.*" result = glog.glob(dirPathPattern) print(result)[Solved] dial tcp: lookup proxy.golang.org: i/o timeout
If you get a timeout when trying to install go dependencies, the error may look something like this:
$ go get github.com/aws/aws-sdk-go/aws go: module github.com/aws/aws-sdk-go/aws: Get "https://proxy.golang.org/github.com/aws/aws-sdk-go/aws/@v/list": dial tcp: lookup proxy.golang.org: i/o timeoutHow to Solve the Timeout Issue when installing Go Deps
export GOPROXY=directThen re-run your
go getcommand.How to Check Operating System in Python
If you need to check the Operating System information from Python, then you can do one of the following:
Option 1 – Using the
platformmoduleimport platform my_os = platform.system() print("Operating System is: ",my_os)Option 2 – Using the
sysmoduleimport sys my_os=sys.platform print("Operating System is: ",my_os)How to Convert Hex to Byte in Python
If you need to convert Hex to Byte in Python, then you can do one of the following:
Option 1 – Using
binasciiimport binascii str_val = 'This is a test'.encode('utf-8') hex_val = binascii.hexlify(str_val).decode('utf-8') print(hex_val)Option 2 – Using
bytes.fromhex()hex_val = 'This is a test' print(bytes.fromhex(hex_val))Option 3 – Using
unhexlifyimport binascii from binascii import unhexlify str_val = 'This is a test'.encode('utf-8') hex_val = binascii.hexlify(str_val).decode('utf-8') print('String value: ', str_val.decode('utf-8')) print('Hexadecimal: ', hex_val) print('Byte value: ', unhexlify(hex_val))[Solved] fatal: Could not read from remote repository with Git
If you receive the following error when trying to clone a Git repository:
fatal: Could not read from remote repository.The full message may look something like this:
$ git clone [email protected]:org/repo.git Cloning into 'repo'... Bad owner or permissions on /Users/ao/.ssh/config fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.How to solve this error
ssh-add ~/.ssh/id_rsawhere
id_rsais a ssh key associated with the repo.How to Install Homebrew on a Mac
Prerequisites
- You should have some familiarity with the Mac Terminal application since you’ll need to use it to install Homebrew. The Terminal application is located in the Utilities folder in the Applications folder.
- Dependencies. You need to install one other piece of software before you can install Homebew:
- Xcode. Install Apple’s Xcode development software: Xcode in the Apple App Store.
Installation Overview
Installing Homebrew is straightforward as long as you understand the Mac Terminal. The Homebrew installation process guides through each step.
How to create an AWS EC2 instance in CloudFormation
Create an EC2 Instance in CloudFormation
If you need to create an EC2 instance in CloudFormation, then you can do the following:
AWSTemplateFormatVersion: "2010-09-09" Resources: WebInstance: Type: AWS::EC2::Instance Properties: InstanceType: t2.nano ImageId: ami-80861296 KeyName: my-key SecurityGroupIds: - sg-abc01234 SubnetId: subnet-abc01234You can set the
Instance Nameas follows:AWSTemplateFormatVersion: "2010-09-09" Resources: WebInstance: Type: AWS::EC2::Instance Properties: InstanceType: t2.nano ImageId: ami-80861296 KeyName: my-key SecurityGroupIds: - sg-abc01234 SubnetId: subnet-abc01234 Tags: - Key: Name Value: webserverYou can
Enable Monitoringas follows:How to Run Commands on an AWS ECS Cluster Task or Container
If you need to run a command, or set of commands on an AWS ECS cluster container, then you can do the following:
aws ecs execute-command --cluster ${ClusterName} --task ${TASK_ARN} --container nginx --command "/bin/sh" --interactiveUnderstanding the Network Modes in AWS ECS
If using the EC2 launch type, the allowable network mode depends on the underlying EC2 instance’s operating system. If Linux, awsvpc, bridge, host and none mode can be used. If Windows, only the NAT mode is allowed.
If using the Fargate launch type, the ‘awsvpc’ is the only network mode supported.
The networking behavior of Amazon ECS tasks hosted on Amazon EC2 instances is dependent on the network mode defined in the task definition. The following are the available network modes. Amazon ECS recommends using the awsvpc network mode unless you have a specific need to use a different network mode.
How to Enable ContainerInsights on AWS ECS from the AWS CLI
If you need to enable
Container Insightsfor an ECS cluster, by using the AWS CLI, then you can do the following:aws ecs update-cluster-settings --cluster <cluster-name> --settings name=containerInsights,value=enabled --region <aws_region>AppMesh and ECS with Imported ACM certificates on Envoy Sidecar through EFS
Summary
This guide showcases the ability to use imported certificates from a third party provider (e.g. Venafi) in ACM, mount them in EFS and use them as trusted sources on Envoy sidecars with applications running in ECS. AppMesh is used as a passthrough with TLS termination occurring on the application container layer.
Prerequisites and limitations
Prerequisites
A certificate that contains the chain of domains required for the fronted service and micro-services needed.
How to Increase the disk size on a Cloud9 instance
If you need to increase the disk size of a Cloud9 instance, you can run the following script directly from the terminal in Cloud9:
pip3 install --user --upgrade boto3 export instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id) python3 -c "import boto3 import os from botocore.exceptions import ClientError ec2 = boto3.client('ec2') volume_info = ec2.describe_volumes( Filters=[ { 'Name': 'attachment.instance-id', 'Values': [ os.getenv('instance_id') ] } ] ) volume_id = volume_info['Volumes'][0]['VolumeId'] try: resize = ec2.modify_volume( VolumeId=volume_id, Size=30 ) print(resize) except ClientError as e: if e.response['Error']['Code'] == 'InvalidParameterValue': print('ERROR MESSAGE: {}'.format(e))" if [ $? -eq 0 ]; then sudo reboot fiHow to Get the Instance Profile attached to an AWS EC2
If you need to get the IAM Role information from the attached EC2 role directly, you can do the following:
IAM_ROLE=$(curl -s 169.254.169.254/latest/meta-data/iam/info | \ jq -r '.InstanceProfileArn' | cut -d'/' -f2)How to Create an AWS ECR Repository in AWS CLI
If you need to create an Elastic Container Registry (ECR) Repository from the AWS CLI, you can do the following:
aws ecr create-repository \ --repository-name <repo-name> \ --image-scanning-configuration scanOnPush=true \ --region ${AWS_REGION}How to Scale Out an AWS ECS Service
When you create the Amazon ECS service, it includes three Amazon ECS task replicas. You can see this by using the describe-services command, which returns three. Use the update-service command to scale the service to five tasks. Re-run the describe-services command to see the updated five.
Step 1 – Query the desired count
aws ecs describe-services \ --cluster fargate-getting-started \ --services nginx-service \ --query 'services[0].desiredCount'Output:
3Step 2 – Set the new desired count
aws ecs update-service \ --cluster fargate-getting-started \ --service nginx-service \ --desired-count 5This will now update the service to have a desired count of 5.
How to Retrieve AWS ECS Cluster Information
For more information about the Amazon ECS cluster, run the following command. You will find the number of running tasks, capacity providers, and more.
aws ecs describe-clusters --cluster <your-fargate-cluster>Sample output:
{ "clusters": [ { "clusterArn": "arn:aws:ecs:us-east-2:123456789012:cluster/<your-fargate-cluster>", "clusterName": "fargate-getting-started", "status": "ACTIVE", "registeredContainerInstancesCount": 0, "runningTasksCount": 3, "pendingTasksCount": 0, "activeServicesCount": 1, "statistics": [], "tags": [], "settings": [], "capacityProviders": [ "FARGATE", "FARGATE_SPOT" ], "defaultCapacityProviderStrategy": [] } ], "failures": [] }Types of communication in Amazon EKS
There are multiple types of communication in Amazon EKS environments. Lines of communication include the following:
- Interpod communication between containers
- Communication between pods on the same node or pods on different nodes
- Ingress connections from outside the cluster
In some cases, the default Kubernetes methods are used. In other cases, specifically inter-node communication and ingress methods specific to Amazon EKS are used.
Intrapod communication
Containers in a pod share a Linux namespace and can communicate with each other using localhost. In Kubernetes networking, the IP address with which a container identifies is the same IP address for all entities in the network. All containers can communicate with all other containers in a pod without NAT.
[Solved] Read timeout on endpoint URL: “https://lambda.[region].amazonaws.com/2015-03-31/functions/[function-name]/invocations”
If you get the following error:
Read timeout on endpoint URL: "https://lambda.<region>.amazonaws.com/2015-03-31/functions/<function-name>/invocations"Then you are probably trying to use the
aws clito invoke an AWS Lambda function and it is timing out.Other than making sure to set the Lambda execution time to something much higher than it is, you also need to make sure to specify the
aws cli--cli-read-timeoutargument to something that will cover the execution time.How to Remove a Passphrase from Certificate Key
If you have a Certificate Key that includes a Passphrase and you need to remove it, potentially to use it with AWS App Mesh, then you can do the following:
How to Remove a Passphrase using OpenSSL
- Locate the Private Key
- Run the following command:
open ssl rsa -in <original.key> -out <new.key> - Enter the original passphrase for the existing key
- The output file <new.key> will now be unencrypted
How to Verify if the Passphrase has been removed
Open the file in a text editor and check the headers.
How to get Python logger to Print to std out
If you use Python’s
loggeras follows:import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) # or logging.INFOPerhaps you want to get it to print to Standard Output (
stdout), then you can do the following:Setup Logger to print to Standard Output
import logging logger = logging.getLogger() # logger.setLevel(logging.INFO) logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler)This way you can now log straight to the console as well:
How to Convert a String to an Integer in C
If you need to convert a String to an Integer in C, then you can do one of the following:
Option 1 – Use
atoi()int atoi(const char *str);You can do something like this:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { int value; char str[20]; strcpy(str,"123"); value = atoi(str); printf("String value = %s, Int value = %d\n", str, value); return(0); }Option 2 – Use
strtol()long int strtol(const char *string, char **laststr,int basenumber);How to Convert an Integer to a String in C
If you need to convert an Integer to a String in C, then you can do one of the following:
Option 1 – Use
sprintf()int sprintf(char *str, const char *format, [arg1, arg2, ... ]);You can do something like this:
#include <stdio.h> int main(void) { int number; char text[20]; printf("Enter a number: "); scanf("%d", &number); sprintf(text, "%d", number); printf("\nYou have entered: %s", text); return 0; }Option 2 – Use
itoa()char* itoa(int num, char * buffer, int base)How to append to an Array in Elasticsearch using elasticsearch-py
If you are using the Official ElasticSearch Python library (Docs), and you want to create an index:
doc = { "something": "123a", "somethingelse": "456b", "timestamp": datetime.now(), "history": [] } es.index(index="someindex", doc_type="somedoctype", id="someid", body=doc)You can append items to the history each time, instead of overriding them, like this:
es.update(index="someindex", doc_type="somedoctype", id="someid", body={ "script" : { "source": "ctx._source.history.addAll(params.history)", "lang": "painless", "params" : { "history" : ["item1","item2"] } } })This uses scripted updates in Elasticsearch, for appending to an array.
How to Copy Text to the Clipboard in Python
If you need to Copy Text to the Clipboard using your Python application code, then you can do the following:
Option 1 – Using
pyperclipFirst install the
pyperclippackage, usingpip:pip install pyperclipNow you can run the following code:
import pyperclip as pc a1 = "This text will now be in your clipboard" pc.copy(a1) a2 = pc.paste() print(a2) print(type(a2))Option 2 – Using
pyperclip3This version is similar to the first option above, except it copies all the data into
bytes.How to Read a PDF file in Python
If you need to read a PDF (Portable Document Format) file in your Python code, then you can do the following:
Option 1 – Using
PyPDF2from PyPDF2 import PDFFileReader temp = open('your_document.pdf', 'rb') PDF_read = PDFFileReader(temp) first_page = PDF_read.getPage(0) print(first_page.extractText())Option 2 – Using
PDFplumberimport PDFplumber with PDFplumber.open("your_document.PDF") as temp: first_page = temp.pages[0] print(first_page.extract_text())Option 3 – Using
textractimport textract PDF_read = textract.process('document_path.PDF', method='PDFminer')How to Convert HEX to RBG in Python
If you need to convert HEX (Hexadecimal) to RGB (Red-Green-Blue) in your Python code, then you can do the following:
Option 1 – Using the
PILlibraryfrom PIL import ImageColor hex = input('Enter HEX value: ') ImageColor.getcolor(hex, "RGB")Option 2 – Using a custom solution
hex = input('Enter HEX value: ').lstrip('#') print('RGB value =', tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)))How to Refer to a Null Object in Python
If you need to refer to a Null Object in your Python code, then you can do the following.
It is important to note that Python does not have a
Nulltype, instead Python refers to not set objects or variables asNone.We can use the
iskeyword to check if an object or variable has the type ofNone.object_name = None print(object_name is None) object_name = ' some_value' print(object_name is None)How to Convert Bytearray to String in Python
If you need to convert a Bytearray to a String in Python, then you can do the following:
Option 1 – Using
bytes()b = bytearray("test", encoding="utf-8") str1 = bytes(b) print(str1)Option 2 – Using
bytearray.decode()b = bytearray("test", encoding="utf-8") str1 = b.decode() print(str1)How to get the Hostname in Python
If you need to get the Hostname in your Python application, then you can do the following:
Option 1 – Using
gethostname()import socket print(socket.gethostname())Option 2 – Using the
platformmoduleimport platform print (platform.node())Option 3 – Using
os.uname()import os hname = os.uname() print(hname)How to get the IP Address in Python
If you need to get the IP Address in your Python application, then you can do the following:
Option 1 – Using
socket.gethostname()import socket print(socket.gethostbyname(socket.gethostname()))Option 2 – Using
socket.getsockname()import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[0])Option 3 – Using the
netifacesmodulefrom netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )] print(' '.join(addresses))How to use SSH in your Python application
If you need to make an SSH connection and issues commands over SSH using your Python application, then you can do the following:
Option 1 – Using the
paramikolibraryssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)Option 2 – Using the
subprocessmodulesubprocess.check_output(['ssh', 'my_server', 'echo /*/'])Option 3 – Using the
subprocessmodulesubprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()How to Pause a Program in Python
If you need to pause the execution of your Python program, then you can do the following:
Option 1 – Using
time.sleep()import time time_duration = 3.5 time.sleep(time_duration)Option 2 – Using
input()name = input("Please enter your name: ") print("Name:", name)Option 3 – Using
os.system("pause")import os os.system("pause")How to Convert String to Double in Python
If you need to convert a String to a Double in your Python code:
Option 1 – Convert String to Double using
float()string = '1234.5678' myfloat = float(string) print(myfloat)Option 2 – Convert String to Double using
decimal.Decimal()from decimal import Decimal string = '1234.5678' myfloat = Decimal(string) print(myfloat)How to a Run Bash Command in Python
If you need to run a bash command in your Python code, then you can do the following:
Option 1 – Using
run()fromsubprocessModulefrom subprocess import PIPE comp_process = subprocess.run("ls",stdout=PIPE, stderr=PIPE) print(comp_process.stdout)Option 2 – Using
Popen()fromsubprocessModulefrom subprocess import PIPE process = subprocess.Popen("ls",stdout=PIPE, stderr=PIPE) output, error = process.communicate() print(output) process.killHow to Force Redeployment of AWS API Gateway using AWS CloudFormation
If you have an AWS API Gateway resource, and need it to force a redeployment using CloudFormation, then you can use the
TIMESTAMPtrick.Example AWS CloudFormation Extract
template.yamlextract:APIGatewayStage: Type: AWS::ApiGateway::Stage Properties: StageName: !Sub ${EnvironmentTagName} RestApiId: !Ref APIGateway DeploymentId: !Ref APIGatewayDeployment__TIMESTAMP__ TracingEnabled: true MethodSettings: - DataTraceEnabled: true HttpMethod: "*" LoggingLevel: INFO ResourcePath: "/*" MetricsEnabled: true APIGatewayDeployment__TIMESTAMP__: Type: AWS::ApiGateway::Deployment Properties: RestApiId: !Ref APIGateway Description: !Sub ${EnvironmentTagName} Deployment __TIMESTAMP__ APIGateway: Type: AWS::ApiGateway::RestApi Properties: Name: !Ref "AWS::StackName" ...As we can see, on line 15 above, we use the
__TIMESTAMP__string in theAPIGatewayDeploymentstage.How to Deploy React App to S3 and CloudFront
If you would like to deploy a React App to AWS S3 and AWS CloudFront, then you can follow this guide.
The following solution creates a React App and deploys it to S3 and CloudFront using the client’s CLI.
It also chains commands so that a Reactbuild, S3syncand CloudFrontinvalidationcan occur with a single command.Code available at GitHub
https://github.com/ao/deploy-react-to-s3-cloudfront
Target Architecture
Guided Deployment Solution
Create a directory for the application:
[Solved] export ‘Switch’ (imported as ‘Switch’) was not found in ‘react-router-dom’
In
react-router-domv6,Switchis replaced by routesRoutes.You need to update the import from:
import { Switch, Route } from "react-router-dom";to:
import { Routes, Route } from 'react-router-dom';You also need to update the Route declaration from:
<Route path="/" component={Home} />to:
<Route path='/welcome' element={<Home/>} />How to List all Files/Folders/Directories in Python
If you need to list all Files, Folders, or Directories in Python code, then you can use the
listdirsmethod from theospackage.import os print(os.listdir("/path/to/directory/")How to Read a File in Python
If you need to read a file in Python, then you can use the
open()built-in function to help you.Let’s say that you have a file called
somefile.txtwith the following contents:Hello, this is a test file With some contentsHow to Open a File and Read it in Python
We can
readthe contents of this file as follows:f = open("somefile.txt", "r") print(f.read())This will print out the contents of the file.
How to Drop Columns in Pandas Only If Exists
If you have a Pandas DataFrame, and want to only drop columns if they exist, then you can do the following:
Add parameter
errorstoDataFrame.drop:errors : {‘ignore', ‘raise'}, default ‘raise'
If ‘ignore', suppress error and only existing labels are dropped.
df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore')An example of how to Ignore Errors with
.drop()df = pd.DataFrame({'row_num':[1,2], 'w':[3,4]}) df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore') print (df) w 0 3 1 4[Solved] An error occurred while calling o86.getDynamicFrame. Exception thrown in awaitResult:
If you are running a
GlueJobin AWS and get the following error:An error occurred while calling o86.getDynamicFrame. Exception thrown in awaitResult:Then you need to view the CloudWatch logs to help you pinpoint where the problem is occuring.
How to solve the Exception thrown in
awaitResultIt’s highly likely that the issue is in an expired IAM Role.
When a Role is created in IAM, the default
maximum session durationis set to1 hour.AWS CDK Commands
The AWS Cloud Development Kit (CDK) comes with a list of commands that you need to know:
cdk list (ls) Lists the stacks in the app cdk synthesize (synth) Synthesizes and prints the CloudFormation template for the specified stack(s) cdk bootstrap Deploys the CDK Toolkit staging stack; see Bootstrapping cdk deploy Deploys the specified stack(s) cdk destroy Destroys the specified stack(s) cdk diff Compares the specified stack with the deployed stack or a local CloudFormation template cdk metadata Displays metadata about the specified stack cdk init Creates a new CDK project in the current directory from a specified template cdk context Manages cached context values cdk docs (doc) Opens the CDK API reference in your browser cdk doctor Checks your CDK project for potential problems You can learn more about the CDK here: https://docs.aws.amazon.com/cdk/v2/guide/cli.html
How to Make a Java Jar File Executable
Let’s say you have a Java project as follows:
package ms.ao.something; public class MyProject { public static void main(String...args) throws Exception { System.out.println("Hello world!"); } }Now you want to build this and make it a self contained executable Jar.
If you do a
mvn clean installormvn clean package, and try and run it as follows:java -jar target/my-java-1.0-SNAPSHOT.jarYou will get the following error:
no main manifest attribute, in target/my-java-1.0-SNAPSHOT.jarHow to List All Resources in an AWS Account
If you need to see a list of all the resources in your AWS Account, then you need to look into the
Tag Editor.Step 1 – Tag Editor
Search for
Tag Editorin the navigation search at the top of the AWS Console.Select the
Resource Groups & Tag Editor.
Step 2 – Find Resources
From the left hand menu, select
Tag Editor
Step 3 – Filter your Search Requirements
From the
Regionsdrop down, selectAll regionsand then selectAll supported resource typesfrom theResource typesdrop down.Fixed size left column and fluid right column both with 100% height in CSS
If you need two (2) columns and want the left column to be a fixed size, but the right column to automatically take the remaining size of the window, then you can use the following solution.
Follow the steps below, which include some CSS and some HTML.
The CSS for our solution
html, body { height: 100%; width: 100%; padding: 0; margin: 0; } .page-wrapper { height: 100%; position: relative; } .left-column { position:fixed; /* <-- This prevents scrolling */ top:0; left:0; width:235px; height:100%; background:#090909; } .right-column { margin-left:235px; background:yellow; min-height:100%; /* <-- Allows the content to grow */ }The HTML for our solution
<div class="page-wrapper"> <div class="left-column"></div> <div class="right-column"> This is the content. </div> </div>How to Check if a Volume is Mounted in Bash
If you need to check if a volume is mounted in a Bash script, then you can do the following.
How to Check Mounted Volumes
First we need to determine the command that will be able to check.
This can be done with the
/proc/mountspath.How to Check if a Volume is Mounted in Bash
if grep -qs '/mnt/foo ' /proc/mounts; then echo "It's mounted." else echo "It's not mounted." fiHow to Check if a Volume is Mounted and Available
MNT_DIR=/mnt/foo df_result=$(timeout 10 df "$MNT_DIR") [[ $df_result =~ $MNT_DIR ]] if [ "$BASH_REMATCH" = "$MNT_DIR" ] then echo "It's available." else echo "It's not available." fiAnother way of Checking Volume Mounts
mount \ | cut -f 3 -d ' ' \ | grep -q /mnt/foo \ && echo "mounted" || echo "not mounted"How to Determine if a Bash Variable is Empty
If you need to check if a
bashvariable is empty, or unset, then you can use the following code:if [ -z "${VAR}" ];The above code will check if a variable called
VARis set, or empty.What does this mean?
Unsetmeans that the variable has not been set.Emptymeans that the variable is set with an empty value of"".What is the inverse of
-z?The inverse of
-zis-n.How to Order by File Size using the du command in Linux
If you use the
ducommand to list all the file sizes on Linux:du # or du -h # Human readableThen you would have noticed that they are not ordered by file size.
Instead you can pass that result to the
sortcommand as follows:du -h | sort -hHow to Join Multiple MySQL Tables in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.Presenting the data
let’s take two (2) tables as a demonstration for the code below.
Users– Table 1{ id: 1, name: 'Carl', fav: 254}, { id: 2, name: 'Emma', fav: 254}, { id: 3, name: 'John', fav: 255}, { id: 4, name: 'Hayley', fav:}, { id: 5, name: 'Andrew', fav:}Products– Table 2How to Limit a MySQL Query in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Limit the Result Returned from MySQL in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers LIMIT 10") myresult = mycursor.fetchall() for x in myresult: print(x)How to Start From Another Position in MySQL from Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers LIMIT 10 OFFSET 5") myresult = mycursor.fetchall() for x in myresult: print(x)How to Update a MySQL Table in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Update a MySQL Table in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = 'Stoneleigh Place' WHERE address = 'Abbey Road'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) affected")Prevent SQL Injection in your Update Clause in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = %s WHERE address = %s" val = ("Stoneleigh Place", "Abbey Road") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record(s) affected")How to Drop a MySQL Table in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Delete/Drop a MySQL Table in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "DROP TABLE customers" mycursor.execute(sql)How to Delete/Drop Only if MySQL Table Exists in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "DROP TABLE IF EXISTS customers" mycursor.execute(sql)How to Delete MySQL Records in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Delete MySQL Records in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "DELETE FROM customers WHERE address = 'The Rockies'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted")Prevent SQL Injection in MySQL queries through Python
Specify the injected variable as the second argument to the
executecommand as below.How to ORDER BY a MySQL Query in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Sort the Result of a MySQL Query in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers ORDER BY name" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)How to Change Direction of MySQL Order in Python
You can change the order of the sort by simply setting the order direction.
How to Filter WHERE MySQL Queries in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Select from MySQL with a Filter in Python
You simply specify the
WHEREclause in your SQL statement as follows:import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address ='London Road'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)How to Select and Filter Wildcard Characters in Python
To filter
wildcard characters, you combine theWHEREandLIKEkeywords, and place the%symbol where the wildcards would occur.How to Select From MySQL in Python
First, you will need the
mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.How to Select From a MySQL Table in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult: print(x)How to Select Columns From a MySQL Table in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT name, address FROM customers") myresult = mycursor.fetchall() for x in myresult: print(x)How to Fetch Only a Single Row From MySQL in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchone() print(myresult)How to Insert into a MySQL Table in Python
If you need to insert data into a MySQL table using Python, then look no further.
If you need to first learn about the
mysql.connectorand how to get this up and running, first take a look at the How to Install MySQL Driver in Python post before continuing.How do Insert into a MySQL Table in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("Andrew", "Somewhere nice") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record successfully inserted")This will insert a single row into the MySQL table.
How to Create a Primary Key for a MySQL Database in Python
You can create a Primary Key for your MySQL database in Python as follows.
First, you need to know if the Primary Key already exists.
Option 1 – The Primary Key does not Exist
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")Option 2 – The Primary Key already Exists
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")How to Create a MySQL Table in Python
If you need to create a table in a MySQL database using Python, then you can do the following.
How to Create a MySQL Table in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE people (name VARCHAR(255), address VARCHAR(255))")How to Check if a MySQL Table Exists in Python
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "yourusername", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SHOW TABLES") for x in mycursor: print(x)How to Create a MySQL Database in Python
In order to create a MySQL database in Python, you first need to initiate a connection using the
mysql.connector. You can learn about how to create a connection to MySQL here.How to Create a Database in Python
Creating a database is simple.
First, make sure you have an active connection to your database, and then set a
cursor.Once you have this, issue the
executecommand to create your database.How to Install MySQL Driver in Python
To begin using MySQL in Python, you need to do the following:
Step 1 – Install the MySQL Connector
Using
pip, we can install the MySQL Connector package:python -m pip install mysql-connector-pythonStep 2 – Test the MySQL Connector
Create a Python file and import the new package:
import mysql.connectorStep 3 – Create a Connection to the MySQL Database
Now you can create a connection to your MySQL database.
Create a file called
app.pyand place the following inside:How to Resize an AWS EBS Volume in Bash
If you need to resize an EBS volume in AWS, you can do so using
bash.Step 1 – Create a
bashfileCreate a bash file called
resize.sh:#!/bin/bash SIZE=${1:-20} INSTANCEID=$(curl http://169.254.169.254/latest/meta-data/instance-id) REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/\(.*\)[a-z]/\1/') VOLUMEID=$(aws ec2 describe-instances \ --instance-id $INSTANCEID \ --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" \ --output text \ --region $REGION) aws ec2 modify-volume --volume-id $VOLUMEID --size $SIZE while [ \ "$(aws ec2 describe-volumes-modifications \ --volume-id $VOLUMEID \ --filters Name=modification-state,Values="optimizing","completed" \ --query "length(VolumesModifications)"\ --output text)" != "1" ]; do sleep 1 done if [[ -e "/dev/xvda" && $(readlink -f /dev/xvda) = "/dev/xvda" ]] then sudo growpart /dev/xvda 1 STR=$(cat /etc/os-release) SUB="VERSION_ID=\"2\"" if [[ "$STR" == *"$SUB"* ]] then sudo xfs_growfs -d / else sudo resize2fs /dev/xvda1 fi else sudo growpart /dev/nvme0n1 1 STR=$(cat /etc/os-release) SUB="VERSION_ID=\"2\"" if [[ "$STR" == *"$SUB"* ]] then sudo xfs_growfs -d / else sudo resize2fs /dev/nvme0n1p1 fi fiStep 2 – Run the
bashfile specifying the new sizeNow that you have the bash file, you can run the
bashfile along with specifying the new size of the desired volume:How to get all checked checkboxes in Javascript
If you need to get all the checked checkboxes using Javascript, then you can do the following:
Option 1 – In a single line
const checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');Option 2 – Another one liner
const data = [...document.querySelectorAll('.mycheckboxes:checked')].map(e => e.value);Option 3 – Create a helper function
function getCheckedBoxes(checkboxName) { var checkboxes = document.getElementsByName(checkboxName); var checkboxesChecked = []; for (var i=0; i<checkboxes.length; i++) { if (checkboxes[i].checked) checkboxesChecked.push(checkboxes[i]); } } return checkboxesChecked.length > 0 ? checkboxesChecked : null; }Now you simply call the function:
How to Setup Credential Helper for AWS CodeCommit
AWS CodeCommit is a
gitcode repository service by Amazon Web Services.You will want to clone your repository and setup your remotes using
credential helper.Step 1 – Setup Credential Helper
git config --global credential.helper '!aws codecommit credential-helper $@' git config --global credential.UseHttpPath trueThis will write to your local user’s
~/.gitconfig, and the file will look something like:[credential] helper = !aws --profile CodeCommitProfile codecommit credential-helper $@ UseHttpPath = trueYou can edit this file by running the following
gitcommand:How to Flex Grid 2 Columns using CSS
If you would like to flex grid 2 columns in CSS then you need three (3)
divs.Step 1 – Set your HTML template
Create some HTML with this layout.
<div class="Parent"> <div class="child1"> <h1>Left</h1> </div> <div class="child2"> <h1>RIGHT</h1> </div> </div>Step 2 – Container Div
Create a
Parentdiv that uses the Flexbox display model..Parent { display: flex; flex-direction: row; }Step 3 – Child Divs
Create two (2) divs that are both 50% of the parent container.
How to Create a Hashtag Generator in Javascript
If you want to create a hashtag generator in Javascript, then you can do the following:
function generateHashtag(string) { if (string.trim() === '') return false; const stringWithCamelCase = string .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(''); const stringWithHashtag = `#${stringWithCamelCase.trim()}`; return stringWithHashtag.length > 140 ? false : stringWithHashtag; }How to use the Hashtag Generator
const hashtag = generateHashtag("My New Hashtag !") console.log(hashtag); // #MyNewHashtag!How to Confirm before Leaving Page in Javascript
You can implement a function to be called before the user leaves a page with Javascript as follows:
window.onbeforeunload = function(e) { return "Do you want to exit this page?"; };This is a typically solution for when you want the user to confirm their changes are saved before allowing them to close the current page in editing tools.
What are the multiples of 3 from 1 to 1000
If you need to calculate the multiples of 3, starting from 1 up until 1000, then you can use the following code:
n = 1 v = [] while n <= 1000: v.append(n) n = n + 3This will generate the list of numbers which are the multiples of 3 from 1 to 1000:
1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97, 100, 103, 106, 109, 112, 115, 118, 121, 124, 127, 130, 133, 136, 139, 142, 145, 148, 151, 154, 157, 160, 163, 166, 169, 172, 175, 178, 181, 184, 187, 190, 193, 196, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385, 388, 391, 394, 397, 400, 403, 406, 409, 412, 415, 418, 421, 424, 427, 430, 433, 436, 439, 442, 445, 448, 451, 454, 457, 460, 463, 466, 469, 472, 475, 478, 481, 484, 487, 490, 493, 496, 499, 502, 505, 508, 511, 514, 517, 520, 523, 526, 529, 532, 535, 538, 541, 544, 547, 550, 553, 556, 559, 562, 565, 568, 571, 574, 577, 580, 583, 586, 589, 592, 595, 598, 601, 604, 607, 610, 613, 616, 619, 622, 625, 628, 631, 634, 637, 640, 643, 646, 649, 652, 655, 658, 661, 664, 667, 670, 673, 676, 679, 682, 685, 688, 691, 694, 697, 700, 703, 706, 709, 712, 715, 718, 721, 724, 727, 730, 733, 736, 739, 742, 745, 748, 751, 754, 757, 760, 763, 766, 769, 772, 775, 778, 781, 784, 787, 790, 793, 796, 799, 802, 805, 808, 811, 814, 817, 820, 823, 826, 829, 832, 835, 838, 841, 844, 847, 850, 853, 856, 859, 862, 865, 868, 871, 874, 877, 880, 883, 886, 889, 892, 895, 898, 901, 904, 907, 910, 913, 916, 919, 922, 925, 928, 931, 934, 937, 940, 943, 946, 949, 952, 955, 958, 961, 964, 967, 970, 973, 976, 979, 982, 985, 988, 991, 994, 997, 1000How to Count Files in Directory on Linux
If you need to count how many files are in a directory on Linux, then you can use a combination of the
lscommand to list all the files, and thewccommand to count how many lines are printed:Option 1 – Using
wcls | wc -lYou can specify a directory as follows:
ls <directory> | wc -lOption 2 – Using
findYou can count files recursively by using the
findcommand:How to Read a File Line by Line in Java
If you need to read a file line by line in Java, then you can use one of the following three (3) options.
Option 1
You can use the
FileReaderandBufferedReaderpackages as follows:File file = new File("./your/file.txt"); try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }Option 2
You can also read the lines using
FilesandPathsas follows:How can I clear or empty a StringBuilder
You can use Java’s
StringBuilderto create and manipulateStringsas follows:StringBuilder sb = new StringBuilder(); sb.append("Some").append(" ").append("String"); System.out.println(sb.toString()); // "Some String"The following three (3) options allow you to clear or empty a StringBuilder.
Option 1 – using
setLengthsb.setLength(0);Option 2 – reinstantiating
sb = new StringBuilder();Option 3 – using
deletesb.delete(0, sb.length());How to Approve a SageMaker model in AWS CLI
Sometimes you will need to manually approve a SageMaker model package from the AWS CLI.
Step 1 – Get a list of the available packages
aws sagemaker list-model-packages --model-package-group-name "the-model-package-group"This will produce the following output:
{ "ModelPackageSummaryList": [ { "ModelPackageGroupName": "...", "ModelPackageVersion": "...", "ModelPackageArn": "the-arn-we-will-use-below", "ModelPackageDescription": "...", "CreationTime": "...", "ModelPackageStatus": "Completed", "ModelApprovalStatus": "PendingManualApproval" }, ... ] }Step 2 – Approve the model
aws sagemaker update-model-package --model-package-arn <ARN-FROM-ABOVE> --model-approval-status ApprovedHow to Assume Role across Accounts in AWS
If you need to assume role between AWS accounts, or allow an account to assume a role and use resources in another AWS account, then you need to create a role and attach the following policy.
The following two (2) steps creates a
Trust Relationshipbetween the accounts.Step 1 – In the
SourceAccount{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Resource": [ "arn:aws:iam::DESTINATION-ACCOUNT-ID:role/DESTINATION-ROLENAME" ] }] }Step 2 – In the
DestinationAccount{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::SOURCE-ACCOUNT-ID:role/SOURCE-USERNAME" }, "Action": "sts:AssumeRole" }] }How to Style an Element using Javascript
If you need to style an element using Javascript then you can use the
styleobject to support all your CSS needs.<html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").style.color = "red"; </script> <p>The paragraph above was changed by a script.</p> </body> </html>If you need to do this purely in a Javascript file itself, then:
// Get a reference to the element var myElement = document.querySelector("#p1"); // Now you can update the CSS attributes myElement.style.color = "red"; myElement.style.backgroundColor = "yellow";Note that where CSS properties would use
dashesto separate words, likebackground-color, Javascript instead uses camel casing and drops the space.How to Wait 1 Second in Javascript
If you need your Javascript code to wait one (1) second (or more) while executing, then there are a couple of ways to achieve this.
Option 1 – Creating a
delayPromisefunction delay(time) { return new Promise(resolve => setTimeout(resolve, time)); } delay(1000).then(() => console.log('ran after 1 second elapsed'));Option 2 – Using
setTimeoutsetTimeout(function(){ console.log("Ready") }, 1000);Option 3 – Using an
asyncPromiseasync function test() { console.log('start timer'); await new Promise(resolve => setTimeout(resolve, 1000)); console.log('after 1 second'); } test();Option 4 – Creating a custom
sleepfunctionfunction sleep(num) { let now = new Date(); const stop = now.getTime() + num; while(true) { now = new Date(); if(now.getTime() > stop) return; } } sleep(1000) console.log('delay 1 second');How to use forEach method in Javascript
Arrays come with a useful
forEachfunction that allows you to loop through the array.var colors = ['red', 'blue', 'green']; colors.forEach(function(color) { console.log(color); }); // red // blue // greenYou can also get the
indexin each loop as follows:const colors = ['red', 'blue', 'green']; colors.forEach((item, index)=>{ console.log(index, item) }); // 0 'red' // 1 'blue' // 2 'green'How to Remove an Element from an Array in Javascript
If you need to remove an element from an array in Javascript, then you can use one of the following five (5) options:
Option 1 – Use
spliceto remove an elementExample 1 using
splice:var colors = ["red","blue","car","green"]; var carIndex = colors.indexOf("car"); colors.splice(carIndex, 1); // colors = ["red","blue","green"]Example 2 using
splice:var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // Remove Sunday -- index 0 and Monday -- index 1 myArray.splice(0,2)Option 2 – Use
filterto remove an elementvar myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; let itemToBeRemoved = ["Sunday", "Monday"] var filteredArray = myArray.filter(item => !itemToBeRemoved.includes(item))Option 3 – Use
popto remove an elementlet dailyActivities = ['work', 'eat', 'sleep', 'exercise']; // remove the last element dailyActivities.pop(); console.log(dailyActivities); // ['work', 'eat', 'sleep'] // remove the last element from ['work', 'eat', 'sleep'] const removedElement = dailyActivities.pop(); // get removed element console.log(removedElement); // 'sleep' console.log(dailyActivities); // ['work', 'eat']Option 4 – Use
removeto remove an elementarray.remove(number);Option 5 – Change
lengthto remove elementsvar arr = [1, 2, 3, 4, 5, 6]; arr.length = 4; // [1, 2, 3, 4]How to get the Alphabet as Array in Javascript
If you need to get an array of alphabetical letters in Javascript then you can use one of the following:
Option 1 – Explicitly define the array first
const alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];Option 2 – Split a string of alphabetical characters
const alphabetArray = "abcdefghijklmnopqrstuvwxyz".split("");Option 3 – Split a string and UpperCase characters
const alphabetArrayUp = toUpperCase("abcdefghijklmnopqrstuvwxyz").split("");The Power of Two (2) Table
With the Power of Two, you can ask the following:
- How do you find the powers of 2?
- What does the power of 2 stand for?
- How much is the power of 2?
The Power of Two (2) Table (Powers of Two)
Power Value 1 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1,024 11 2,048 12 4,096 13 8,192 14 16,384 15 32,768 16 65,536 17 131,072 18 262,144 19 524,288 20 1,048,576 21 2,097,152 22 4,194,304 23 8,388,608 24 16,777,216 25 33,554,432 26 67,108,864 27 134,217,728 28 268,435,456 29 536,870,912 30 1,073,741,824 31 2,147,483,648 32 4,294,967,296 33 8,589,934,592 34 17,179,869,184 35 34,359,738,368 36 68,719,476,736 37 137,438,953,472 38 274,877,906,944 39 549,755,813,888 40 1,099,511,627,776 41 2,199,023,255,552 42 4,398,046,511,104 43 8,796,093,022,208 44 17,592,186,044,416 45 35,184,372,088,832 46 70,368,744,177,664 47 140,737,488,355,328 48 281,474,976,710,656 49 562,949,953,421,312 50 1,125,899,906,842,624 51 2,251,799,813,685,248 52 4,503,599,627,370,496 53 9,007,199,254,740,992 54 18,014,398,509,481,984 55 36,028,797,018,963,968 56 72,057,594,037,927,936 57 144,115,188,075,855,872 58 288,230,376,151,711,744 59 576,460,752,303,423,488 60 1,152,921,504,606,846,976 61 2,305,843,009,213,693,952 62 4,611,686,018,427,387,904 63 9,223,372,036,854,775,808 64 18,446,744,073,709,551,616 65 36,893,488,147,419,103,232 66 73,786,976,294,838,206,464 67 147,573,952,589,676,412,928 68 295,147,905,179,352,825,856 69 590,295,810,358,705,651,712 70 1,180,591,620,717,411,303,424 71 2,361,183,241,434,822,606,848 72 4,722,366,482,869,645,213,696 73 9,444,732,965,739,290,427,392 74 18,889,465,931,478,580,854,784 75 37,778,931,862,957,161,709,568 76 75,557,863,725,914,323,419,136 77 151,115,727,451,828,646,838,272 78 302,231,454,903,657,293,676,544 79 604,462,909,807,314,587,353,088 80 1,208,925,819,614,629,174,706,176 81 2,417,851,639,229,258,349,412,352 82 4,835,703,278,458,516,698,824,704 83 9,671,406,556,917,033,397,649,408 84 19,342,813,113,834,066,795,298,816 85 38,685,626,227,668,133,590,597,632 86 77,371,252,455,336,267,181,195,264 87 154,742,504,910,672,534,362,390,528 88 309,485,009,821,345,068,724,781,056 89 618,970,019,642,690,137,449,562,112 90 1,237,940,039,285,380,274,899,124,224 91 2,475,880,078,570,760,549,798,248,448 92 4,951,760,157,141,521,099,596,496,896 93 9,903,520,314,283,042,199,192,993,792 94 19,807,040,628,566,084,398,385,987,584 95 39,614,081,257,132,168,796,771,975,168 96 79,228,162,514,264,337,593,543,950,336 97 158,456,325,028,528,675,187,087,900,672 98 316,912,650,057,057,350,374,175,801,344 99 633,825,300,114,114,700,748,351,602,688 100 1,267,650,600,228,229,401,496,703,205,376 The Power of Two (2) Tables from 1 to 100
Below you will find the Power of Two (2) tables from 1 to 100.
How to get the Screen Width in Javascript
Javascript gives a few options to determine the screen width.
When we say
screen, we mean the browser window’s width itself.Option 1 – Using Native Javascript
Using native Javascript objects, we can find the innerWidth and innerHeight:
var w = window.innerWidth; var h = window.innerHeight;The window object also allows for:
window.screen.width // or simply screen.widthWe can write some code to tell us the width and height with fallbacks:
var win = window, doc = document, docElem = doc.documentElement, body = doc.getElementsByTagName('body')[0], x = win.innerWidth || docElem.clientWidth || body.clientWidth, y = win.innerHeight|| docElem.clientHeight|| body.clientHeight; alert(x + ' × ' + y);Option 2 – Get Width using jQuery
$(window).width()You can use this as follows:
How to Read a File in Rust
If you need to read a file in Rust, then you can use the
fspackage from the standard library:use std::fs; fn main() { let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); println!("With text:\n{}", contents); }How to Convert Array to String in Java
If you need to convert an array to a string in Java, then you could look at a solution like this:
String stringArray[] = {"Hello ", " world", " this", " is", " a", " test"}; StringBuffer sb = new StringBuffer(); for(int i = 0; i < stringArray.length; i++) { sb.append(stringArray[i]); } String str = sb.toString(); System.out.println(str);Or you could do something simple like this:
String str = String.join(",", arr);How to Join Two Strings Together in Golang
If you need to join two (2) strings together in Golang, you can do the following, using the
+concatenation operator:package main import ( "fmt") func main() { message1 := "Join Strings" message2 := "Together" result := message1 + " " + message2 fmt.Println(result) }How to Recursively Delete all Files in an AWS S3 Bucket
If you need to recursively delete all files in an AWS S3 bucket, then you can do the following:
aws s3 rm --recursive s3://your-bucket-name/foo/bar/If you only want to delete an specific object from AWS S3:
aws s3 rm s3://your-bucket-name/foo/bar/item.txtHow to Execute Linux Commands in Golang
If you want to execute linux commands in Golang, then you can use
exec.Command:cmd := exec.Command("echo", "hello world") res, _ := cmd.CombinedOutput() fmt.Println(string(res))How to Check for Prime Numbers using Golang
If you need to check for Prime Numbers in Golang, then you can use the following method:
const n = 1212121 if big.NewInt(n).ProbablyPrime(0) { fmt.Println(n, "is prime") } else { fmt.Println(n, "is not prime") }How to Raise a Number to a Power in Golang
If you need to raise a number to a power in Golang, then you can use the
math.Powfunction:package main import ( "math" ) func main() { var exponent, base float64 output := math.Pow(base, exponent) }How to get CPU Frequency in Linux
If you need to get the CPU Frequency in Linux, then you can run the following command:
watch -n.1 "grep \"^[c]pu MHz\" /proc/cpuinfo"How to Disable Warning with Python Pandas
How can python pandas disable warnings?
If you need to disable warnings with Pandas on Python, then you can use the
warningsmodule and ignore the filter as follows:import warnings warnings.filterwarnings('ignore')How to Get all Caps Alphabet as List in Python
If we take the following list:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']How do we extract only the UpperCase letters of a given word?
How to get only the Capital Letters from a String
word = 'AbcDefgHijkL' result = re.findall('([A-Z])', word) print(result) # ['A', 'D', 'H', 'L'][Solved] Error creating RDS DB Instance: IAM role ARN value is not value or does not include the required permissions for: ENHANCED_MONITORING
When you are trying to create an RDS database and you get the dreaded error message:
IAM role ARN value is invalid or does not include the required permissions for: ENHANCED_MONITORINGThen you need to make sure that you are assuming the correct service principle:
monitoring.rds.amazonaws.comYour code should look something like this:
{ "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "cloudwatch.amazonaws.com" } }, { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "monitoring.rds.amazonaws.com" } } ] }How to create an AWS Lambda in Terraform
Step 1 – Lambda Code in Python
The following code expects a python file with the contents as follows in a file called
python/script1.py:def lambda_handler(event, context): return { 'code': 200, 'message': 'Triggered' }Step 2 – Lambda Code in Terraform
Now we create the
lambda.tf:data "archive_file" "zip_python_code_create" { type = "zip" source_file = "python/script1.py" output_path = "python/script1.zip" } resource "aws_lambda_function" "lambda_script1" { filename = "python/script1.zip" function_name = "LambdaScript1" role = aws_iam_role.lambda_role.arn description = "LambdaScript1" handler = "create.lambda_handler" runtime = "python3.8" depends_on = [aws_iam_role_policy_attachment.attach_iam_policy_to_iam_role] }Step 3 – IAM and Permissions in Terraform
We need to specify the permissions for the Lambda:
[Solved] Instance Profile already exists in Terraform
If you get the
Instance Profile already existserror when running your Terraformapply, then it is either because an instance profile with that name already existed in the account, or because the previousterraform destroydid not remove it.Step 1 – Identify the Instance Profiles in the account
aws iam list-instance-profilesStep 2 – Delete the Instance Profile/s
aws iam delete-instance-profile --instance-profile-name <name-of-instance-profile>[Solved] An error occurred (UnauthorizedException) when calling ListAccounts operation: Session token not found or invalid
If you are using
aws configure ssoto populate your~/.aws/credentialsfile and you get the following error when you try and reauthorize, then you can solve this problem as follows:An error occurred (UnauthorizedException) when calling ListAccounts operation: Session token not found or invalidStep 1 – Logout from SSO
aws sso logoutStep 2 – Reconfigure SSO with previous defaults
aws configure ssoHow to Match Multiple Strings with grep
If you need to match a string in a file, then
grepis your friend.An example of using
grepLet’s take a file called
somefile.txtthis is a test that looks for somethingWe can look for the string
somethingin this file usinggrep:cat somefile.txt | grep something # somethingBut what if we want to look for both
somethingandthis?An example of using multiple
grepsIt’s pretty easy, we just pass the
-Eflag, which is short for--extended-regexp, and separate our strings with a pipe|.How to Invoke an AWS Lambda from the CLI
If you want to invoke an AWS Lambda from your CLI, then the best option is to have the AWS CLI installed.
Getting started with the AWS CLI – AWS Command Line Interface (amazon.com)
Once this is installed, you can invoke Lambdas as follows:
Setting your AWS Region
It is recommended to always set your AWS region in an environment variable called
AWS_REGIONexport AWS_REGION=eu-west-1Option 1 – Recommended with AWS CLI v2
aws lambda invoke --function-name YourFunction --region ${AWS_REGION} --cli-binary-format raw-in-base64-out --payload '{"keyName":"keyValue"}' response.jsonOption 2 – If you need to use AWS CLI v1
aws lambda invoke --function-name YourFunction --region ${AWS_REGION} --payload $(echo '{"keyName":"keyValue"}') response.jsonLogging
We specified a
response.jsonat the end of the above commands. This is to get the output from the Lambda run.How to Exit if a Bash Variable in Not Set
Sometimes you might want to exit a command if a variable is not set in Bash.
You can do this as follows:
if [ -z "$VARIABLE_NAME" ]; then echo "VARIABLE_NAME is not set"; exit 1; fiHow to Force Gitlab pipeline to fail on condition
if you have a conditional in your Gitlab pipeline stage that checks if something has succeeded or failed, then you can use this to pass or fail your pipeline stage.
Option 1 – Fail on String Found
if cat log.txt | grep "Failure Summary" ; then exit 1 ; else exit 0 ; fiThis will fail the pipeline if it find a string matching
Failure Summaryin a file calledlog.txtin the current stage.How to run AWS CLI commands based on AWS CLI Version in Bash
If you find yourself having the requirements to support both AWS CLI v1 and v2 simultaneously, then you can use the following conditional in Bash to only run the specific version required:
AWS_VERSION=$(aws --version | gawk '{print $1}' | gawk -F/ '{print $2}' | gawk -F. '{print $1}') if [ AWS_VERSION == "1" ] then aws lambda invoke --function-name YourFunction --payload $(echo '{"k":"v"}') response.json else aws lambda invoke --function-name YourFunction --cli-binary-format raw-in-base64-out --payload '{"k":"v"}' response.json fiThis can be useful for deploying to environments where you cannot guarantee the AWS CLI version installed. Such as distributed pipelines, or customer environments.
[Solved] Unknown options: –cli-binary-format AWS CLI
If you have tried calling the AWS CLI and got the following error:
Unknown options: --cli-binary-formatThen it is because you are using the
AWS CLI v1and should be using the newerAWS CLI v2.Another error that you will see along with this is:
An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could not parse request body into json: Could not parse payload into json: Unrecognized token 'eyJwYXRoIjoiJEdMAAAAIgfQo': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')An example that fails on AWS CLI v1
aws lambda invoke --function-name YourFunction --cli-binary-format raw-in-base64-out --payload '{"yourKey":"yourValue"}'How to fix this error on AWS CLI v1
aws lambda invoke --function-name YourFunction --region eu-west-1 --payload '{"yourKey":"yourValue"}' response.jsonHow to fix this error by Upgrading to AWS CLI v2
You can follow the guide directly to upgrade your CLI from v1 to v2 here Migrating from AWS CLI version 1 to version 2 – AWS Command Line Interface (amazon.com)
How to Generate Random Strings with Dash in-between in Python
If you need to generate a random string that looks something like this:
VUNBXJ-230411, then you can use the following random generator:import random, string def generate_random_string_with_dash(): rand = "{0}-{1}".format(''.join(random.choice(string.ascii_uppercase) for x in range(6)), ''.join(random.choice(string.digits) for x in range(6))) return randYou simply call the above as follows:
print( generate_random_string_with_dash() ) # JJXFNS-420809If you need to adjust the length of string A and B, then you can change the value in the
rangeabove from something other than6.How to Check OS version and flavor in Linux
If you need to check the version and flavour of the running Linux instance, then you can try the below commands:
cat /etc/os-release lsb_release -a hostnamectlHow to use a Backend-Config File for Terraform S3 State Configuration
If you are using S3 as the backend for your state management in Terraform, then you can create environment specific configuration files where you store the
bucket,regionamong other things to be pulled in automatically when switching environments.Step 1 – Create environment specific configs
Create a
dev.conffile with the following content:bucket = "your-bucket" region = "your-aws-region" key = "path/to/key"Step 2 – Set the
terraformbackendIn your
main.tf,providers.tforstate.tffile, specify the following:How to Refresh State in Terraform
Sometimes your infrastructure may be out of sync with your Terraform state because resources may have been amended or deleted manually.
For this you can
refreshthe Terraform state.Using the
refreshcommandterraform refresh [options]Why this command may appear strange at first, not that it is merely an alias for:
terraform apply -refresh-only -auto-approveIf you don’t want to
auto-approvethe transaction, then you can perform a refresh as follows:How to get the Length of an Array in C
There isn’t really a standard way to get the length of array in C. This means you need to do some additional work to achieve getting the length of an array when using C.
Creating and Looping through an Array in C
Usually you would create an array as follows:
int items[5] = {1, 2, 3, 4, 5};You could always define the size right off the bat:
const int SIZE = 5; int items[SIZE] = {1, 2, 3, 4, 5};This way if you need to loop through the array later on, you can use your
SIZEvariable.How to write If/Else Statements in Terraform
If/Elsestatements are conditional statements that perform decisions based on some known state, or variable.Terraform allows you to perform these if/else statements using a
ternary operationwhich have become popular as short-form if/else statements in many programming languages.Where a language would write something similar to:
let truthy = false if (something == "value") { truthy = true } else { truthy = false }The ternary alternative would be:
How to Reset Udemy Progress
If you need to redo a Udemy course and you would like to reset the course’s progress, then you can use the following Javascript snippet below.
You have to do this manually because Udemy does not provide native functionality to do this.
Step 1 – Navigate to Udemy in a web browser
Make sure you are on the course content page you would like to reset.
Step 2 – Open up the developer tools
You will need to run a Javascript snippet, so press the following keyboard shortcuts, or right-click and select
Inspect:How to Get Last Digit of a Large Number in C
The challenge
Define a function that takes in two non-negative integers aa_a_ and bb_b_ and returns the last decimal digit of aba^b_a__b_. Note that aa_a_ and bb_b_ may be very large!
For example, the last decimal digit of 979^797 is 999, since 97=47829699^7 = 478296997=4782969. The last decimal digit of (2200)2300({2^{200}})^{2^{300}}(2200)2300, which has over 109210^{92}1092 decimal digits, is 666. Also, please take 000^000 to be 111.
You may assume that the input will always be valid.
[Solved] Network interface is in use by another service in AWS
If you have tried to delete a Security Group, or VPC, or various other resources and you get the dreaded
Network interface is in use by another serviceerror, then you can resolve this by deleting the resource through the API.How to delete the Network Interface (
ENI)aws ec2 delete-network-interface --network-interface-id eni-xxxxxReplace the
eni-xxxxxwith the ENI id that you are struggling to delete.How to find what services are using the
ENI#!/bin/bash vpc="vpc-xxxxxxxxxxxxx" aws ec2 describe-internet-gateways --filters 'Name=attachment.vpc-id,Values='$vpc | grep InternetGatewayId aws ec2 describe-subnets --filters 'Name=vpc-id,Values='$vpc | grep SubnetId aws ec2 describe-route-tables --filters 'Name=vpc-id,Values='$vpc | grep RouteTableId aws ec2 describe-network-acls --filters 'Name=vpc-id,Values='$vpc | grep NetworkAclId aws ec2 describe-vpc-peering-connections --filters 'Name=requester-vpc-info.vpc-id,Values='$vpc | grep VpcPeeringConnectionId aws ec2 describe-vpc-endpoints --filters 'Name=vpc-id,Values='$vpc | grep VpcEndpointId aws ec2 describe-nat-gateways --filter 'Name=vpc-id,Values='$vpc | grep NatGatewayId aws ec2 describe-security-groups --filters 'Name=vpc-id,Values='$vpc | grep GroupId aws ec2 describe-instances --filters 'Name=vpc-id,Values='$vpc | grep InstanceId aws ec2 describe-vpn-connections --filters 'Name=vpc-id,Values='$vpc | grep VpnConnectionId aws ec2 describe-vpn-gateways --filters 'Name=attachment.vpc-id,Values='$vpc | grep VpnGatewayId aws ec2 describe-network-interfaces --filters 'Name=vpc-id,Values='$vpc | grep NetworkInterfaceIdHow to Uninstall npm packages
We typically install an
npmpackage as follows:npm install <package_name>But how do we uninstall an
npmpackage?How to uninstall an npm package
This will uninstall an npm package that was installed in your project.
Just make sure to run the command from the root directory of your project.
npm uninstall <package_name>This will remove the package from the
node_modulesdirectory and will also remove the reference to it from thepackage.jsonfile.RBG Color Codes
Often you need to reference an HTML/CSS Color Code in RGB or Hex. This is known as
rgb color codes.Below is an easy-to-use table to find the appropriate RGB and Hex Color Codes.
Color Name #RRGGBB (Hex Code) R,G,B (Decimal code) maroon #800000 (128,0,0) dark red #8B0000 (139,0,0) brown #A52A2A (165,42,42) firebrick #B22222 (178,34,34) crimson #DC143C (220,20,60) red #FF0000 (255,0,0) tomato #FF6347 (255,99,71) coral #FF7F50 (255,127,80) indian red #CD5C5C (205,92,92) light coral #F08080 (240,128,128) dark salmon #E9967A (233,150,122) salmon #FA8072 (250,128,114) light salmon #FFA07A (255,160,122) orange red #FF4500 (255,69,0) dark orange #FF8C00 (255,140,0) orange #FFA500 (255,165,0) gold #FFD700 (255,215,0) dark golden rod #B8860B (184,134,11) golden rod #DAA520 (218,165,32) pale golden rod #EEE8AA (238,232,170) dark khaki #BDB76B (189,183,107) khaki #F0E68C (240,230,140) olive #808000 (128,128,0) yellow #FFFF00 (255,255,0) yellow green #9ACD32 (154,205,50) dark olive green #556B2F (85,107,47) olive drab #6B8E23 (107,142,35) lawn green #7CFC00 (124,252,0) chart reuse #7FFF00 (127,255,0) green yellow #ADFF2F (173,255,47) dark green #006400 (0,100,0) green #008000 (0,128,0) forest green #228B22 (34,139,34) lime #00FF00 (0,255,0) lime green #32CD32 (50,205,50) light green #90EE90 (144,238,144) pale green #98FB98 (152,251,152) dark sea green #8FBC8F (143,188,143) medium spring green #00FA9A (0,250,154) spring green #00FF7F (0,255,127) sea green #2E8B57 (46,139,87) medium aqua marine #66CDAA (102,205,170) medium sea green #3CB371 (60,179,113) light sea green #20B2AA (32,178,170) dark slate gray #2F4F4F (47,79,79) teal #008080 (0,128,128) dark cyan #008B8B (0,139,139) aqua #00FFFF (0,255,255) cyan #00FFFF (0,255,255) light cyan #E0FFFF (224,255,255) dark turquoise #00CED1 (0,206,209) turquoise #40E0D0 (64,224,208) medium turquoise #48D1CC (72,209,204) pale turquoise #AFEEEE (175,238,238) aqua marine #7FFFD4 (127,255,212) powder blue #B0E0E6 (176,224,230) cadet blue #5F9EA0 (95,158,160) steel blue #4682B4 (70,130,180) corn flower blue #6495ED (100,149,237) deep sky blue #00BFFF (0,191,255) dodger blue #1E90FF (30,144,255) light blue #ADD8E6 (173,216,230) sky blue #87CEEB (135,206,235) light sky blue #87CEFA (135,206,250) midnight blue #191970 (25,25,112) navy #000080 (0,0,128) dark blue #00008B (0,0,139) medium blue #0000CD (0,0,205) blue #0000FF (0,0,255) royal blue #4169E1 (65,105,225) blue violet #8A2BE2 (138,43,226) indigo #4B0082 (75,0,130) dark slate blue #483D8B (72,61,139) slate blue #6A5ACD (106,90,205) medium slate blue #7B68EE (123,104,238) medium purple #9370DB (147,112,219) dark magenta #8B008B (139,0,139) dark violet #9400D3 (148,0,211) dark orchid #9932CC (153,50,204) medium orchid #BA55D3 (186,85,211) purple #800080 (128,0,128) thistle #D8BFD8 (216,191,216) plum #DDA0DD (221,160,221) violet #EE82EE (238,130,238) magenta / fuchsia #FF00FF (255,0,255) orchid #DA70D6 (218,112,214) medium violet red #C71585 (199,21,133) pale violet red #DB7093 (219,112,147) deep pink #FF1493 (255,20,147) hot pink #FF69B4 (255,105,180) light pink #FFB6C1 (255,182,193) pink #FFC0CB (255,192,203) antique white #FAEBD7 (250,235,215) beige #F5F5DC (245,245,220) bisque #FFE4C4 (255,228,196) blanched almond #FFEBCD (255,235,205) wheat #F5DEB3 (245,222,179) corn silk #FFF8DC (255,248,220) lemon chiffon #FFFACD (255,250,205) light golden rod yellow #FAFAD2 (250,250,210) light yellow #FFFFE0 (255,255,224) saddle brown #8B4513 (139,69,19) sienna #A0522D (160,82,45) chocolate #D2691E (210,105,30) peru #CD853F (205,133,63) sandy brown #F4A460 (244,164,96) burly wood #DEB887 (222,184,135) tan #D2B48C (210,180,140) rosy brown #BC8F8F (188,143,143) moccasin #FFE4B5 (255,228,181) navajo white #FFDEAD (255,222,173) peach puff #FFDAB9 (255,218,185) misty rose #FFE4E1 (255,228,225) lavender blush #FFF0F5 (255,240,245) linen #FAF0E6 (250,240,230) old lace #FDF5E6 (253,245,230) papaya whip #FFEFD5 (255,239,213) sea shell #FFF5EE (255,245,238) mint cream #F5FFFA (245,255,250) slate gray #708090 (112,128,144) light slate gray #778899 (119,136,153) light steel blue #B0C4DE (176,196,222) lavender #E6E6FA (230,230,250) floral white #FFFAF0 (255,250,240) alice blue #F0F8FF (240,248,255) ghost white #F8F8FF (248,248,255) honeydew #F0FFF0 (240,255,240) ivory #FFFFF0 (255,255,240) azure #F0FFFF (240,255,255) snow #FFFAFA (255,250,250) black #000000 (0,0,0) dim gray / dim grey #696969 (105,105,105) gray / grey #808080 (128,128,128) dark gray / dark grey #A9A9A9 (169,169,169) silver #C0C0C0 (192,192,192) light gray / light grey #D3D3D3 (211,211,211) gainsboro #DCDCDC (220,220,220) white smoke #F5F5F5 (245,245,245) white #FFFFFF (255,255,255) How to Sum the Two Lowest Positive Integers in C++
The challenge
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like
[19, 5, 42, 2, 77], the output should be7.[10, 343445353, 3453445, 3453545353453]should return3453455.The solution in C++
Option 1:
#include <algorithm> #include <vector> long sumTwoSmallestNumbers(std::vector<int> numbers) { std::sort(numbers.begin(), numbers.end()); return (long)numbers[0] + (long)numbers[1]; }Option 2:
How to Sort an Array of Objects by Property in Javascript
If you need to sort an array of objects by their property values using Javascript, then you don’t need to look further than the built-in
sortfunctionality.Step 1 – Create an array of objects to work with
let people = [ { name : "John", surname : "Doe", age : 21 }, { name : "Jack", surname : "Bennington", age : 35 }, { name : "Jane", surname : "Doe", age : 19 } ];Step 2 – Sort by keys
Option 1 – Sort by surname
people.sort((a, b) => a.surname.localeCompare(b.surname)); console.log(people);This will give you the following output:
How to create a Countdown Timer in Python
If you need to count down a specific amount of time, say for example, when a token is set to expire, then a countdown timer will be useful.
Step 1 – Writing the Python code
Place the following Python code in a file called
countdowntimer.pyOption 1 – Text output
import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 print('Countdown time has elapsed!!') t = input("Enter the time in seconds: ") countdown(int(t))Option 2 – Text and speech output
Here we also invoke
saywhich speaks out the text. This is only native to some operating systems.How to Remove a Resource from Terraform State
Terraform
statereflects the most up to date reference of the infrastructure.Sometimes you may need to remove a resource from the Terraform state manually. This is helpful if a resource has been deleted or modified manually and the resource definition has been removed in your Terraform code. This way you can re-run your Terraform plan and apply without deleting the remote infra resource that you removed from the state.
How to Delete a Specific Resource in Terraform
Running
terraform destroywill tear down the whole stack associated to some terraform code.However, sometimes you might only want to remove a specific piece of your infrastructure.
To do this, you can use the
terraform destroy -targetobject.Step 1 – List the State
Get a list of all the resources from the state:
terraform state list #data.aws_ami.webserver_ami #aws_autoscaling_group.asg-web[0] #random_string.rand3 #...Step 2 – Remove a Specific Resource
Run a
terraform destroy -targetand pass a resource from thestate listabove:How to Create a DynamoDB Lock Table for Terraform
Provision the DynamoDB Table
resource "aws_dynamodb_table" "dynamodb-terraform-state-lock" { name = "terraform-state-lock-dynamo" hash_key = "LockID" read_capacity = 20 write_capacity = 20 attribute { name = "LockID" type = "S" } }Configure the DynamoDB table in Terraform Backend
terraform { backend "s3" { encrypt = true bucket = "your-unique-bucket-name" dynamodb_table = "terraform-state-lock-dynamo" key = "terraform.tfstate" region = "us-east-1" } }How to add Comments in Terraform
Terraform, a powerful Infrastructure as Code (IaC) tool, allows you to define and provision infrastructure resources. Properly commenting your Terraform code is essential for maintaining readability and sharing insights with your team. In this comprehensive guide, we’ll explore various methods to add comments in Terraform and address common questions related to Terraform syntax and best practices.
Adding Comments in Terraform
1. # - Single Line Comment
The
#symbol marks the beginning of a single-line comment in Terraform. Anything following#on the same line is considered a comment.How to log/debug in Terraform
If you have Terraform reporting an error but want more information, then you can configure debug logging.
How to configure Bash
export TF_LOG="TRACE" export TF_LOG_PATH="terraform.txt"How to configure PowerShell
$env:TF_LOG="TRACE" $env:TF_LOG_PATH="terraform.txt"How to find the number of trailing zeros of N in Rust
The challenge
Write a program that will calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * ... * NBe careful
1000!has 2568 digits…For more info, see: http://mathworld.wolfram.com/Factorial.html
Examples
zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 # 12! = 479001600 --> 2 trailing zerosThe solution in Rust
Option 1:
How to do RGB To Hex Conversion in Rust
The challenge
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 – 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
How to Rename a Git Branch
If you want to rename a git branch, then you have a few options, dependent on the use-case.
Option 1 – Rename a Git Branch
git branch -a <oldname> <newname>Option 2 – Rename the Current Branch
git branch -m <newname>Option 3 – On Windows
Windows required a capital “-M” instead.
git branch -M <newname>Push the Local Branch and Reset the Upstream Branch
git push origin -u <newname>Delete the Old Remote Branch
git push origin --delete <oldname>How to Find the Shortest Word in C++
The challenge
Simple, given a string of words, return the length of the shortest word(s).
The string will never be empty and you do not need to account for different data types.
The solution in C++
Option 1:
int find_short(const std::string &str) { std::istringstream inp(str); std::string s; int len = -1; while (std::getline(inp, s, ' ')) if (s.length() < len) len = s.length(); return len; }Option 2:
int find_short(std::string str) { std::istringstream iss(str); std::vector<std::string> vec{ std::istream_iterator<std::string>(iss), {} }; return std::min_element(vec.begin(), vec.end(), [](const std::string& s1, const std::string& s2) { return s1.length() < s2.length(); })->length(); }Option 3:
How to Square Every Digit in C++
The challenge
You are asked to square every digit of a number and concatenate them.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer
The solution in C++
Option 1:
int square_digits(int n) { int a = 1; int m = 0; while (n > 0) { int d = n % 10; m += a * d * d; a *= d <= 3 ? 10 : 100; n /= 10; } return m; }Option 2:
How to Count Vowels in C++
The challenge
Return the number (count) of vowels in the given string.
We will consider
a,e,i,o,uas vowels for this challenge (but noty).The input string will only consist of lower case letters and/or spaces.
The solution in C++
Option 1:
#include <string> using namespace std; bool is_vowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } int getCount(const string& inputStr) { return count_if(inputStr.begin(), inputStr.end(), is_vowel); }Option 2:
How to Calculate the Sum of the Numbers in the Nth row of a Triangle in Golang
The challenge
Given the triangle of consecutive odd numbers:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ...Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input –> Output)
1 --> 1 2 --> 3 + 5 = 8The solution in Golang
Option 1:
package solution func RowSumOddNumbers(n int) int { return n * n * n }Option 2:
[Solved] Terraform Error accessing remote module registry in PowerShell
If you are using PowerShell and trying to run a
terraform init, you may get an error as follows:Error: error accessing remote module registryFailed to retrieve available versions for module ... from registry.terraform.io: Failed to request discovery document: Get "https://registry.terraform.io/.well-known/terraform.json": read tcp x.x.x.x:xxxx->x.x.x.x: wsarecv: An existing connection was forcibly closed by the remote host..Note that you will still be able to make a successful
curlrequest, butterraformwill fail!How to Recursively Delete a Directory in PowerShell
If you want to recursively delete a directory/folder using PowerShell, then you have 2 options.
Option 1 – With
LiteralPathandForceRemove-Item -LiteralPath "myFolder" -Force -RecurseOption 2 – With implicit and
RecurseRemove-Item myFolder/* -Recurse[Solved] npm ERR! could not determine executable to run
If you get the following message, then there’s a very easy fix:
npm ERR! could not determine executable to runThe solution – using
npmrm -rf .git/hooks npm installThe solution – using
yarnrm -rf .git/hooks yarn install[Solved] npm ERR! path node_modules/node-sass
If you get the following error and need a solution, then look no further!
npm ERR! code 1 npm ERR! path ./node_modules/node-sass npm ERR! command failed npm ERR! command sh -c node scripts/build.js npm ERR! gyp verb cli './node_modules/node-gyp/bin/node-gyp.js', npm ERR! gyp verb cli 'rebuild', npm ERR! gyp verb cli '--verbose',Option 1 – With
npmFirst, remove the
node-sassdependency from yourpackage.json, then:npm install npm i sass npm startOption 2 – With
yarnFirst, remove the
node-sassdependency from yourpackage.json, then:How to Install Lodash through Yarn for React
You can install
lodashthroughyarnas follows:Step 1 – Install Lodash to get the Library
yarn add lodashStep 2 – Get the Typescript info
yarn add --dev @types/lodashHow to SHA256 a String in Golang
If you need to SHA256 a String in Go, then you can use the
crypto/sha256package.SHA256 a String in Go
package main import ( "crypto/sha256" "fmt" ) func main() { s := "A sample string to SHA256!" h := sha256.New() h.Write([]byte(s)) bs := h.Sum(nil) fmt.Println(s) fmt.Printf("%x\n", bs) }The output will look like this:
A sample string to SHA256! 9abf637c7e39cc4ef84d6d92cf7ffe168dc922b8ae666260d907e0353865ce89How to Base64 Encode/Decode in Golang
Go ships with an
encoding/base64package that allows for encode and decoding of Base64 strings.Import the base64 package and then start using it!
Base64 encode/decode a string
package main import ( b64 "encoding/base64" "fmt" ) func main() { // define a string data := "This is a test string!" // Encode to Base64 sEnc := b64.StdEncoding.EncodeToString([]byte(data)) fmt.Println(sEnc) // Decode from Base64 sDec, _ := b64.StdEncoding.DecodeString(sEnc) fmt.Println(string(sDec)) // URL Encode uEnc := b64.URLEncoding.EncodeToString([]byte(data)) fmt.Println(uEnc) // URL Decode uDec, _ := b64.URLEncoding.DecodeString(uEnc) fmt.Println(string(uDec)) }How to Base64 Encode a String in Java
Quick solution
In short, you can just do this:
new String(Base64.getEncoder().encode(bytes));Examples and an explanation
In Java 8 and above, you just need to import the Base64 class:
import java.util.Base64;Then use the Base64 static methods as follows:
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes()); System.out.println("encodedBytes " + new String(encodedBytes)); byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes); System.out.println("decodedBytes " + new String(decodedBytes));If you want to directly encode a string and get the result as an encoded string:
String encodeBytes = Base64.getEncoder() .encodeToString(("Your String").getBytes());How to add a Lambda Environment Variable in Terraform
If you have an
aws_lambda_functionblock that needs to make use of environment variables, then you can simply do the following:resource "aws_lambda_function" "test_lambda" { filename = "lambda_function_payload.zip" function_name = "lambda_function_name" runtime = "python3.9" ... environment { variables = { api_key = "secret-key" } } }The above example creates an environment variable called
api_keywith a value ofsecret-keyHow to perform Array Element Parity in Golang
The challenge
You will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer.
Examples:
[1, -1, 2, -2, 3] => 33has no matching negative appearance[-3, 1, 2, 3, -1, -4, -2] => -4-4has no matching positive appearance[1, -1, 2, -2, 3, 3] => 3How to Reverse Letters in Kotlin
The challenge
Given a string
str, reverse it omitting all non-alphabetic characters.Examples:
For
str = "krishan", the output should be"nahsirk".For
str = "ultr53o?n", the output should be"nortlu".Input/Output:
[input]stringstr
A string consists of lowercase Latin letters, digits, and symbols.
[output]a string
The solution in Kotlin
Option 1:
fun reverseLetter(str: String): String { return str.filter(Char::isLetter).reversed() }Option 2:
fun reverseLetter(str: String) = str.reversed().filter{ it.isLetter() }Option 3:
How to Get the ASCII Value of Character in Kotlin
The challenge
Get the ASCII value of a character.
The solution in Kotlin
Option 1:
val getAscii = Char::toIntOption 2:
fun getAscii(c: Char) = c.codeOption 3:
fun getAscii(c: Char): Int { return c.code.toByte().toInt() }Test cases to validate our solution
import kotlin.test.assertEquals import org.junit.Test class TestExample { @Test fun `Basic tests`() { assertEquals(65, getAscii('A')) assertEquals(32, getAscii(' ')) assertEquals(33, getAscii('!')) } }How to update each dependency in package.json to the latest version
You have 2 options:
Option 1 – Recommended (Using
npx)npx npm-check-updates -u npm installOption 2 – Older way (Using
npm globally)npm i -g npm-check-updates ncu -u npm installHow to Convert IPv4 to int32 in Javascript
The challenge
Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits).
- 1st octet 128 has the binary representation: 10000000
- 2nd octet 32 has the binary representation: 00100000
- 3rd octet 10 has the binary representation: 00001010
- 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.
How to Solve the Grouped by Commas Challenge in Javascript
The challenge
Finish the solution so that it takes an input
n(integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.Assume:
0 <= n < 2147483647Examples:
1 -> "1" 10 -> "10" 100 -> "100" 1000 -> "1,000" 10000 -> "10,000" 100000 -> "100,000" 1000000 -> "1,000,000" 35235235 -> "35,235,235"The solution in Javascript
Option 1:
function groupByCommas(n) { return n.toLocaleString() }Option 2:
How to Save sed Output Directly to a File
You have 3 options here:
Option 1: use
teewith sedsed 's/Hello/Hi/g' file-name | tee fileOption 2: use
>with sedsed 's/Hello/Hi/g' file-name > fileOption 3: use
sedwith-ioptionsed -i 's/Hello/Hi/g' file-nameHow to Convert BigNumber to Int/Number in Ethers/Web3
If you have a
BigNumberwhen usingweb3, then you can convert this to a regular JavascriptNumberusing theetherslibrary as follows:ethers.BigNumber.from(max).toNumber()<a href="https://github.com/ethers-io/ethers.js/" target="_blank" rel="noreferrer noopener nofollow">Ethers</a>is a complete Ethereum library and wallet implementation in Javascript.How to Create a Pyramid Array in Javascript
The challenge
Write a function that when given a number >= 0, returns an Array of ascending length subarrays.
pyramid(0) => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]Note: the subarrays should be filled with
1sThe solution in Javascript
Option 1:
function pyramid(n) { const res = []; for(let i = 0; i < n; i++){ res.push([...Array(i+1)].fill(1)) } return res; }Option 2:
How to Create a Reverse Polish Notation Calculator in Javascript
The challenge
Your job is to create a calculator which evaluates expressions in Reverse Polish notation.
For example expression
5 1 2 + 4 * + 3 -(which is equivalent to5 + ((1 + 2) * 4) - 3in normal notation) should evaluate to14.For your convenience, the input is formatted such that a space is provided between every token.
The empty expression should evaluate to ``.
How to declare a global variable in React?
If you need to declare a global variable in React, then you can do the following:
Create a file called
config.jsmodule.exports = global.config = { something: { somethingelse: { amount: 123, name: "Andrew" } } };Then import the config file where you need it:
import './config';Then where you need it in your code:
global.config.something.somethingelse.amountor
global.config.something.somethingelse.nameHow to Find the Missing Term in an Arithmetic Progression in Javascript
The challenge
An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers that have been given to you. The rest of the given series is the same as the original AP. Find the missing term.
How to Count Characters in a Javascript String
The challenge
The main idea is to count all the occurring characters in a string. If you have a string like
aba, then the result should be{'a': 2, 'b': 1}.What if the string is empty? Then the result should be an empty object literal,
{}.The solution in Javascript
Option 1:
function count (string) { var count = {}; string.split('').forEach(function(s) { count[s] ? count[s]++ : count[s] = 1; }); return count; }Option 2:
How to Increment/Decrement a value in React/NextJS
Use the following code block to get started:
function GetCount() { const [count, setCount] = useState(1); const incrementCounter = () => { setCount(count+1) } const decrementCounter = () => { if (count>1) setCount(count-1) } return <div className="_counterWrapper"> <span className="_dec" onClick={() => decrementCounter()}>-</span> <span className="_val">{count}</span> <span className="_inc" onClick={() => incrementCounter()}>+</span> </div> }Then in your HTML code, add it like this:
<GetCount />How to disable text selection highlighting in CSS
If you would like to disable the text selection highlighting that is enabled by default on all browsers, then you can do this:
user-select: none;If you are concerned about cross-browser support, then use this class:
.noselect { -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Safari */ -khtml-user-select: none; /* Konqueror HTML */ -moz-user-select: none; /* Old versions of Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */ }You can then use it like this:
Irreducible Sum of Rationals in Golang
The challenge
You will have a list of rationals in the form:
lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]where all numbers are positive integers. You have to produce their sum
N / Din an irreducible form: this means thatNandDhave only1as a common divisor.Return the result in the form:
"N/D"If the result is an integer (
Devenly dividesN) return:"n"How to copy S3 objects between AWS accounts
In your source account create a
customer-managed policy:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetObject" ], "Resource": [ "arn:aws:s3:::source-EXAMPLE-BUCKET", "arn:aws:s3:::source-EXAMPLE-BUCKET/*" ] }, { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::destination-EXAMPLE-BUCKET", "arn:aws:s3:::destination-EXAMPLE-BUCKET/*" ] } ] }In your destination bucket, update the
bucket policy:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::1234567890:user/Andrew" }, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::destination-EXAMPLE-BUCKET/*", "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } } }, { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::1234567890:user/Andrew" }, "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::destination-EXAMPLE-BUCKET" } ] }Testing the S3 copy between accounts:
How to find all symlinks in a directory tree on Mac
If you need to recursively find all symbolic links in a directory tree on a Mac, then you have a couple of options.
You could be trying to find them because a tool like Dropbox is consuming high CPU and you need to remove them, or perhaps you want to move a directory to another machine or network drive and verifying a package is required.
Option 1 – View all files that are symlinks
ls -lR . | grep ^lOption 2 – View all symlink-files as absolute paths
find . -type l -lsHow to Install App Mesh on AWS EKS
You can follow the steps below to install App Mesh on AWS EKS (Kubernetes).
Step 1 – Prerequisites
curl -o pre_upgrade_check.sh https://raw.githubusercontent.com/aws/eks-charts/master/stable/appmesh-controller/upgrade/pre_upgrade_check.sh sh ./pre_upgrade_check.shStep 2 – Add Helm Repo
helm repo add eks https://aws.github.io/eks-chartsStep 3 – Add Custom Resource Definitions (CRDs)
kubectl apply -k "https://github.com/aws/eks-charts/stable/appmesh-controller/crds?ref=master"Step 4 – Create a Namespace for App Mesh
kubectl create ns appmesh-systemStep 5 – Set Environment Variables
You will need to set a couple of environment variables to make things easier later.
[Solved] Kubernetes Namespace stuck in Terminating state
If you have tried to delete a Kubernetes namespace, and it has been hanging in ‘deleting’ for hours on end, it’s likely that you have dangling resources that have not deleted yet.
$ kubectl get ns NAME STATUS AGE apps Active 2d19h default Active 3d8h my-apps Terminating 11hThis will prevent the namespace from being removed.
How to find resources that need to be deleted
You can chain the
api-resourcesverbs along with akubectl getto find dangling resources:[Solved] Error creating: pods “my-service-a-xxx” is forbidden: error looking up service account my-apps/my-service-a: serviceaccount “my-service-a” not found
So you’ve run a
deploymentand tried to check thepodsand there’s nothing there!kubectl get podsNext step is to see what’s happening with the
replicasetkubectl get rsThen take the replicaset name and do a
describeon it:kubectl describe rs my-service-a-5549cbc6c8The error
Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning FailedCreate 2m10s.. replicaset-controller Error creating: pods "my-service-a-5549cbc6c8-" is forbidden: error looking up service account my-apps/my-service-a: serviceaccount "my-service-a" not foundIt’s down to a missing Service Account!
[Solved] error: src refspec main does not match any
If you get the following error:
error: src refspec main does not match any error: failed to push some refs to 'https://github.com/ao/xxx.git'This is because you probably haven’t committed any files to git yet!
Fix for:
src refspec main does not match anyMake sure to add your files, if they have not been added yet:
git add .Commit your files:
git commit -m "your commit message"Push your changes to the git repo, remember to swap out the branch name as appropriate:
How to Force a Redeploy in Kubernetes
If you need to force a redeploy of a deployment in Kubernetes, then you can use the
rolloutfeature.You may have an image that has been updated, but without changing the tag/version.
Step 1 – Optionally update the
imagePullPolicyIf you have not changed the image version, then check your
imagePullPolicy.In your
deployment.yamlfile:containers: - name: backend image: aoms/mock_backend_python:latest imagePullPolicy: AlwaysStep 2 – Get the deployment name
kubectl get deployStep 3 – Force the Redeployment
kubectl rollout restart deploy backendHow to Print to stdout in Flask using Python
If you are trying to
print()to the console/stdout in your Flask app, but nothing is happening, then you just need toflushyour prints, as follows:print('This will print', flush=True)How to Restart a Deployment in Kubernetes
If you need to restart a deployment in Kubernetes, perhaps because you would like to force a cycle of pods, then you can do the following:
Step 1 – Get the deployment name
kubectl get deploymentStep 2 – Restart the deployment
kubectl rollout restart deployment <deployment_name>How to push multiple Dockerfile apps to AWS ECR at the same time
I have a parent directory containing multiple sub-directories. Each of these child directories is a different application and contains a
Dockerfile.I want to build and push each image to AWS ECR.
The directory looks as follows:
├── apps ├── microservice1 ├── app.js ├── Dockerfile ├── package.json └── readiness.txt ├── frontend ├── Dockerfile ├── index.html ├── package.json ├── server.js ├── microservice2 ├── app.py ├── bootstrap.sh ├── Dockerfile └── requirements.txtNotice there are 3 apps, each with their own
Dockerfile, under the parentappsdirectory.How to Create a Horizontal Pod Autoscaler in Kubernetes
If you could like to a create a Horizontal Pod Autoscaler (
hpa) in Kubernetes, then you could run the following:Step 1 – Create a Deployment
If you already have a deployment, then ignore this step, otherwise:
kubectl create deployment php-apache --image=us.gcr.io/k8s-artifacts-prod/hpa-example kubectl set resources deploy php-apache --requests=cpu=200m kubectl expose deploy php-apache --port 80 kubectl get pod -l app=php-apacheStep 2 – Create a Horizontal Pod Autoscaler
kubectl autoscale deployment php-apache `#The target average CPU utilization` \ --cpu-percent=50 \ --min=1 `#The lower limit for the number of pods that can be set by the autoscaler` \ --max=10 `#The upper limit for the number of pods that can be set by the autoscaler`Step 3 – Get your
hpakubectl get hpaHow to Run a Load Generator on Kubernetes
If you would like to test
hpa, Horizontal Pod Autoscaling, or throw some chaos at a specific deployment in Kubernetes, then you could run a Load GeneratorStep 1 – Run a BusyBox container
The following command will use a
busyboxcontainer and dump you into it’s shell window:kubectl run -i --tty load-generator --image=busybox /bin/shAs an alternative, you could also run:
kubectl --generator=run-pod/v1 run -i --tty load-generator --image=busybox /bin/shStep 2 – Run a
wgetloopYou can now trigger a
wgetloop to make HTTP request calls to your deployment:How to Deploy a Metrics Server in Kubernetes
If you would like to deploy a Metrics Server in Kubernetes, then you first need to create a namespace for it to live it, followed by installing the actual metrics server.
Step 1 – Install the Metrics Server
Using
kubectlkubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.5.0/components.yamlUsing
helmkubectl create namespace metrics helm install metrics-server \ stable/metrics-server \ --version 2.9.0 \ --namepsace metricsStep 2 – Get the Metrics Server Status
If you used
kubectlabove, then you should be able to run:How to create an AWS EKS cluster using eksctl
eksctldramatically simplifies the creation of AWS EKS clusters, by providing a simple command-line interface.Step 1 – Define a Cluster YAML
You can either create a file called
ekscluster.yamland place the YAML in, or run the following command which will create a file calledekscluster.yamland automatically add the default YAML configuration for you.cat << EOF > ekscluster.yaml --- apiVersion: eksctl.io/v1alpha5 kind: ClusterConfig metadata: name: eksworkshop-eksctl region: ${AWS_REGION} version: "1.19" availabilityZones: ["${AZS[0]}", "${AZS[1]}", "${AZS[2]}"] managedNodeGroups: - name: nodegroup desiredCapacity: 3 instanceType: t3.small ssh: enableSsm: true # To enable all of the control plane logs, uncomment below: # cloudWatch: # clusterLogging: # enableTypes: ["*"] secretsEncryption: keyARN: ${MASTER_ARN} EOFStep 2 – Create the EKS Cluster
Tell the
eksctltool to create a new cluster using theekscluster.yaml.How to Dockerize a Flask App
If you have a Flask app that you would like packaged in a Docker container, then you can do the following. The steps outlined below will help you create the following directory tree:
└── flaskapp ├── Dockerfile ├── app.py └── requirements.txtStep 1 – Create your Flask app
In a new directory, create the following files:
app.pyfrom flask import Flask app = Flask(__name__) @app.route('/') def hello_geek(): return '<h1>Hello world!</h2>' if __name__ == "__main__": app.run(debug=True)requirements.txtHow to get an EKS Cluster name from an AWS Region
You can use the
aws clito get the EKS cluster name, parse the first result and return it into a variable.EKS_CLUSTER_NAME=$(aws eks list-clusters --region us-west-2 --query clusters[0] --output text) echo $EKS_CLUSTER_NAMEHow to automatically generate a Manifests file in Kubernetes
If you want to automatically generate a manifest file in Kubernetes, you can do so by using the
kubectl runcommand coupled with a--dry-runto output directly toyaml.kubectl run nginx --image=nginx --port=80 --replicas=2 --expose --dry-run -o yamlYou can also output this directly to a file on disk as follows:
kubectl run nginx --image=nginx --port=80 --replicas=2 --expose --dry-run -o yaml > your-deployment-manifest.yamlHow to Sort Pods by CreationTimestamp in Kubernetes
If you need to sort a list of your pods by their CreationTimestamp, then do the following:
kubectl get pods -n kube-system --sort-by=metadata.creationTimestampA better way to specify the JSON path is:
kubectl get pods -n kube-system --sort-by='{.metadata.creationTimestamp}'How to Jump onto a Kubernetes Pod with Bash
If you want to jump onto a particular Kubernetes Pod and run Bash within it, you can do so as follows:
kubectl exec -ti <pod_name> /bin/bashYou can get the
<pod_name>by runningkubectl get podsHow to run Shell Commands in a Kubernetes Cluster
If you would like to run shell commands inside of your Kubernetes cluster, then you can use the
kubectl runcommand.What the syntax looks like
kubectl run --image=<imagename> <name> -restart=Never -it --rm -- /bin/sh -c "<command>"Breaking this down, you pass in an
imagenamewhich is the container image you would like to execute the commands in, thenameof this temporary container, and thencommandyou would like to run in it.How to Bulk Move All Email from One Account to Another using the CLI
If you find yourself in a position where you need to sync all emails from one account to another, then you can use the
imapsynccommand-line tool to bulk copy, or move everything for you.Step 1 – Get
imapsyncYou need to get the
imapsynctool running locally.It can be found here https://github.com/imapsync/imapsync
Alternatively, if you are using a Mac and have homebrew installed, then you’re in luck!
How to Install AWS CLI on Linux
You can download and install the AWS CLI on Linux as follows:
Perform the install
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/installVerify the install
aws --versionHow to Reboot Networking on Mac from CLI
If you need to reboot, or restart the networking interface on your Mac, by using the CLI, then you can issue the following commands:
Using the
ifconfigprimary interfaceTear down the networking interface
sudo ifconfig en0 downRestart the networking interface
sudo ifconfig en0 upVerify the networking restart
ifconfig -u en0Alternative without
sudo, usingnetworksetupIf you need to perform the same result, but not able to run
sudo, then look to thenetworksetup.[Solved] fatal: unable to access <git>: SSL certificate problem: self signed certificate in certificate chain
If you get the following error:
fatal: unable to access <git>: SSL certificate problem: self signed certificate in certificate chain..when trying to clone a
gitrepo, then you can quickly get around it by doing one of the following.Note that both of these solutions are merely workarounds and should be done at absolute worst case.
Workaround Solution 1
Disable SSL verification while running the git clone.
git -c http.sslVerify=false clone <repository-name>Workaround Solution 2
Disable SSL verification globally while running the git clone.
How to Extract the Files in a Docker Image
Ever needed to extract the files in a Docker container?
Docker provides the
savesub-command.Exporting Docker files into a Tar Archive
The examples below use a Docker container called:
aoms/hellojavaSwap this out with your own container as required.
docker save aoms/hellojava > hellojava.tarhellojava.tarnow contains a list of files found in the Docker image.Taking it one step further
You can make this a bit better by extracting it into a new directory and untarring automatically:
[Solved] Error response from daemon: No such image: Docker
If you’ve run into this dreaded error:
Error response from daemon: No such image:Then you can solve it as follows:
Step 1
Perform a
docker pull -a <org/image>Then perform a
docker images -ato see what the version is.Step 2
This issue can occur when it is trying to map
tagtolatest, but a specific version is explicitly listed instead.docker tag <org>/<image>:v1 <new_org>/<image>Make sure to replace
:v1with the specificTAGthat was shown from thedocker imagescommand above.How to Bootstrap a Web Server on AWS EC2
When you launch an EC2 instance, you can use the
user-datato bootstrap a instance creation script.We can use the following code to start a web server and echo out it’s instance id:
#!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo "<h1>Hello World from $(hostname -f)</h1>" > /var/www/html/index.htmlSteps to create a new bootstrapped instance
Step 1 – Launch a new instance
Login to your EC2 console and click
Launch instances.How to Update Kubectl Config from AWS EKS
Ever searched for
kubectl update config from aws eksand needed a quick result?Step 1 – Validate AWS CLI
Make sure that you have valid AWS Credentials setup in your
aws cli.You can check this by typing:
aws sts get-caller-identityThis will let you know where your
aws cliis pointing to.You may need to update your
~/.aws/credentialsfile with aprofile_name,aws_access_key_id,aws_secret_access_keyandaws_session_tokenif these are generated for you by your Single Sign On (SSO).How to Generate a Random String in Java
Java provides many ways to generate random strings.
1. Using Apache Commons
public void generatingRandomAlphanumericString_ApacheCommons() { String generatedString = RandomStringUtils.randomAlphanumeric(10); System.out.println(generatedString); }2. Using Java 8
public void generatingRandomAlphanumericString_Java8() { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(generatedString); }3. Using Plain Java
public void generatingRandomStringUnbounded_PlainJava() { byte[] array = new byte[7]; // length is bounded by 7 new Random().nextBytes(array); String generatedString = new String(array, Charset.forName("UTF-8")); System.out.println(generatedString); }How to Generate a Random String in Python
Python gives the ability to generate random strings out of the box, by using a combination of the
stringandrandommodules.import string import random # How many characters do you want S = 10 # Call random.choices() string module to find the string in Uppercase + numeric data. ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S)) # Print the result print("The randomly generated string is : " + str(ran))How to Generate a Random Number/String in Terraform
If you need to generate a random number or string in Terraform, then you can use the following:
resource "random_id" "myrandom" { keepers = { first = "${timestamp()}" } byte_length = 8 }Then refer to it as:
random_id.myrandom.hex[Solved] Unable to connect to the server: dial tcp: lookup with AWS EKS
If you have received the following error while trying to issue commands to
kubectl:Unable to connect to the server: dial tcp: lookupThen it may be due to your kube-config being out of date. You might just need to update the local kube-config.
How to update the local
kube-configMake sure to replace
eu-west-1with your cluster’s region, and replacecluster_namewith the name of your EKS cluster.aws eks --region "eu-west-1" update-kubeconfig --name "cluster_name"How to update
kube-configfrom Terraform stateaws eks --region $(terraform output -raw region) update-kubeconfig --name $(terraform output -raw cluster_name)The above code makes use of the Terraform state’s output from when you generated the cluster.
How to Store Terraform State in AWS S3
Storing Terraform states files locally is not recommended. Instead you should use a
backendsuch as as S3 from AWS.To do this, you just need to add the following
backendinformation in aterraformblock in your code:terraform { backend "s3" { bucket = "mybucket" key = "path/to/my/key" region = "eu-west-1" } }[Solved] ZipArchive extension: disabled/not installed on Ubuntu
If you have come across the following error:
ZipArchive extension: <strong>disabled/not installed</strong>This just means that you are missing the
php-zipmodule.How to fix the ZipArchive extension problem
Run the following command:
sudo apt-get install -y php-zipNow restart Apache2, and you’re good!
service apache2 restartCalculating Cartesian Neighbors Distance in Golang
The challenge
We have been searching for all the neighboring points in a Cartesian coordinate system. As we know each point in a coordinate system has eight neighboring points when we search it by range equal to 1, but now we will change the range by the third argument of our function (range is always greater than zero). For example, if range
= 2, count of neighboring points= 24. In this challenge, a grid step is the same (= 1).How to Calculate Dominant Primes in Golang
The challenge
The prime number sequence starts with:
2,3,5,7,11,13,17,19.... Notice that2is in positionone.3occupies positiontwo, which is a prime-numbered position. Similarly,5,11and17also occupy prime-numbered positions. We shall call primes such as3,5,11,17dominant primes because they occupy prime-numbered positions in the prime number sequence. Let’s call thislistA.As you can see from listA, for the prime range
range(0,10), there areonly twodominant primes (3and5) and the sum of these primes is:3 + 5 = 8.[Solved] error: src refspec main does not match
When you first try and push to a
gitrepository, you may get the following error message:error: src refspec master does not match any. error: failed to push some refs to 'git@github ... .git'This is because you have not committed your files!
How to Fix
src refspec main does not matchgit commit -m "initial commit" git push origin mainThe above code will commit your files that are staged, before pushing them to your desired branch.
How to Solve Simple Square Numbers in Golang
The challenge
In this challenge, you will be given a number
n(n > 0) and your task will be to return the smallest square numberN(N > 0) such thatn + Nis also a perfect square. If there is no answer, return-1(nilin Clojure,Nothingin Haskell,Nonein Rust).solve 13 = 36 <em>; because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49</em> solve 3 = 1 <em>; 3 + 1 = 4, a perfect square</em> solve 12 = 4 <em>; 12 + 4 = 16, a perfect square</em> solve 9 = 16 solve 4 = nilThe solution in Golang
Option 1:
How to perform Function Iteration in Golang
The challenge
The purpose of this challenge is to write a higher-order function returning a new function that iterates on a specified function a given number of times. This new function takes in an argument as a seed to start the computation.
For instance, consider the function
getDouble. When run twice on value3, yields12as shown below.getDouble(3) => 6 getDouble(6) => 12Let us name the new function
createIteratorand we should be able to obtain the same result usingcreateIteratoras shown below:Determining Integer Depth in Python
The challenge
The
depthof an integernis defined to be how many multiples ofnit is necessary to compute before all10digits have appeared at least once in some multiple.Example:
let see n=42 Multiple value digits comment 42*1 42 2,4 42*2 84 8 4 existed 42*3 126 1,6 2 existed 42*4 168 - all existed 42*5 210 0 2,1 existed 42*6 252 5 2 existed 42*7 294 9 2,4 existed 42*8 336 3 6 existed 42*9 378 7 3,8 existedLooking at the above table under
digitscolumn you can find all the digits from `` to9, Hence it required9multiples of42to get all the digits. So the depth of42is9. Write a function namedcomputeDepthwhich computes the depth of its integer argument. Only positive numbers greater than zero will be passed as an input.How to Reverse a singly-linked list in Python
The challenge
Implement a function
reverse_listthat takes a singly-linked list of nodes and returns a matching list in the reverse order.Assume the presence of a class
Node, which exposes the propertyvalue/Valueandnext/Next.nextmust either be set to the nextNodein the list, or toNone(ornull) to indicate the end of the list.To assist in writing tests, a function
make_linked_list(Node.asLinkedList()in Java) has also been defined, which converts a python list to a linked list ofNode.Calculating Simple Time Difference in Python
The challenge
In this challenge, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any.
Examples:
# If the alarm goes off now, it will not go off for another 23 hours and 59 minutes. solve(["14:51"]) = "23:59" # The max interval that the alarm will not go off is 11 hours and 40 minutes. solve(["23:00","04:22","18:05","06:24"]) == "11:40"In the second example, the alarm goes off
4times in a day.Calculating Odd/Even number of divisors in Python
The challenge
Given an integer
nreturn"odd"if the number of its divisors is odd. Otherwise, return"even".Note: big inputs will be tested.
Examples:
All prime numbers have exactly two divisors (hence
"even").For
n = 12the divisors are[1, 2, 3, 4, 6, 12]–"even".For
n = 4the divisors are[1, 2, 4]–"odd".The solution in Python code
Option 1:
def oddity(n): #your code here return 'odd' if n**0.5 == int(n**0.5) else 'even'Option 2:
Calculate possibilities of throwing a coin N times in Python
The challenge
In this challenge, you will be given an integer n, which is the number of times that is thrown a coin. You will have to return an array of strings for all the possibilities (heads[H] and tails[T]). Examples:
coin(1) should return {"H", "T"}
coin(2) should return {"HH", "HT", "TH", "TT"}
coin(3) should return {"HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT"}When finished sort them alphabetically.
In C and C++ just return a
char*with all elements separated by,(without space):
coin(2) should return "HH,HT,TH,TT"How to Convert Integer to Whitespace format in Python
The challenge
Hereinafter,
[space]refers to" ",[tab]refers to"\t", and[LF]refers to"\n"for illustrative purposes. This does not mean that you can use these placeholders in your solution.In esoteric language called Whitespace, numbers are represented in the following format:
- first character represents the sign:
[space]for plus,[tab]for minus; - characters after that and until
[LF]are the binary representation of the integer:[space]for 0,[tab]for 1. - characters after that are the binary representation of the absolute value of the number, with
[space]for 0,[tab]for 1, the rightmost bit is the least significand bit, and no leading zero bits. - the binary representation is immediately followed by
[LF].
Notes
- Valid Whitespace number must always have at least two characters: a sign and the terminator. In case there are only two characters, the number is equal to zero.
- For the purposes of this challenge, zero must always be represented as
[space][LF]. - In Whitespace, only space, tabulation and linefeed are meaningful characters. All other characters are ignored. However, for the purposes of this simple challenge, please do not add any other characters in the output.
- In this challenge, input will always be a valid negative or positive integer.
- For your convenience, in this challenge we will use
unbleach()function when evaluating your results. This function replaces whitespace characters with[space],[tab], and[LF]to make fail messages more obvious. You can see how it works in Example Test Cases.
Examples
1in Whitespace is" \t\n".- `` in Whitespace is
" \n". -1in Whitespace is"\t\t\n".2in Whitespace is" \t \n".-3in Whitespace is"\t\t\t\n".
The solution in Python code
Option 1:
How to Perform Frog Jumping in Python
The challenge
You have an array of integers and have a frog at the first position
[Frog, int, int, int, ..., int]The integer itself may tell you the length and the direction of the jump
For instance:
2 = jump two indices to the right -3 = jump three indices to the left 0 = stay at the same positionYour objective is to find how many jumps are needed to jump out of the array.
How to Calculate the area of a regular N sides polygon inside a circle of radius R in Python
The challenge
Write the following function:
def area_of_polygon_inside_circle(circle_radius, number_of_sides):It should calculate the area of a regular polygon of
numberOfSides,number-of-sides, ornumber_of_sidessides inside a circle of radiuscircleRadius,circle-radius, orcircle_radiuswhich passes through all the vertices of the polygon (such a circle is called circumscribed circle or circumcircle). The answer should be a number rounded to 3 decimal places.Input/Output Examples
area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.053 area_of_polygon_inside_circle(4, 5) # returns 38.042The solution in Python code
Option 1:
How to create an Image Host Filename Generator in Python
The challenge
You are developing an image hosting website.
You have to create a function for generating random and unique image filenames.
Create a function for generating a random 6 character string that will be used to access the photo URL.
To make sure the name is not already in use, you are given access to a PhotoManager object.
You can call it like so to make sure the name is unique
How to Find the Missing Alphabets in Python
The challenge
Task
Given string
s, which contains only letters froma to zin lowercase.A set of the alphabet is given by
abcdefghijklmnopqrstuvwxyz.2 sets of alphabets mean 2 or more alphabets.
Your task is to find the missing letter(s). You may need to output them by the order a-z. It is possible that there is more than one missing letter from more than one set of alphabet.
How to move MySQL database to another drive
Step 1:
Login to your MySQL server, enter your password when prompted:
mysql -u root -pFind out where the
data directoryis located:mysql> select @@datadir;Output +-----------------+ | @@datadir | +-----------------+ | /var/lib/mysql/ | +-----------------+ 1 row in set (0.00 sec)Step 2:
Now you can stop the server and check the status:
sudo systemctl stop mysqlsudo systemctl status mysqlIt’s time to make a copy to your new mount location:
How to Find the Sum of Prime-Indexed Elements in Go
The challenge
You will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices.
The first element of the array is at index ``.
The solution in Golang
Option 1:
package solution import "math/big" func Solve(arr []int) int { c := 0 for i := 0; i < len(arr); i++ { n := arr[i] if big.NewInt(int64(i)).ProbablyPrime(0) { c += n } } return c }Option 2:
How to Find the Longest Substring in Alphabetical Order in Python
The challenge
Find the longest substring in alphabetical order.
Example:
the longest alphabetical substring in
"asdfaaaabbbbcttavvfffffdf"is"aaaabbbbctt".Overview:
There are tests with strings up to
10 000characters long so your code will need to be efficient.The input will only consist of lowercase characters and will be at least one letter long.
If there are multiple solutions, return the one that appears first.
The solution in Python
Option 1:
Calculate the Most Frequent Weekdays in Go
The challenge
What is your favourite day of the week? Check if it’s the most frequent day of the week in the year.
You are given a year as integer (e. g. 2001). You should return the most frequent day(s) of the week in that year. The result has to be a list of days sorted by the order of days in week (e. g.
['Monday', 'Tuesday'],['Saturday', 'Sunday'],['Monday', 'Sunday']). Week starts with Monday.Return Index of Matching Closing Bracket in Go
The challenge
In this challenge, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based. An opening brace will always have a closing brace. Return an error if there is no answer.
Examples:
solve("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10 solve("((1)23(45))(aB)", 1) = 3 solve("((1)23(45))(aB)", 2) = -1 // there is no opening bracket at index 2, so return -1 solve("((1)23(45))(aB)", 6) = 9 solve("((1)23(45))(aB)", 11) = 14 solve("((>)|?(*'))(yZ)", 11) = 14Input will consist of letters, numbers, and special characters, but no spaces. The only brackets will be
(and).How to Presign an S3 URL in AWS using AWS CLI
You can use the AWS CLI to presign URLs so that objects in S3 can be shared publicly even if they are set as private.
Presigned URLs are great for sharing private files in an S3 bucket
aws s3 presign s3://<bucket>/<file.jpg>This can also be coupled with an expiry duration:
aws s3 presign s3://<bucket>/<file.jpg> --expires-in 3600How to Download using Aria2c with Multiple Connections
If you use
aria2cto download files using the command-line, then you can also use it to download using multiple connections.aria2c -x16 -s16 <url>-x**, –max-connection-per-server=**
The maximum number of connections to one server for each download. Default: 1
-s**, –-split=**
Download a file using N connections. Default: 5
How to Parse HTML/CSS Colors in Java
The challenge
In this challenge, you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task is to implement a function that takes a color as a string and returns the parsed color as a map (see Examples).
Inputs:
The input string represents one of the following:
- 6-digit hexadecimal – “#RRGGBB”
e.g. “#012345”, “#789abc”, “#FFA077”
Each pair of digits represents a value of the channel in hexadecimal: 00 to FF - 3-digit hexadecimal – “#RGB”
e.g. “#012”, “#aaa”, “#F5A”
Each digit represents a value 0 to F which translates to 2-digit hexadecimal: 0->00, 1->11, 2->22, and so on. - Preset color name
e.g. “red”, “BLUE”, “LimeGreen”
You have to use the predefined mapPRESET_COLORS(JavaScript, Python, Ruby),presetColors(Java, C#, Haskell), orpreset-colors(Clojure). The keys are the names of preset colors in lower-case and the values are the corresponding colors in 6-digit hexadecimal (same as 1. “#RRGGBB”).
Examples:
Solving Simple Transposition in Java
The challenge
Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in Row 1, the second in Row 2, third in Row 1, and so on until the end. Then we put the text from Row 2 next to the Row 1 text and that’s it.
Complete the function that receives a string and encrypts it with this simple transposition.
Example:
How to Binary to Text (ASCII) Conversion in Python
The challenge
Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded).
Each 8 bits on the binary string represent 1 character on the ASCII table.
The input string will always be a valid binary string.
Characters can be in the range from “00000000” to “11111111” (inclusive)
Note: In the case of an empty binary string your function should return an empty string.
How to Find the Row of the Odd Triangle in Python
The challenge
Given a triangle of consecutive odd numbers:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ...find the triangle’s row knowing its index (the rows are 1-indexed), e.g.:
odd_row(1) == [1] odd_row(2) == [3, 5] odd_row(3) == [7, 9, 11]Note: your code should be optimized to handle big inputs.
The solution in Python code
Option 1:
def odd_row(n): m = (n - 1) * n + 1 return [*range(m, m + n * 2, 2)]Option 2:
Solving Number Zoo Patrol in Python
The challenge
Write a function that takes a shuffled list of unique numbers from
1tonwith one element missing (which can be any number includingn). Return this missing number.Note: huge lists will be tested.
Examples:
[1, 3, 4] => 2 [1, 2, 3] => 4 [4, 2, 3] => 1The solution in Python code
Option 1:
def find_missing_number(a): n = len(a) + 1 return n * (n + 1) // 2 - sum(a)Option 2:
Common AWS CDK CLI Commands
The AWS Cloud Development Kit (CDK) comes with numerous CLI commands.
Command Function cdk list (ls) Lists the stacks in the application cdk synthesize (synth) Synthesizes and prints the AWS CloudFormation template for the specified stack or stacks cdk bootstrap Deploys the AWS CDK Toolkit stack, required to deploy stacks containing assets cdk deploy Deploys the specified stacks cdk destroy Destroys the specified stacks cdk diff Compares the specified stack with the deployed stack or a local AWS CloudFormation template cdk metadata Displays metadata about the specified stack cdk init Creates a new AWS CDK project in the current directory from a specified template cdk context Manages cached context values cdk docs (doc) Opens the AWS CDK API reference in your browser cdk doctor Checks your AWS CDK project for potential problems Learn more about AWS CDK here, or read the Official Guides here.
How to Create an S3 bucket with PublicRead in CloudFormation
AWSTemplateFormatVersion: 2010-09-09 Description: Basic S3 Bucket CloudFormation template Resources: S3BucketForWebsiteContent: Type: AWS::S3::Bucket Properties: AccessControl: PublicRead Outputs: BucketName: Value: !Ref S3BucketForWebsiteContent Description: Name of the newly created Amazon S3 DistributionHow to Create a VPC in CloudFormation
It’s very easy to deploy a VPC using CloudFormation:
AWSTemplateFormatVersion: 2010-09-09 Description: Deploy a VPC Resources: VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 EnableDnsHostnames: true Tags: - Key: Name Value: Lab VPC <meta charset="utf-8">Outputs: VPC: Description: VPC Value: !Ref VPCThis will also output the created VPC resource information.
But what if you also want to create Subnets and an attached Internet Gateway?
AWSTemplateFormatVersion: 2010-09-09 Description: Deploy a VPC Resources: VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 EnableDnsHostnames: true Tags: - Key: Name Value: Lab VPC InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Name Value: Lab Internet Gateway AttachGateway: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: !Ref VPC InternetGatewayId: !Ref InternetGateway PublicSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC CidrBlock: 10.0.0.0/24 AvailabilityZone: !Select - '0' - !GetAZs '' Tags: - Key: Name Value: Public Subnet 1 PrivateSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC CidrBlock: 10.0.1.0/24 AvailabilityZone: !Select - '0' - !GetAZs '' Tags: - Key: Name Value: Private Subnet 1 PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: Public Route Table PublicRoute: Type: AWS::EC2::Route Properties: RouteTableId: !Ref PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway PublicSubnetRouteTableAssociation1: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref PublicSubnet1 RouteTableId: !Ref PublicRouteTable PrivateRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: Private Route Table PrivateSubnetRouteTableAssociation1: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref PrivateSubnet1 RouteTableId: !Ref PrivateRouteTable Outputs: VPC: Description: VPC Value: !Ref VPC AZ1: Description: Availability Zone 1 Value: !GetAtt - PublicSubnet1 - AvailabilityZoneHow to Setup Git on EC2 for AWS CodeCommit
Connect to the instance:
chmod 400 KEYPAIR.pem ssh -i KEYPAIR.pem ec2-user@EC2PublicIPInstall Git:
sudo yum install -y gitSetup Git Credential Helper:
git config --global credential.helper '!aws codecommit credential-helper $@' git config --global credential.UseHttpPath trueNow you can clone the CodeCommit repo which will look something like the following:
https://git-codecommit.us-east-1.amazonaws.com/v1/repos/My-RepoThe Difference of 2 in Java
The challenge
The objective is to return all pairs of integers from a given array of integers that have a difference of 2.
The resulting array should be sorted in ascending order of values.
Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.
Examples:
[1, 2, 3, 4] should return [[1, 3], [2, 4]] [4, 1, 2, 3] should also return [[1, 3], [2, 4]] [1, 23, 3, 4, 7] should return [[1, 3]] [4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]]The solution in Java code
Option 1:
How to Make the Deadfish Swim in Java
The challenge
Write a simple parser that will parse and run Deadfish.
Deadfish has 4 commands, each 1 character long:
iincrements the value (initially ``)ddecrements the valuessquares the valueooutputs the value into the return array
Invalid characters should be ignored.
Deadfish.parse("iiisdoso") =- new int[] {8, 64};The solution in Java code
Option 1:
import java.util.ArrayList; import java.util.List; public class DeadFish { public static int[] parse(String data) { int value = 0; List<Integer> result = new ArrayList<>(); for(char letter : data.toCharArray()) { switch(letter) { case 'i': value++; break; case 'd': value--; break; case 's': value *= value; break; case 'o': result.add(value); break; default: throw new IllegalArgumentException("Not valid code letter"); } } return result.stream().mapToInt(Integer::intValue).toArray(); } }Option 2:
How to Write Number in Expanded Form in Java
The challenge
You will be given a number and you will need to return it as a string in Expanded Form.
Examples:
Challenge.expandedForm(12); // Should return "10 + 2" Challenge.expandedForm(42); // Should return "40 + 2" Challenge.expandedForm(70304); // Should return "70000 + 300 + 4"NOTE: All numbers will be whole numbers greater than 0.
The solution in Java code
Option 1:
public class Challenge { public static String expandedForm(int num) { StringBuffer res = new StringBuffer(); int d = 1; while(num > 0) { int nextDigit = num % 10; num /= 10; if (nextDigit > 0) { res.insert(0, d * nextDigit); res.insert(0, " + "); } d *= 10; } return res.substring(3).toString(); } }Option 2:
Is a Number Prime in Java
The challenge
Define a function that takes one integer argument and returns a logical value
trueorfalsedepending on if the integer is a prime.Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Requirements:
- You can assume you will be given an integer input.
- You can not assume that the integer will be only positive. You may be given negative numbers as well (or ``).
- NOTE on performance: There are no fancy optimizations required, but still the most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to
n, orn/2, will be too slow.
Examples:
How to Calculate Minutes to Midnight in Java
The challenge
Write a function minutesToMidnight(d) that will take a date object as the parameter. Return the number of minutes in the following format:
“x minute(s)”
You will always get a date object with of today with a random timestamp.
You have to round the number of minutes.
Milliseconds don’t matter!Some examples: 10.00 am => "840 minutes" 23.59 pm => "1 minute"The solution in Java code
Option 1:
import java.util.Date; public class Minute { public String countMinutes(Date d){ int mins=(24-d.getHours()-1)*60+60-d.getMinutes(); if (d.getHours()==23 && d.getMinutes()==59) return "1 minute"; return (d.getSeconds()!=0)? ""+(mins-1)+" minutes" : ""+mins+" minutes"; } }Option 2:
How to Change the Timestamp of a File on Mac/Linux
If you have a file on your machine, and you want to change the created/modified time/date stamp, then you can use the
touch command.touch -t 202202011308.57 someFile.jpgIn the above example, the timestamp will be changed to
<meta charset="utf-8">2022-02-01 13:08:57.Simply remove all non-decimal characters and place a period before the seconds.
How to Round up to the Next Multiple of 5 in Python
The challenge
Given an integer as input, can you round it to the next (meaning, “higher”) multiple of 5?
Examples:
input: output: 0 -> 0 2 -> 5 3 -> 5 12 -> 15 21 -> 25 30 -> 30 -2 -> 0 -5 -> -5 etc.Input may be any positive or negative integer (including 0).
You can assume that all inputs are valid integers.
The solution in Python code
Option 1:
How to get the Sum of the First nth Term of a Series in Java
The challenge
Your task is to write a function that returns the sum of the following series up to nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...Rules:
- You need to round the answer to 2 decimal places and return it as String.
- If the given value is 0 then it should return 0.00
- You will only be given Natural Numbers as arguments.
Examples: (Input –> Output)
How to satisfy Wilson Primes in Python
The challenge
Wilson primes satisfy the following condition. Let
Prepresent a prime number.Then
((P-1)! + 1) / (P * P)should give a whole number.Your task is to create a function that returns
trueif the given number is a Wilson prime.The solution in Python code
Option 1:
def am_i_wilson(n): return n in (5, 13, 563)Option 2:
def am_i_wilson(n): if n < 2 or not all(n % i for i in xrange(2, n)): return False import math return (math.factorial(n - 1) + 1) % (n ** 2) == 0Option 3:
How to Boot an EC2 with a WebServer Setup
Create a new AWS EC2 instance, and set the User Script to the following:
#!/bin/bash sudo su yum update -y yum install -y httpd.x86_64 systemctl start httpd.service systemctl enable httpd.service echo "<h1>Serving from $(hostname -f)</h1>" > /var/www/html/index.htmlWriting a Sleigh Authentication in Python
The challenge
Christmas is coming and many people dreamed of having a ride with Santa’s sleigh. But, of course, only Santa himself is allowed to use this wonderful transportation. And in order to make sure, that only he can board the sleigh, there’s an authentication mechanism.
Your task is to implement the
authenticate()method of the sleigh, which takes the name of the person, who wants to board the sleigh and a secret password. If, and only if, the name equals “Santa Claus” and the password is “Ho Ho Ho!” (yes, even Santa has a secret password with uppercase and lowercase letters and special characters :D), the return value must betrue. Otherwise, it should returnfalse.Solving for Multiple of Index in Python
The challenge
Return a new array consisting of elements which are multiple of their own index in input array (length > 1).
Examples:
[22, -6, 32, 82, 9, 25] => [-6, 32, 25]
[68, -1, 1, -7, 10, 10] => [-1, 10]
[-56,-85,72,-26,-14,76,-27,72,35,-21,-67,87,0,21,59,27,-92,68] => [-85, 72, 0, 68]
The solution in Python code
Option 1:
def multiple_of_index(l): return [l[i] for i in range(1, len(l)) if l[i] % i == 0]Option 2:
How to Find an item’s Alphabet Position in Python
The challenge
When provided with a letter, return its position in the alphabet.
Input :: “a”
Ouput :: “Position of alphabet: 1”
The solution in Python code
Option 1:
def position(alphabet): return "Position of alphabet: {}".format(ord(alphabet) - 96)Option 2:
from string import ascii_lowercase def position(char): return "Position of alphabet: {0}".format( ascii_lowercase.index(char) + 1)Option 3:
def position(alphabet): return "Position of alphabet: %s" % ("abcdefghijklmnopqrstuvwxyz".find(alphabet) + 1)Test cases to validate our solution
import test from solution import position @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): tests = [ # [input, expected] ["a", "Position of alphabet: 1"], ["z", "Position of alphabet: 26"], ["e", "Position of alphabet: 5"], ] for inp, exp in tests: test.assert_equals(position(inp), exp)How to Keep up the Hoop in Java
The challenge
Alex just got a new hula hoop, he loves it but feels discouraged because his little brother is better than him
Write a program where Alex can input (n) how many times the hoop goes round and it will return him an encouraging message 🙂
- If Alex gets 10 or more hoops, return the string “Great, now move on to tricks”.
- If he doesn’t get 10 hoops, return the string “Keep at it until you get it”.
The solution in Java code
Option 1:
Will there be Enough Space in Java
The challenge
Bob is working as a bus driver. However, he has become extremely popular amongst the city’s residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not having enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers.
The task:
You have to write a function that accepts three parameters:
How to Swap Node Pairs In Linked List in Java
The challenge
If you are given the head node in a linked list, write a method that swaps each pair of nodes in the list, then returns the head node of the list.
Example:
if you are given a list ordered
A,B,C,Dthe resulting list should beB,A,D,C.The list will be composed of
Nodes of the following specification:public class Node { private String value; public Node next; public Node(String value) { this.value = value; } public String getValue() { return value; } public String toString() { return this.value; } public String printList() { if (this.next == null) return this.toString() + " ->"; return this.toString() + " -> " + next.printList(); } }The solution in Java code
Option 1:
How to Solve ‘Finding Neo’ in Java
The challenge
Neo is somewhere in the Matrix.
public interface Matrix { public int size(); public int get(int x, int y); }You are Morpheus, and your job is to find him.
public class Morpheus { public int[] find(Matrix matrix, int neo) { // return Neo's x and y coordinates as a two-element array } }You will need a good search strategy – the matrix is huge! But it is controlled by machines, so it is also very orderly. It is quadratic, and the following rules hold for all elements:
How to Solve a Pandigital Sequence in Java
The challenge
In mathematics, a pandigital number is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10.
For simplification, in this challenge, we will consider pandigital numbers in base 10 and with all digits used exactly once. The challenge is to calculate a sorted sequence of pandigital numbers, starting at a certain
offsetand with a specifiedsize.How to get Meta-Data information from an AWS EC2 Instance
If you need to query
meta-datainformation from your running EC2 instance, you can curl the following location:curl http://169.254.169.254/latest/meta-dataThis will provide a list of all information that can be retrieved.
Say you want to get the
local IPv4 address, this can be done as follows:curl http://169.254.169.254/latest/meta-data/local-ipv4You can also get JSON blocks of information back, such as querying the
IAM Info:curl http://169.254.169.254/latest/meta-data/iam/infoHow to write a Lazy Repeater Helper in Python
The challenge
The
make_looper()function takes a string (of non-zero length) as an argument. It returns a function. The function it returns will return successive characters of the string on successive invocations. It will start back at the beginning of the string once it reaches the end.Examples:
abc = make_looper('abc') abc() # should return 'a' on this first call abc() # should return 'b' on this second call abc() # should return 'c' on this third call abc() # should return 'a' again on this fourth callThe solution in Python code
Option 1:
How to write a String Case Conversion Helper in Python
The challenge
In this challenge, you will make a function that converts between
camelCase,snake_case, andkebab-case.You must write a function that changes to a given case. It must be able to handle all three case types:
change_case("snakeCase", "snake") # "snake_case" change_case("some-lisp-name", "camel") # "someLispName" change_case("map_to_all", "kebab") # "map-to-all" change_case("doHTMLRequest", "kebab") # "do-h-t-m-l-request" change_case("invalid-inPut_bad", "kebab") # None change_case("valid-input", "huh???") # None change_case("", "camel") # ""Your function must deal with invalid input as shown, though it will only be passed strings. Furthermore, all valid identifiers will be lowercase except when necessary, in other words on word boundaries in
camelCase.How to create Interleaving Arrays in Python
The challenge
Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed-in arguments. If one of them is shorter than the others, the result should be padded with empty elements.
Examples:
interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"] interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None] interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9] interleave([]) == []The solution in Python code
Option 1:
How to Find the Largest product in a Series in Python
The challenge
Complete the
greatestProductmethod so that it’ll find the greatest product of five consecutive digits in the given string of digits.Example:
greatestProduct("123834539327238239583") # should return 3240The input string always has more than five digits.
The solution in Python code
Option 1:
from itertools import islice from functools import reduce def greatest_product(n): numbers=[int(value) for value in n] result=[reduce(lambda x,y: x*y, islice(numbers, i, i+5), 1) for i in range(len(numbers)-4)] return max(result)Option 2:
How to Calculate the Least Common Multiple in Python
The challenge
Write a function that calculates the least common multiple of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return
1.The solution in Python code
Option 1:
from math import gcd def lcm(*args): lcm=1 for x in args: if x!=0: lcm=lcm*x//gcd(lcm,x) else: lcm=0 return lcmOption 2:
def lcm(*args): gcd = lambda m,n: m if not n else gcd(n,m%n) return reduce( lambda x, y: x*y/gcd(x, y), args)Option 3:
How to Solve Caesar Cipher Helper in Python
The challenge
Write a class that, when given a string, will return an uppercase string with each letter shifted forward in the alphabet by however many spots the cipher was initialized to.
Example:
c = CaesarCipher(5); # creates a CipherHelper with a shift of five c.decode('BFKKQJX') # returns 'WAFFLES'If something in the string is not in the alphabet (e.g. punctuation, spaces), simply leave it as is.
The shift will always be in the range of[1, 26].How to Write Out Numbers in Python
The challenge
Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999.
Examples:
number2words(0) ==> "zero" number2words(1) ==> "one" number2words(9) ==> "nine" number2words(10) ==> "ten" number2words(17) ==> "seventeen" number2words(20) ==> "twenty" number2words(21) ==> "twenty-one" number2words(45) ==> "forty-five" number2words(80) ==> "eighty" number2words(99) ==> "ninety-nine" number2words(100) ==> "one hundred" number2words(301) ==> "three hundred one" number2words(799) ==> "seven hundred ninety-nine" number2words(800) ==> "eight hundred" number2words(950) ==> "nine hundred fifty" number2words(1000) ==> "one thousand" number2words(1002) ==> "one thousand two" number2words(3051) ==> "three thousand fifty-one" number2words(7200) ==> "seven thousand two hundred" number2words(7219) ==> "seven thousand two hundred nineteen" number2words(8330) ==> "eight thousand three hundred thirty" number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine" number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight"The solution in Python code
Option 1:
How to do Base64 Encoding in Python
The challenge
Create a function that converts the value of the String to and from Base64 using the ASCII character set.
Do not use built-in functions.
Examples:
# should return 'dGhpcyBpcyBhIHN0cmluZyEh' to_base_64('this is a string!!') # should return 'this is a string!!' from_base_64('dGhpcyBpcyBhIHN0cmluZyEh')You can learn more about Base64 encoding and decoding here.
The solution in Python code
Option 1:
CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; def to_base_64(string): padding = 3 - len(string) % 3 if len(string) % 3 else 0 binary = ''.join(format(ord(i),'08b') for i in string) + '00'*padding return ''.join(CODES[int(binary[i:i+6], 2)] for i in range(0, len(binary), 6)) def from_base_64(string): binary = ''.join(format(CODES.find(i),'06b') for i in string) return ''.join(chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8)).rstrip('\x00')Option 2:
How to Calculate Transport on Vacation in Java
The challenge
After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you.
You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers.
Every day you rent the car costs $40. If you rent the car for 7 or more days, you get $50 off your total. Alternatively, if you rent the car for 3 or more days, you get $20 off your total.
Playing with the letter ‘E’ in Java
The challenge
Given String
str, return:- If given String doesn’t contain any “e”, return: “There is no “e”.”
- If given String is empty, return empty String.
- If given String is `null`
The solution in Java code
Option 1:
public class WithoutLetterE { public static String findE(String str){ if (str==null) return null; if (str.equals("")) return ""; int len = str.length() - str.toLowerCase().replaceAll("e", "").length(); if (len > 0) return String.valueOf(len); if (!str.contains("e")) return "There is no \"e\"."; return null; } }Option 2:
How to Sum the Average for NBA Players in Golang
The challenge
Write a function, called
sumPPG, that takes two NBA player objects/struct/Hash/Dict/Class and sums their PPGExamples:
iverson := NBAPlayer{ Team: "76ers", Ppg: 11.2 } jordan := NBAPlayer{ Team: "bulls", Ppg: 20.2 } SumPpg(iverson, jordan) // => 31.4The solution in Golang
Option 1:
package solution type NBAPlayer struct { Team string Ppg float64 } func SumPpg(playerOne, playerTwo NBAPlayer) float64 { return playerOne.Ppg+playerTwo.Ppg }Option 2:
package solution type NBAPlayer struct { Team string Ppg float64 } func SumPpg(a, b NBAPlayer) float64 { return float64(a.Ppg + b.Ppg) }Test cases to validate our solution
package solution_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const tol=1e-6 var _ = Describe("Fixed tests", func() { It("Iverson and jordan", func() { iverson := NBAPlayer{ Team: "76ers", Ppg: 11.2 } jordan := NBAPlayer{ Team: "bulls", Ppg: 20.2 } Expect(SumPpg(iverson,jordan)).To(BeNumerically("~",31.4,tol)) }) It("Standard tests", func(){ player1 := NBAPlayer{ Team: "p1_team", Ppg: 20.2 } player2 := NBAPlayer{ Team: "p2_team", Ppg: 2.6 } player3 := NBAPlayer{ Team: "p3_team", Ppg: 2023.2 } player4 := NBAPlayer{ Team: "p4_team", Ppg: 0 } player5 := NBAPlayer{ Team: "p5_team", Ppg: -5.8 } Expect(SumPpg(player1, player2)).To(BeNumerically("~",22.8 ,tol)) Expect(SumPpg(player3, player1)).To(BeNumerically("~",2043.4 ,tol)) Expect(SumPpg(player3, player4)).To(BeNumerically("~",2023.2 ,tol)) Expect(SumPpg(player4, player5)).To(BeNumerically("~",-5.8 ,tol)) Expect(SumPpg(player5, player2)).To(BeNumerically("~",2.6 - 5.8 ,tol)) }) })How to Compute a Cube as Sums in Golang
The challenge
You will be given a number
n(wheren >= 1) and your task is to findnconsecutive odd numbers whose sum is exactly the cube ofn.**Mathematically:
** cube = n ** 3
sum = a1 + a2 + a3 + ….. + an
sum == cube
a2 == a1 + 2, a3 == a2 + 2, …….For example:
FindSummands(3) == []int{7,9,11} // ..because 7 + 9 + 11 = 27, the cube of 3. // Note that there are only n = 3 elements in the array.Write function
findSummands(n)which will return an array of n consecutive odd numbers with the sum equal to the cube of n(n*n*n).The Deaf Rats of Hamelin Challenge in Java
The challenge
The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town.
But some of the rats are deaf and are going the wrong way!
Task
How many deaf rats are there?
Legend
P= The Pied PiperO~= Rat going left~O= Rat going right
Examples
- ex1
~O~O~O~O Phas 0 deaf rats - ex2
P O~ O~ ~O O~has 1 deaf rat - ex3
~O~O~O~OP~O~OO~has 2 deaf rats
The solution in Java code
Option 1:
How to Find the Next Perfect Square in Java
The challenge
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the
findNextSquaremethod that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.If the parameter is itself not a perfect square then
-1should be returned. You may assume the parameter is non-negative.How to Find the Unique String in Python
The challenge
There is an array of strings. All strings contain similar letters except one. Try to find it!
find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo'Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter.
E.g. A string that contains only spaces is like an empty string.It’s guaranteed that the array contains more than 3 strings.
How to convert a PascalCase string into snake_case in Python
The challenge
Complete the function/method so that it takes a
PascalCasestring and returns the string insnake_casenotation. Lowercase characters can be numbers. If the method gets a number as input, it should return a string.Examples:
"TestController" --> "test_controller" "MoviesAndBooks" --> "movies_and_books" "App7Test" --> "app7_test" 1 --> "1"The solution in Python code
Option 1:
import re def to_underscore(string): return re.sub(r'(.)([A-Z])', r'\1_\2', str(string)).lower()Option 2:
def to_underscore(string): string = str(string) camel_case = string[0].lower() for c in string[1:]: camel_case += '_{}'.format(c.lower()) if c.isupper() else c return camel_caseOption 3:
How to Convert a Hex String to RGB in Python
The challenge
When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements:
- Accepts a case-insensitive hexadecimal color string as its parameter (ex.
"#FF9933"or"#ff9933") - Returns a Map<String, int> with the structure
{r: 255, g: 153, b: 51}where r, g, and b range from 0 through 255
Note: your implementation does not need to support the shorthand form of hexadecimal notation (ie
"#FFF")How to Create a Hashtag Generator in Python
The challenge
Write a hashtag generator function that takes a
stringand returns a#HashCodeStringof it.The hashtag generator should perform the following tasks.
Follow these rules:
- It must start with a hashtag (
#). - All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return
false. - If the input or the result is an empty string it must return
false.
Examples:
How to Move Zeros to the End in Python
The challenge
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0]The solution in Python code
Option 1:
def move_zeros(arr): l = [i for i in arr if isinstance(i, bool) or i!=0] return l+[0]*(len(arr)-len(l))Option 2:
def move_zeros(array): return sorted(array, key=lambda x: x==0 and type(x) is not bool)Option 3:
Regex for Gregorian Date Validation in Python
The challenge
Write a regular expression that validates the gregorian date in the format “DD.MM.YYYY”
Correct date examples:
"23.12.2008" "01.08.1994"Incorrect examples:
"12.23.2008" "01-Aug-1994" " 01.08.1994"Notes:
- maximum length of validator is 400 characters to avoid hardcoding. (shortest solution to date is 170 characters)
- validator should process leap days (February, 29) correctly.
- the date is Gregorian, it’s important to determine if year is leap: https://en.wikipedia.org/wiki/Gregorian_calendar
The solution in Python code
Option 1:
How to Create Your Own Python Split Function
The challenge
Write your own implementation of the built-in
splitfunction in Python.The following rules must be adhered to:
- the function cannot use, in any way, the original
splitorrsplitfunctions, - the new function must be a generator,
- it should behave as the built-in
split, so it will be tested that way — think ofsplit()andsplit('')
The solution in Python
Option 1:
import re def my_very_own_split(string, delimiter = None): if delimiter == '': raise ValueError('empty delimiter') if delimiter == None: delimiter = '\s+' else: delimiter = re.escape(delimiter) pos = 0 for m in re.finditer(delimiter, string): yield string[pos:m.start()] pos = m.end() yield string[pos:]Option 2:
How to create a Domain Name Validator in Python
The challenge
Create a domain name validator mostly compliant with RFC 1035, RFC 1123, and RFC 2181
The following rules apply:
- Domain name may contain subdomains (levels), hierarchically separated by . (period) character
- Domain name must not contain more than 127 levels, including top level (TLD)
- Domain name must not be longer than 253 characters (RFC specifies 255, but 2 characters are reserved for trailing dot and null character for root level)
- Level names must be composed out of lowercase and uppercase ASCII letters, digits and – (minus sign) character
- Level names must not start or end with – (minus sign) character
- Level names must not be longer than 63 characters
- Top level (TLD) must not be fully numerical
Additionally:
How to start Java Jar as Service on Linux
If you have a Java Jar file, you can run it as a service under Linux/Ubuntu.
sudo ln -s /var/www/japi-0.0.1-SNAPSHOT.jar /etc/init.d/japiNow you can use the default
init.dverbs [start,stop,restart,status].Additionally,
init.dalso gives the following.Usage for your new
init.dserviceUsage: /etc/init.d/japi {start|stop|force-stop|restart|force-reload|status|run}
Start Java Service
sudo /etc/init.d/japi startStop Java Service
sudo /etc/init.d/japi stopRestart Java Service
sudo /etc/init.d/japi restartStatus Information
sudo /etc/init.d/japi statusHow to write a validDate Regex in Python
The challenge
Your task is to write a regular expression (regex) that will match a string only if it contains at least one valid date, in the format
[mm-dd](that is, a two-digit month, followed by a dash, followed by a two-digit date, surrounded by square brackets).You should assume the year in question is not a leap year. Therefore, the number of days each month should have are as follows:
How to Validate Passwords with Regex in Python
The challenge
You need to write regex that will validate a password to make sure it meets the following criteria:
- At least six characters long
- contains a lowercase letter
- contains an uppercase letter
- contains a number
Valid passwords will only be alphanumeric characters.
The solution in Python code
Option 1:
from re import compile, VERBOSE regex = compile(""" ^ # begin word (?=.*?[a-z]) # at least one lowercase letter (?=.*?[A-Z]) # at least one uppercase letter (?=.*?[0-9]) # at least one number [A-Za-z\d] # only alphanumeric {6,} # at least 6 characters long $ # end word """, VERBOSE)Option 2:
How to create a Coordinates Validator in Golang
The challenge
You need to create a function that will validate if given parameters are valid geographical coordinates.
Valid coordinates look like the following: “23.32353342, -32.543534534”. The return value should be either true or false.
Latitude (which is the first float) can be between 0 and 90, positive or negative. Longitude (which is the second float) can be between 0 and 180, positive or negative.
Coordinates can only contain digits, or one of the following symbols (including space after the comma)
How to Validate ISBN-10 numbers in Golang
The challenge
ISBN-10 identifiers are ten digits long. The first nine characters are digits
0-9. The last digit can be0-9orX, to indicate a value of 10.An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11 equals zero.
For example:
ISBN : 1 1 1 2 2 2 3 3 3 9 position : 1 2 3 4 5 6 7 8 9 10This is a valid ISBN, because:
How to Create a Java GUI App that shows the Logged-in User and Hostname
Create a new file called
Application.javaand paste the following:import javax.swing.*; import java.net.InetAddress; import java.net.UnknownHostException; public class Application { public static void main(String...args) throws UnknownHostException { JFrame frame = new JFrame("Sample App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); String user = System.getProperty("user.name"); String host = InetAddress.getLocalHost().getHostName(); JTextArea txt = new JTextArea(); txt.setText( "\n" + " User: "+user+"\n" + " Host: "+host+"\n" ); frame.getContentPane().add(txt); frame.setVisible(true); } }Now open the terminal/command-line and type:
java Application.javaThis will show a GUI application that will have a textarea with two lines of text:
How to view a Terraform Module’s Output
An
outputin Terraform is a way to view the result of an action that has been performed, or resource that has been created.Let’s say that you have some code to create a Load Balancer, or Assign a Public IP. Once this action is complete, the
outputblock will have access to this created value.An simple
outputexampleoutputs.tfoutput "instance_ips" { value = aws_instance.web.*.public_ip } output "lb_address" { value = aws_alb.web.public_dns }This will output the values to the console once the
terraform applystep has successfully run.How to Count the Characters in Python
The challenge
The goal of this challenge is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive.
Examples:
count_char("fizzbuzz","z") # 4 count_char("Fancy fifth fly aloof","f") # 5The character can be any alphanumeric character.
The solution in Python code
Option 1:
def count_char(haystack, needle): count = 0 for c in haystack: if c.lower()==needle.lower(): count+=1 return countOption 2:
How to Install Cuda driver for Nvidia on Ubuntu
If you have just upgraded Ubuntu on your AWS g4dn instance and need to install/reinstall Cuda drivers for your Nvidia chipset, then you can run the following:
Install Cuda drivers for Nvidia on Ubuntu
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin sudo mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/ /" sudo apt-get update sudo apt-get -y install cudaHow to get the versions for your own setup
Or follow the wizard here to generate the correct version numbers for your specific environment/platform:
How to List all Running Services on Ubuntu
If you need to view a list of all the services that are either running or stopped (or both) on an Ubuntu server, then you can use the following command:
service --status-allThis will print out a list of services that may look something like this:
# service --status-all [ - ] acpid [ + ] apache-htcacheclean [ + ] apache2 [ + ] apparmor [ + ] apport [ + ] atd [ - ] console-setup.sh [ + ] cron [ - ] cryptdisks [ - ] cryptdisks-early [ + ] datadog-agent [ + ] datadog-agent-process [ + ] datadog-agent-trace [ + ] dbus [ - ] dockerOnly show Running Services in Ubuntu
If you are only interested in the
runningservices, then we can filter by the[ + ]items:[Solved] conflict: unable to remove repository reference in Docker
If you get the following error while trying to delete an image in Docker:
Error response from daemon: conflict: unable to remove repository reference "some-image" (must force) - container 3ab4c18d2219 is using its referenced image 133c1827439aYou may already have tried looking for the container, but it seems to not exist!
How to Remove the Docker Container and Image
This usually means that the Docker container has already terminated, and is why you won’t see it running.
How to Upgrade an Ubuntu Server
Upgrading an Ubuntu Server is quite easy, just follow the below commands:
Option 1: Tldr; (just run the below!)
sudo apt-get update && sudo apt-get upgrade sudo apt dist-upgrade sudo do-release-upgrade rebootOption 2: Follow the steps to Upgrade Ubuntu Server
1: Update the packages:
Start by making sure that you have all the packages and dependencies ready locally before we upgrade
sudo apt-get update && sudo apt-get upgrade2: Update the dependencies for the distribution:
sudo apt dist-upgradeHow to Solve Two-Sum in Java
The challenge
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so:
(index1, index2).For the purposes of this challenge, some tests may have multiple answers; any valid solutions will be accepted.
How to Sort the Gift Code in Java
The challenge
Santa’s senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code.
Santa asked his organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes! Can you help him out?
How to get the Numericals of a String in Java
You are given an input string.
For each symbol in the string if it’s the first character occurrence, replace it with a ‘1’, else replace it with the amount of times you’ve already seen it.
Examples:
input = "Hello, World!" result = "1112111121311" input = "aaaaaaaaaaaa" result = "123456789101112"There might be some non-ascii characters in the string.
Note: there will be no int domain overflow (character occurrences will be less than 2 billion).
How to Replace Noun Phrases with Pronouns in Golang
The challenge
A Noun Phrase is a phrase that can be replaced by a pronoun [he/she/it].
For example, in the sentence:
a girl ate the cookie“A girl” is a Noun Phrase, so we can say “she ate the cookie.” “The cookie” is also a Noun Phrase, so we can even say “she ate it.”
Both of these Noun Phrases are made up of an auxialliary (aux) [the/a] followed by a Noun (N) [girl/cookie].
Maximum Positive Integer Rotations in Golang
The challenge
Write
function MaxRot(n)which given a positive integernreturns the maximum number you got doing rotations similar to the above example.So
MaxRotis such as:MaxRot(56789) should return 68957MaxRot(38458215) should return 85821534
Examples:
Take a number:
56789. Rotate left, you get67895.Keep the first digit in place and rotate left the other digits:
68957.Keep the first two digits in place and rotate the other ones:
68579.How to “Dashatize It” in Java
The challenge
Given a variable
n,If
nis an integer, Return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. Ifnis negative, then the negative sign should be removed.If
nis not an integer, return an empty value.Ex:
dashatize(274) -> '2-7-4' dashatize(6815) -> '68-1-5'The solution in Java code
Option 1:
public class Solution { public static String dashatize(int num) { String n = String.valueOf(Math.abs(num)).replaceAll("-", ""); return java.util.Arrays.asList(n.split("")).stream() .map(ch -> Integer.valueOf(ch) % 2 !=0 ? "-"+ch+"-" : ch) .collect(java.util.stream.Collectors.joining("")) .replaceAll("--", "-") .replaceAll("^-+", "") .replaceAll("-+$", ""); } }Option 2:
How to create a Nickname Generator in Python
The challenge
Write a nickname generator function,
nicknameGeneratorthat takes a string name as an argument and returns the first 3 or 4 letters as a nickname.The nickname generator should perform the following tasks.
If the 3rd letter is a consonant, return the first 3 letters.
nickname("Robert") # "Rob" nickname("Kimberly") # "Kim" nickname("Samantha") # "Sam"If the 3rd letter is a vowel, return the first 4 letters.
nickname("Jeannie") # "Jean" nickname("Douglas") # "Doug" nickname("Gregory") # "Greg"If the string is less than 4 characters, return “Error: Name too short”.
Comparing Array Multiplicities in Java
The challenge
Given two arrays
aandbwrite a functioncomp(a, b)(orcompSame(a, b)) that checks whether the two arrays have the “same” elements, with the same multiplicities. “Same” means, here, that the elements inbare the elements inasquared, regardless of the order.Examples
Valid arrays
a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]comp(a, b)returns true because inb121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we writeb‘s elements in terms of squares:How to Find the Sum of Angles in Golang
The challenge
Find the total sum of internal angles (in degrees) in an n-sided simple polygon.
Nwill be greater than 2.The solution in Golang
Option 1:
package solution func Angle(n int) int { return (n - 2) * 180 }Option 2:
package solution func Angle(n int) (r int) { r = (n-2)*180 return }Option 3:
package solution func Angle(n int) int { return (n/2-1) * 360 + n%2 * 180 }Test cases to validate our solution
package solution_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Basic tests", func() { It("Angle(3)", func() { Expect(Angle(3)).To(Equal(180)) }) It("Angle(4)", func() { Expect(Angle(4)).To(Equal(360)) }) })How to Find the Max Tree Node Value in Java
The challenge
You are given a binary tree. Implement the method
findMaxwhich returns the maximal node value in the tree.For example, the maximum in the following Tree is 11.
7 / \ / \ 5 2 \ \ 6 11 /\ / 1 9 4Note:
- Tree node values range is Integer MIN VALUE – Integer MAX VALUE constants.
- Tree can unbalanced and unsorted.
- Root node is always not null.
You are given a tree node class as follows:
How to String Search with a Wildcard in Java
The challenge
The method below is the most simple string search algorithm. It will find the first occurrence of a word in a text string.
haystack = the whole textneedle = searchwordwildcard = _find("strike", "i will strike down upon thee"); // return 7The find method is already made.
The problem is to implement wildcard(s) in the needle. If you have a _ in the needle it will match any character in the haystack.
How to get the AWS AccountID in Terraform
If you are automating AWS resources in Terraform, then you will want to not hardcode things as much as possible.
Terraform makes it possible to pull the
account_idfrom the local credentials.How to get the AccountID data attributes
Create a
data.tffile and place the following item in it:data "aws_caller_identity" "current" {}Now the account_id will be available to you within your standard code as follows:
data.aws_caller_identity.current.account_idHow to use the AccountID data attributes
This can now be used in a module, or wherever you need to reference the account id:
Error creating AppStream Fleet – InvalidRoleException
If you get the following error when trying to run some Terraform:
error creating Appstream Fleet (): InvalidRoleException: AppStream 2.0 encountered an error because your service role 'arn:aws:iam::<ACCOUNT_ID>:role/service-role/AmazonAppStreamServiceAccess' is invalid..then you just need to run your IaC again, as the roles are automatically created when you first interact with the service.
Alternatively, go and have a look at what has already been created in the AWS Console.
What roles are required for AppStream?
Role required by AWS AppStream:
How to Create AWS AppStream resources in Terraform
AWS AppStream has finally made its way into the Terraform AWS Provider.
If you are using
hashicorp/awsversion3.67or above, then you can do the following:terraform { required_version = "~> 1.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 3.67" } } } provider "aws" { region = "eu-west-1" default_tags { tags = { Contact = "[email protected]" Environment = "dev" DeployedBy = "Automation:Terraform" } } } resource "aws_appstream_fleet" "example" { name = "ao-tmp-fleet-1" image_name = "Amazon-AppStream2-Sample-Image-02-04-2019" instance_type = "stream.standard.small" compute_capacity { desired_instances = 1 } } resource "aws_appstream_stack" "example" { name = "ao-tmp-stack-1" } resource "aws_appstream_fleet_stack_association" "example" { fleet_name = aws_appstream_fleet.example.name stack_name = aws_appstream_stack.example.name }How to Stop a Goroutine in Golang
It’s possible to stop a Goroutine by sending a value into it via a
signal channel:exit := make(chan bool) go func() { for { select { case <- exit: return default: // Perform some tasks } } }() // Exit the Goroutine exit <- trueAs an alternative, you could also use a
WaitGroupandrangeover it:package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup c := make(chan bool) wg.Add(1) go func() { defer wg.Done() for b := range c { fmt.Printf("Hello %t\n", b) } }() c <- true c <- true close(c) wg.Wait() }How to Create an Empty Branch in Git
If you need to create an empty branch in git, you can follow one of the below options.
If you are using git version 2.27 or newer, then follow the
switchroute (option 1) below, otherwise fall back to the older way, usingcheckoutanddelete(option 2).Newer way – Using
switch:git switch --orphan <new branch> git commit --allow-empty -m "Initial commit on orphan branch" git push -u origin <new branch>Older way – Using
checkoutanddelete:git checkout --orphan <new branch> git rm -rf . git commit --allow-empty -m "root commit" git push origin <new branch>Get the Consonant Value in Java
The challenge
Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except
"aeiou".We shall assign the following values:
a = 1, b = 2, c = 3, .... z = 26.For example, for the word “zodiacs”, let’s cross out the vowels. We get: “z
odiacs”-- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22. The highest is 26. solve("zodiacs") = 26 For the word "strength", solve("strength") = 57 -- The consonant substrings are: "str" and "ngth" with values "str" = 19 + 20 + 18 = 57 and "ngth" = 14 + 7 + 20 + 8 = 49. The highest is 57.The solution in Java code
Option 1:
How to Check for Factor in Python
The challenge
This function should test if the
factoris a factor ofbase.Return
trueif it is a factor orfalseif it is not.About factors
Factors are numbers you can multiply together to get another number.
2 and 3 are factors of 6 because:
2 * 3 = 6- You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor.
- You can use the mod operator (
%) in most languages to check for a remainder
Examples:
Understanding Bitwise Operators in Python
There are 6 binary/bitwise operators in Python:
- Complement/Not (
~) - And (
&) - Or (
|) - XOR (
^) - Left Shift (
<<) - Right Shift (
>>)
A fantastic python method to help us along our journey is
bin(). Thebinfunction will return a binary representation of a base 10 integer we pass to it.>>> bin(1) '0b1' >>> bin(5) '0b101'Now let’s explore the 6 bitwise operators by learning a bit about each of them.
Word Values Challenge in Java
The challenge
Given a string
"abc"and assuming that each letter in the string has a value equal to its position in the alphabet, our string will have a value of1 + 2 + 3 = 6. This means that:a = 1, b = 2, c = 3 ....z = 26.You will be given a list of strings and your task will be to return the values of the strings as explained above multiplied by the position of that string in the list. For our purpose, position begins with
1.How to update/upgrade all Homebrew packages
If you use Homebrew – and you probably should if you’re on a Mac – then you have probably installed various different applications and packages as time went on. It’s probably likely that by now, you have many different packages that are out of date and need to be upgraded to their newer versions.
Luckily, Homebrew makes it very easy to upgrade everything; run the following command to upgrade everything.
[Solved] FirebaseError: Missing or insufficient permissions
Using Firebase and get the following error in the console?
Uncaught Error in onSnapshot: FirebaseError: Missing or insufficient permissions.<br>at new FirestoreError (index.cjs.js:x)How to fix the Missing or Insufficient Permissions Error
Option 1: Change rules (Recommended)
- Login to Firebase
- Go to
Database->Rules
Change:
service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } }to:
service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth != null; } } }Option 2: Override Authorization / Disable Security
- Login to Firebase
- Go to
Database->Rules - Change
allow read, writefromfalsetotrue[for dev] - Change
allow read, writefromfalsetorequest.auth != null[for prod]
[Solved] Error: Cannot find module ‘../lib/cli.js’
If you try and run
npm iand getError: Cannot find module '../lib/cli.js', then you can easily fix the problem by running the following.How does the error look?
Error: Cannot find module '../lib/cli.js' Require stack: - /usr/local/lib/node_modules/npm/bin/npm-cli.js at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:999:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:2:1) at Module._compile (node:internal/modules/cjs/loader:1095:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) { code: 'MODULE_NOT_FOUND', requireStack: [ '/usr/local/lib/node_modules/npm/bin/npm-cli.js' ] }How to solve the Module Not Found error
brew uninstall --ignore-dependencies node sudo chown -R $(whoami) /usr/local/* brew cleanup brew install nodeThis will uninstall and cleanup your previous
nodeinstallation, making sure to set the correct permissions, before reinstalling it.How to use Git Commit in GitHub Actions
If you’ve tried to use
git commitin GitHub Actions before, you may have come across the following error messages:Author identity unknown *** Please tell me who you are. Run git config --global user.email "[email protected]" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set the identity only in this repository. fatal: empty ident name (for <[email protected]>) not allowed Author identity unknownThis can easily be fixed by doing the following:
[Solved] Error acquiring the state lock in Terraform
If you have been handed the
Acquiring state lockerror message aboutConditionalCheckFailedException: The conditional requestthen you have 2 options for fixing it!The error looks something like this:
Acquiring state lock. This may take a few moments... ╷ │ Error: Error acquiring the state lock │ │ Error message: ConditionalCheckFailedException: The conditional request │ failed │ Lock Info: │ ID: 3324a6cb-7401-3194-d650-fxxxxxx3864 │ Path: xxxx-terraformstate-nonprod/env:/xxxx/terraform.tfstate │ Operation: OperationTypeApply │ Who: root@ip-100-65-2-165 │ Version: 1.0.4 │ Created: 2021-11-29 21:00:37.652114035 +0000 UTC │ Info: │ │ Terraform acquires a state lock to protect the state from being written │ by multiple users at the same time. Please resolve the issue above and try │ again. For most commands, you can disable locking with the "-lock=false" │ flag, but this is not recommended.There are 3 possible ways to fix this
In short, you want to delete the lock associated. This is achieved by forcing an unlock.
How to Install Chocolatey on Windows PowerShell
Chocolatey is a software management automation for Windows that wraps installers, executables, zips, and scripts into compiled packages
chocolatey.org
How to Install Chocolatey in PowerShell
Open
PowerShell(Run PowerShell in Administrator mode) and paste the following script:Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))This will install Chocolatey, and get you to the point of being able to install packages.
Install some Packages with Chocolatey
Some example packages to install:
How to run PowerShell in Administrator Mode
Some
PowerShellcommands require elevated permissions to complete.To do this, you must first open
PowerShell in Administrator Mode.Steps to Run PowerShell as an Administrator
- Click
Start(super key) - Type
powershell - Right-click on
Windows PowerShelland selectRun as administrator
or;
SelectRun as Administratorfrom the right-hand-side menu.
(Run as Administrator)
The application will now be started in Administrator Mode.
[Solved] Permission denied @ apply2files – /usr/local/lib/node_modules/expo-cli/node_modules/extglob/lib
If you have recently upgraded your MacOS operating system, you may get the following error in your terminal when installing some Homebrew packages:
Error: Permission denied @ apply2files - /usr/local/lib/node_modules/expo-cli/node_modules/.bin/detect-libcHow to solve the Permissions Denied problem
Simply run the following command in your terminal:
sudo chown -R $(whoami):admin /usr/local/* \ && sudo chmod -R g+rwx /usr/local/*Or change the user directly:
sudo chown -R ${LOGNAME}:staff /usr/local/lib/node_modulesHow to Fix “is not authorized to create managed-rule” in AWS Step Functions
If you have ever received the following error
is not authorized to create managed-rulewhen running a Step Function through Terraform’s AWS Provider, then you may have jumped through many different hoops trying to figure out what was wrong.What is the Quick Fix?
Open the
roleinIAMand attach theCloudWatchEventsFullAccessAWS managed policy to the permissions policies.Need More Information?
IAM Role Principal Policy required to AssumeRole
{ "Version" : "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Principal" : { "Service" : "states.amazonaws.com" }, "Action" : "sts:AssumeRole" } ] }IAM Role Policy GetEvents For StepFunctions Execution Rule
{ "Effect": "Allow", "Action": [ "events:PutTargets", "events:PutRule", "events:DescribeRule" ], "Resource": [ "arn:aws:events:[[region]]:[[account]]:rule/StepFunctionsGetEventsForStepFunctionsExecutionRule" ] }IAM Role Policy under StepFunctions CloudFormation
- Effect: Allow Action: - events:PutTargets - events:PutRule - events:DescribeRule Resource: - !Sub arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventsForStepFunctionsExecutionRuleIf you need to limit it to a resource, then
StepFunctionsGetEventsForStepFunctionsExecutionRuleis the one you’re looking for!How to add Account Condition to AWS Lambda Permissions in Terraform
If you need to lock an AWS Lambda function down to a source account for security reasons (PCI.Lambda.1) then you can do so by using the
source_accountoption of theaws_lambda_permissionTerraform resource type.resource "aws_lambda_permission" "do_something_with_bucket" { statement_id = "AllowExecutionFromS3Bucket" action = "lambda:InvokeFunction" function_name = module.do_something_with_bucket.arn principal = "s3.amazonaws.com" source_arn = var.source_bucket_arn source_account = var.account_id # <---------- here }We have stored the
account_idin a variable so that it can be updated when we initialize our Terraform context:How to AssumeRole in Terraform LocalExec Provisioner Block
I needed to execute a Terraform
null_resourceprovisioner(local-exec) block to run anawsclicommand, but assume a role passed down to it.There was no obvious way to pass the credentials to it, or assume a role directly, so the following workaround did the trick:
AssumeRole and Pass LocalExec Provisioner Command
resource "null_resource" "start-appstream-fleet" { provisioner "local-exec" { interpreter = ["/bin/bash", "-c"] command = <<EOF set -e CREDENTIALS=(`aws sts assume-role \ --role-arn ${local.workspace.role} \ --role-session-name "start-appstream-fleet" \ --query "[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]" \ --output text`) unset AWS_PROFILE export AWS_DEFAULT_REGION=us-east-1 export AWS_ACCESS_KEY_ID="$${CREDENTIALS[0]}" export AWS_SECRET_ACCESS_KEY="$${CREDENTIALS[1]}" export AWS_SESSION_TOKEN="$${CREDENTIALS[2]}" aws appstream start-fleet --name sample-app-${var.environment}-fleet --region ${var.region} --output json EOF } }The above code snippet runs 2
aws clicommands. The first is to get the credentials, which are then stored in environment variables, followed by consuming them in the actualaws clicommand at the bottom.Split and then add both sides of an array together in Java
The challenge
You will receive an array as a parameter that contains 1 or more integers and a number
n.Here is a little visualization of the process:
- Step 1: Split the array in two:
[1, 2, 5, 7, 2, 3, 5, 7, 8] / \ [1, 2, 5, 7] [2, 3, 5, 7, 8] - Step 2: Put the arrays on top of each other:
[1, 2, 5, 7] [2, 3, 5, 7, 8] - Step 3: Add them together:
[2, 4, 7, 12, 15]
Repeat the above steps
ntimes or until there is only one number left, and then return the array.Highest Rank Number in an Array in Golang
The challenge
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for the most frequent number, return the largest number among them.
Note: no empty arrays will be given.
Examples
[12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 [12, 10, 8, 12, 7, 6, 4, 10, 12, 10] --> 12 [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10] --> 3The solution in Golang
Option 1:
Sort Words by Position Index in Java
The challenge
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
How to get the Current Machine Name and Logged In User in Java
It’s very easy to get the
current machine nameandlogged in userusing Java.Get the Currently Logged in User
String username = System.getProperty("user.name"); System.out.println("Username logged in: " + username);This is also platform-independent.
Get the Hostname of the Machine
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); System.out.println("Hostname of local machine: " + hostname);How to set ZSH as your default Shell
You may have installed ZSH and every-time you open your terminal, it opens BASH by default.
How do you set your default shell to open as ZSH?
It’s easy, you can just use the
change shellcommand:chsh -s $(which zsh)How to Base64 Encode/Decode in the Terminal/CLI
If you need to either Encode or Decode a Base64 value, there are many ways to achieve this, one of them is directly from your commandline itself!
How to Encode a Base64 value in CLI
echo 'This is a test' | base64This will output a base64 encoded value of
VGhpcyBpcyBhIHRlc3QKHow to Decode a Base64 value in CLI
echo VGhpcyBpcyBhIHRlc3QK | base64 --decodeThis will output a decoded value from our base64 value of
This is a testHow to Enable Syntax Highlighting in Vim
There are a few different ways to enable Syntax Highlighting in Vim.
Option 1 – Edit ~/.vimrc
Add
syntax onto your local~/.vimrcecho "syntax on" >> ~/.vimrcOption 2 – Override System Vim (Mac)
cd vim --version xcode-select --install ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew doctor brew install vim --override-system-vim vim --versionOption 3 – Toggle in Vim
You can use
Vim Commandswhile in Vim itself::syntax onHow to Create an AWS Security Group in Terraform - Securing AWS Resources with Terraform Security Groups
Security groups are a critical component for securing resources in AWS. This guide will show you how to create and manage security groups in AWS using Terraform, a popular infrastructure-as-code tool.
Overview of AWS Security Groups
Security groups act as a firewall to control inbound and outbound traffic to AWS resources like EC2 instances, RDS databases, ELB load balancers, etc. They operate at the instance level, not the subnet level.
Some key characteristics of security groups:
How to Create an AWS Security Group in CloudFormation
Below is a simple CloudFormation script block to create a Security Group in AWS.
Resources: SampleAppAppstreamSG: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Inbound and outbound traffic for service GroupName: 'sampleappsg-123' VpcId: !Ref vpcid Tags: - Key: "Name" Value: "Sample App Security Group" SecurityGroupEgress: - IpProtocol: "-1" FromPort: 0 ToPort: 0 CidrIp: 10.0.0.0/8 SecurityGroupIngress: - IpProtocol: "-1" FromPort: 0 ToPort: 0 CidrIp: 10.0.0.0/8You can read up more about all the possible arguments in the AWS Security Group CloudFormation Reference.
How to provide Default Values for AWS CloudFormation Parameters
AWS CloudFormation is very useful for creating template-able infrastructure definitions.
One of the sections of a template, is the
Input Parameters, or simplyParametersas CloudFormation calls it. This is a section block that llows for user defined variables to be consumed by the template.When testing, it can be useful to specify default values here.
This can be achieved by adding the
Defaultkey and setting a value.Parameters: environment: Type: String Default: DEV vpcid: Type: String Default: "vpc-123456789123456a"How to Validate an AWS CloudFormation Template
The AWS CLI comes with a useful subcommand to validate a CloudFormation template.
Simply run the following to validate a CloudFormation template file:
aws cloudformation validate-template --template-body file://cf-infra.yamlRemember to swap out
cf-infra.yamlwith your CloudFormation template file.How to Reverse Sort Integers in Go
The challenge
The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age].
The order of the numbers passed in could be any order. The array will always include at least 2 items. If there are two or more oldest age, then return both of them in array format.
How to view the Encoded Authorization Failure Message in AWS
You may come across a message that reads similar to the following:
<meta charset="utf-8">Encoded authorization failure messageA full message, will look something like:
API: ec2:CreateSecurityGroup You are not authorized to perform this operation. Encoded authorization failure message: B2UTpuAS30_naB5rE3Dw5v2ENy-V5w3H0wmt6rfE8hrpUz2dCIiA5XcBCtzo4cipk_JiGxAKCvlZQy0Rr2Xi3Fg2pKdkvojgn5LOZJzVroFPqMbyJguCJWxxxxxxxDNOZGGGlT2PIxTnqLQ561_piXzApfRL2kv-cYhxnuNwJWEeX8-N15mDcswhUyoV5pYtehdupp5umWZt8mcAiatlf7JIo0Q6tobs7Iw22tWTofMIZW-qkPtrTg7YrrY2--kTF3Q9qQBJw6gjr_QGznd9Fh0OMF_dCLC70bLRg5Jtxn5HyLxZWu9sC-y6x1tebYRokj32NVqr4h8pklocEKe6iqM88xV1cHJXcstP_gvoFf22yFmIll7DcE5Llsn-lD6bsB0QWWgy81m6_X0JW6s5ea4BD2nE1GM511BS20x-gGM65fm5z2SrjU09G-kmXngugnra135eY28qqjdvIl1Knb-KnEXzrtAj_DaAehx5HizwtIdi3_Yxxxxxxx_AmwgLBDZuqEL1BLZjClw7TtVjysGeO6WJyL2NMXN7Gtvzg2AL4q_z-ROH1xxxxxxxxxxxHow to view the Encoded Message from AWS
In your terminal/commandline, you need to paste the encoded message from above (your own one) into the following
aws ststool:aws sts decode-authorization-message --encoded-message <past_encoded_string_here> --query DecodedMessage --output text | jq '.'If it complains about
jq; perhaps you don’t have it installed; then you can exclude the last section and rather use the following:How to run/execute a program from Terraform
If you need to run a local application from your Terraform scripts, you can call out to the
provisionerlocal-execand issue thecommandsyntax:resource "null_resource" "dig-aoms" { provisioner "local-exec" { # define your command below # this can be any application available in your terminal/commandline, # along with arguments command = "dig any andrewodendaal.com" } }How to script AWS AppStream 2.0 ImageBuilder
AppStream (2.0) is a fully managed non-persistent desktop and application service for remotely accessing your work.
The
ImageBuilderforms the first stage in the creation and definition of an image that can be used to stream.You can use the AWS CLI to initiate the creation of an image in ImageBuilder:
aws appstream create-image-builder \ --name <name> \ --image-name <image_name> \ --instance-type <instance_type> \ --vpc-config SubnetIds=<subnet_ids>,SecurityGroupIds=<security_group_ids> \ --iam-role-arn <iam_role_arn> \ --enable-default-internet-accessSwap out the above items with your own values:
How to Reimplement the Unix Uniq Command in Golang
The challenge
Implement a function which behaves like the
uniqcommand in UNIX.It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance.
Example:
["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"]The solution in Golang
Option 1:
package uniq func Uniq(a []string) []string { array := []string{} for i, value := range a { if i == 0 { array = append(array, value) } else if a[i-1] != value { array = append(array, value) } } return array }Option 2:
How to install GraalVM on Mac
Install GraalVM with Homebrew
Homebrew is the preferred way to install anything on your Mac.
brew install graalvm/tap/graalvm-ce-java17Install GraalVM without Homebrew
Follow these 5 steps to get GraalVM installed on your Mac.
Step1:
Download the official binary: https://www.graalvm.org/downloads/
Unpack the archive into a folder.
Step2:
Move the folder into the JavaVirtualMachines directory:
sudo mv graalvm-ce-java17-21.3.0 /Library/Java/JavaVirtualMachinessudois required because/Libraryis a system directory.Step3:
Verify the installation using the
java_homeutility:How to Generate Random Integers with a Range in Java
Java comes with many different ways to generate random integers, even if you need to specify a lower and upper bound to constrain your required value for.
Option 1 – ThreadLocalRandom
Specify the
minandmaxvalues:import java.util.concurrent.ThreadLocalRandom; int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);Option 2 – Random
Between `` (inclusive) and the
specified value(exclusive):import java.util.Random; Random rn = new Random(); int range = maximum - minimum + 1; int randomNum = rn.nextInt(range) + minimum;Option 3 – Multiple values
import java.util.Random; Random r = new Random(); int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray(); int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();How to create ArrayList from Array in Java
The problem
If you have a traditional array, that looks something like the following:
A[] array = {new A(1), new A(2), new A(3)};And you would like to convert this to an ArrayList:
ArrayList<Element> arraylist = ???;..then you can do the following!
The solution
The technique
new ArrayList<>(Arrays.asList(array));How to use it
Of course you could always simplify this one further directly as:
List<ClassName> list = Arrays.asList(array)How to old Java
If you are stuck in the old world of Java, you can fall back to:
How to Generate a Random AlphNumeric String in Linux/MacOS
If you need to generate a random AlphaNumeric string from the Linux/MacOS Command-Line, then you can use the following script:
dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n'This can also be piped into a variable as follows:
RANDOM_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n')The above
echo $RANDOM_IDwill resemble something similar to:90fa3bb51922eadcHow to check if a string is empty in Go
If you need to check if a
stringis empty in Go, then there are two possible ways to immediately verify this:Option 1 – Compare the length:
if len(s) > 0 { // do something with string }Option 2 – Compare against blank:
if s != "" { // do something with string }How to read a file line by line in Go
If you need to read a file line by line in Go, then you can use the
bufiopackage as follows:package main import ( "bufio" "fmt" "log" "os" ) func main() { file, err := os.Open("/path/to/file.txt") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(err) } }Just note that the
Scannerwill throw an error if any line has a character count longer than 65536. This relates back to a 64K size limit. In this case, you can use theBuffermethod to increase the capacity.Floating-point Approximation in Golang
The challenge
Consider the function
f: x -> sqrt(1 + x) - 1atx = 1e-15.We get:
f(x) = 4.44089209850062616e-16This function involves the subtraction of a pair of similar numbers when x is near 0 and the results are significantly erroneous in this region. Using
powinstead ofsqrtdoesn’t give better results.A “good” answer is
4.99999999999999875... * 1e-16.Can you modify f(x) to give a good approximation of f(x) in the neighborhood of 0?
All the Ways to Divide an Array in Two in Golang
The challenge
Write a function
partlistthat gives all the ways to divide an array of at least two elements into two non-empty parts.- Each two non empty parts will be in a pair
- Each part will be in a string
- Elements of a pair must be in the same order as in the original array.
Examples:
a = ["az", "toto", "picaro", "zone", "kiwi"] --> [("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]The solution in Golang
Option 1:
How to check if a file exists in Go
If you need to check if a file exists using Go, then you can use one of the following methods, depending on the version of Go you may be using.
If you are using Go >=1.13, then
file, err := os.OpenFile("/path/to/file.txt") if errors.Is(err, os.ErrNotExist) { // The file does not exists }However, it is also possible to trap an error from an
OpenFileattempt:file, err := os.OpenFile("/path/to/file.txt") if os.IsNotExist(err) { // The file does not exists }You can also confirm if the path is also not a directory as follows:
How to convert a string value to an int in Go
If you need to convert a
stringto anintin Go, then you should use thestrconv.Atoifunction:package main import ( "strconv" "fmt" ) func main() { t := strconv.Atoi("123") fmt.Println(t) }Learn how to convert an int value to a string in Go.
How to convert an int value to string in Go
If you need to convert an
intto astringin Go, then you should use thestrconv.Itoafunction:package main import ( "strconv" "fmt" ) func main() { t := strconv.Itoa(123) fmt.Println(t) }Learn how to convert a string value to an int in Go.
How to Efficiently Concatenate Strings in Go
If you are using a version of Go >= 1.10, then you should be using the newer
strings.Builderpattern as follows:package main import ( "strings" "fmt" ) func main() { var sb strings.Builder for i := 0; i < 100; i++ { sb.WriteString("a") } fmt.Println(sb.String()) }For older version, you should be looking to use the
bytes.Bufferinstead:package main import ( "bytes" "fmt" ) func main() { var buffer bytes.Buffer for i := 0; i < 100; i++ { buffer.WriteString("a") } fmt.Println(buffer.String()) }How to check if a map contains a key in Go
If you have a
mapin Go and want to only perform an action if it contains a certain key, then you can do so easily:if val, ok := myMap["someValue"]; ok { // your code here }The way this works is the conditional
ifstatement checks to see if a value ofsomeValueexists in themyMapmap variable.If it exists, it assigns the key’s value to a
valvariable, and assigns theokvariable to a truthy boolean.How to Remove all Vowels from a String in Java
The challenge
Remove all vowels from the string.
Vowels:
a e i o u A E I O UThe solution in Java code
Option 1:
public class VowelRemoval { public static String disemvowel(String str) { return str.replaceAll("[aAeEiIoOuU]", ""); } }Option 2:
public class VowelRemoval { public static String disemvowel(String str) { return str.replaceAll("(?i)[aeiou]" , ""); } }Option 3:
public class VowelRemoval { public static String disemvowel(String str) { return str .replaceAll("a", "").replaceAll("A", "") .replaceAll("e", "").replaceAll("E", "") .replaceAll("i", "").replaceAll("I", "") .replaceAll("o", "").replaceAll("O", "") .replaceAll("u", "").replaceAll("U", ""); } }Test cases to validate our solution
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.lang.StringBuilder; import java.util.Random; public class Tests { @Test public void FixedTests() { assertEquals("Ths wbst s fr lsrs LL!" , VowelRemoval.disemvowel("This website is for losers LOL!")); assertEquals("N ffns bt,\nYr wrtng s mng th wrst 'v vr rd", VowelRemoval.disemvowel ("No offense but,\nYour writing is among the worst I've ever read")); assertEquals("Wht r y, cmmnst?" , VowelRemoval.disemvowel("What are you, a communist?")); } public static String generateRandomChars(String candidateChars, int length) { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { sb.append(candidateChars.charAt(random.nextInt(candidateChars.length()))); } return sb.toString(); } public static String C(String Z) { return Z.replaceAll("(?i)[aeiou]" , ""); } @Test public void RandomTests() { for(int i = 0; i < 100; i++) { String X = generateRandomChars( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", i + 3); assertEquals(C(X) , VowelRemoval.disemvowel(X)); } } }How to Loop Forever in Golang
If you need to loop forever, or infinitely, in your Go code, then you have 2 options:
Option 1:
for { // your code here }Option 2:
for true { // your code here }Just remember that you need to break out of this, otherwise it really will run forever!
How to use in a Go Application
package main func main() { // OPTION 1 for { // your code here } // OPTION 2 for true { // your code here } }Understanding For Loops in Golang
In Golang a
for loopis a way to loop through an iterable.The most basic For Loop
i := 0 for i <= 3 { i = i + 1 }A classic For Loop
for i := 7; i <= 9; i++ { // do something }For Loop without Conditions
A
forwithout a condition will loop forever, until either abreakorreturnis hit.for { // do something break // kill the loop }When to use
continueA
continuewill move to the next iteration of the loop[Solved] go mod init: modules disabled by GO111MODULE=off
You’ve probably just tried to initialise a new Go module, and received the following error:
go mod init: modules disabled by GO111MODULE=off; see 'go help modules'This usually happens after running a command like:
go mod init github.com/<user>/<repo>What is GO111MODULE?
From Go version 1.11, the way to deal with modules was revamped.
Beforehand, it was required that you place all your Go code under a $GOPATH.
Which many Go developers didn’t much like, as it seemed chaotic at best.
How to UpperCase the start of each Word in a String in Golang
The challenge
The task is to take a string of lower-cased words and convert the sentence to upper-case the first letter/character of each word
Example:
this is the sentencewould beThis Is The SentenceThe solution in Golang
Option 1:
As a first approach, we could loop through each word, and
Titleit before adding it back to a new string. Then make sure to trim any spaces before returning it.How to Solve Max-Min Arrays in Java
The challenge
You are given an array of unique elements, and your task is to rearrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc.
For example:
solve([15,11,10,7,12]) = [15,7,12,10,11]The first max is
15and the first min is7. The second max is12and the second min is10and so on.The solution in Java code
Option 1:
How to Find the Smallest Integer in the Array in Golang
The challenge
Given an array of integers your solution should find the smallest integer.
For example:
- Given
[34, 15, 88, 2]your solution will return2 - Given
[34, -345, -1, 100]your solution will return-345
You can assume, for the purpose of this challenge, that the supplied array will not be empty.
The solution in Golang
Option 1:
package solution func SmallestIntegerFinder(numbers []int) int { curr := numbers[0] for _, v := range numbers { if v<curr { curr = v } } return curr }Option 2:
How to do Basic Encryption in Java
The challenge
The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example ‘a’ + 1 would give us ‘b’, because ‘a’ value is 97 and ‘b’ value is 98.
You will need to write a method that does exactly that –
get a string as text and an int as the rule of manipulation, and should return encrypted text. for example:
Forming Unique Array Combinations in Golang
The challenge
You are given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray.
For example:
solve([[1,2],[4],[5,6]]) = 4, because it results in only4possibilites. They are[1,4,5],[1,4,6],[2,4,5],[2,4,6].Make sure that you don’t count duplicates; for example
solve([[1,2],[4,4],[5,6,6]]) = 4, since the extra outcomes are just duplicates.The solution in Golang
Option 1:
How to Check if String is a Palindrome in Python
The challenge
Write a function that checks if a given string (case insensitive) is a palindrome.
The solution in Python
Option 1:
def is_palindrome(s): s = s.lower() for i, item in enumerate(s): if i<len(s)/2: if s[i]!=s[len(s)-i-1]: return False return TrueOption 2:
def is_palindrome(s): s = s.lower() return s == s[::-1]Option 3:
def is_palindrome(s): return s.lower()==s[::-1].lower()Test cases to validate our solution
@test.describe('sample tests') def sample_tests(): test.assert_equals(is_palindrome('a'), True) test.assert_equals(is_palindrome('aba'), True) test.assert_equals(is_palindrome('Abba'), True) test.assert_equals(is_palindrome('malam'), True) test.assert_equals(is_palindrome('walter'), False) test.assert_equals(is_palindrome('kodok'), True) test.assert_equals(is_palindrome('Kasue'), False)How to Find the Squares in Java
The challenge
Complete the function that takes an odd integer (
0 < n < 1000000) which is the difference between two consecutive perfect squares, and return these squares as a string in the format"bigger-smaller".Examples
9 --> "25-16" 5 --> "9-4" 7 --> "16-9"The solution in Java code
Option 1:
public class Solution { public static String findSquares(final int n) { final long a = (n + 1) / 2; final long b = a - 1; return String.format("%d-%d", a * a, b * b); } }Option 2:
How to Get Longest Word in Sentence in Java
The challenge
When given a string of space-separated words, return the word with the longest length.
If there are multiple words with the longest length, return the last instance of the word with the longest length.
Example:
'red white blue' // returns string value of white 'red blue gold' // returns goldThe solution in Java code
Option 1:
public class Solution { public static String longestWord(String wordString) { String longest = ""; for (String word: wordString.split(" ")) if (word.length()>=longest.length()) longest = word; return longest; } }Option 2:
How to Sum all the Integers in a String in Golang
The challenge
Implement a function that calculates the sum of the integers inside a string. For example, in the string
"The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is3635.Note: only positive integers will be tested.
The solution in Golang
Option 1:
package solution import ( "fmt" "regexp" "strconv" ) func SumOfIntegersInString(strng string) int { re := regexp.MustCompile("[0-9]+") fmt.Println(re.FindAllString(strng, -1)) sum := 0 for _, i := range re.FindAllString(strng, -1) { number, _ := strconv.Atoi(i) sum += number } return sum }Option 2:
How to Reverse a String in Golang
The challenge
Complete the solution so that it reverses the string passed into it.
'world' => 'dlrow' 'word' => 'drow'The solution in Golang
Option 1:
package solution func Solution(word string) (out string) { for _, v := range word { out = string(v) + out } return }Option 2:
package solution import "strings" func Solution(word string) string { var b strings.Builder for i:=len(word)-1; i>-1; i-- { b.WriteByte(word[i]) } return b.String() }Option 3:
Maximum Different of Int-Array in Java
The challenge
You must implement a function that returns the difference between the biggest and the smallest value in a list(lst) received as a parameter.
The list(
lst) contains integers, which means it may contain some negative numbers.If the list is empty or contains a single element,
return 0.The list(
lst) is not sorted.maxDiff([1, 2, 3, 4]); // return 3, because 4 - 1 == 3 maxDiff([1, 2, 3, -4]); // return 7, because 3 - (-4) == 7The solution in Java code
Option 1:
Indexed Capitalization in Java
The challenge
Given a string and an array of integers representing indices, capitalize all letters at the given indices.
Example:
capitalize("abcdef",[1,2,5]) = "aBCdeF"capitalize("abcdef",[1,2,5,100]) = "aBCdeF". There is no index 100.
The input will be a lowercase string with no spaces and an array of digits.
The solution in Java code
Option 1:
package solution; import java.util.*; public class Solution{ public static String capitalize(String s, int[] ind){ char[] chars = s.toCharArray(); Arrays.stream(ind) .filter(c -> c < s.length()) .forEach(c -> chars[c] = Character.toUpperCase(chars[c])); return new String(chars); } }Option 2:
How to Spacify a String in Java
The challenge
Modify the spacify function so that it returns the given string with spaces inserted between each character.
spacify("hello world") // returns "h e l l o w o r l d"The solution in Java code
Option 1:
import java.util.*; import java.util.stream.*; public class Spacify { public static String spacify(String str){ return Arrays.stream(str.split("")) .map(c -> c+" ") .collect(Collectors.joining()) .trim(); } }Option 2:
public class Spacify { public static String spacify(String str){ return str.replaceAll("", " ").trim(); } }Option 3:
How to Find the Last Digit of a Huge Number in Golang
The challenge
For a given list
[x1, x2, x3, ..., xn]compute the last (decimal) digit ofx1 ^ (x2 ^ (x3 ^ (... ^ xn))).Example:
last_digit({3, 4, 2}, 3) == 1because
3 ^ (4 ^ 2) = 3 ^ 16 = 43046721.Beware: powers grow incredibly fast. For example,
9 ^ (9 ^ 9)has more than 369 millions of digits.lastDigithas to deal with such numbers efficiently.Find the Maximum Length Difference between Lists/Arrays in Python
The challenge
You are given two arrays
a1anda2of strings. Each string is composed of letters fromatoz. Letxbe any string in the first array andybe any string in the second array.Find max(abs(length(x) − length(y)))If
a1and/ora2are empty return-1in each language except in Haskell (F#) where you will returnNothing(None).Examples:
a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"] a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"] mxdiflg(a1, a2) --> 13The solution in Python
Option 1:
How to Circularly Sort an Array in Golang
The challenge
An array is circularly sorted if the elements are sorted in ascending order but displaced, or rotated, by any number of steps.
Complete the function/method that determines if the given array of integers is circularly sorted.
Examples:
These arrays are circularly sorted (
true):[2, 3, 4, 5, 0, 1] --> [0, 1] + [2, 3, 4, 5] [4, 5, 6, 9, 1] --> [1] + [4, 5, 6, 9] [10, 11, 6, 7, 9] --> [6, 7, 9] + [10, 11] [1, 2, 3, 4, 5] --> [1, 2, 3, 4, 5] [5, 7, 43, 987, -9, 0] --> [-9, 0] + [5, 7, 43, 987] [1, 2, 3, 4, 1] --> [1] + [1, 2, 3, 4]While these are not (
false):Largest Number Groupings in String in Python
The challenge
You are be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros.
For example,
solve("gh12cdy695m1") = 695, because this is the largest of all number groupings.The solution in Python code
Option 1:
import re def solve(s): return max(map(int,re.findall(r"(\d+)", s)))Option 2:
def solve(s): return max(map(int,"".join(" " if x.isalpha() else x for x in s).split()))Option 3:
How to Alternate String Casing in Golang
The challenge
Write a function
toWeirdCase(weirdcasein Ruby) that accepts a string, and returns the same string with all even indexed characters in each word uppercased, and all odd indexed characters in each word lowercased. The indexing just explained is zero-based, so the zero-ith index is even, therefore that character should be uppercased and you need to start over for each word.The passed-in string will only consist of alphabetical characters and spaces(
' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').How to Sort a List of Numbers in Python
The challenge
Finish the solution so that it sorts the passed-in array/list of numbers. If the function passes in an empty array/list or null/None value then it should return an empty array/list.
Examples:
solution([1,2,3,10,5]) # should return [1,2,3,5,10] solution(None) # should return []The solution in Python code
Option 1:
def solution(nums): if not nums: return [] return sorted(nums)Option 2:
def solution(nums): return sorted(nums) if nums else []Option 3:
def solution(nums): return sorted(nums or [])Test cases to validate our solution
import test from solution import solution @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(solution([1,2,3,10,5]), [1,2,3,5,10]) test.assert_equals(solution(None), []) test.assert_equals(solution([]), []) test.assert_equals(solution([20,2,10]), [2,10,20]) test.assert_equals(solution([2,20,10]), [2,10,20])How to Validate Usernames with Regex in Java
The challenge
Write a simple regex to validate a username. Allowed characters are:
- lowercase letters,
- numbers,
- underscore
Length should be between 4 and 16 characters (both included).
The solution in Java code
Option 1:
public class PasswordValidation { public static boolean validateUsr(String s) { return s.matches("[a-z_\\d]{4,16}"); } }Option 2:
import java.util.regex.Pattern; public class PasswordValidation { private static final Pattern usernamePattern = Pattern.compile("[a-z0-9_]{4,16}"); public static boolean validateUsr(String s) { return usernamePattern.matcher(s).matches(); } }Option 3:
Sort Lexicographical Order of Substrings in Java
The challenge
Given two arrays of strings
a1anda2return a sorted arrayrin lexicographical order of the strings ofa1which are substrings of strings ofa2.Example 1:
a1 = ["arp", "live", "strong"]a2 = ["lively", "alive", "harp", "sharp", "armstrong"]returns
["arp", "live", "strong"]Example 2:
a1 = ["tarp", "mice", "bull"]a2 = ["lively", "alive", "harp", "sharp", "armstrong"]returns
[]The solution in Java code
Option 1:
How to Perform Alphabetical Addition in Java
The challenge
Your task is to add up letters to one letter.
The function will be given an array of single-character Strings, each one being a letter to add.
Notes:
- Letters will always be lowercase.
- Letters can overflow (see second to last example of the description)
- If no letters are given, the function should return
'z'
Examples:
addLetters("a", "b", "c") = "f" addLetters("a", "b") = "c" addLetters("z") = "z" addLetters("z", "a") = "a" addLetters("y", "c", "b") = "d" // notice the letters overflowing addLetters() = "z"The solution in Java code
Option 1:
Roman Numerals Decoder in Golang
The challenge
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII). The Roman numeral for 1666, “MDCLXVI”, uses each letter in descending order.
How to Subtract from Time in Golang
The challenge
Clock shows
hhours,mminutes andsseconds after midnight.Your task is to write a function that returns the time since midnight in milliseconds.
Example:
h = 0 m = 1 s = 1 result = 61000Input constraints:
0 <= h <= 230 <= m <= 590 <= s <= 59
The solution in Golang
Option 1:
package solution func Past(h, m, s int) int { return (h*3600000 + m*60000 + s*1000) }Option 2:
How to Encrypt Words in Java
The challenge
You want to create secret messages which must be deciphered.
Here are the conditions:
- Your message is a string containing space separated words.
- You need to encrypt each word in the message using the following rules:
- The first letter must be converted to its ASCII code.
- The second letter must be switched with the last letter
- Keepin’ it simple: There are no special characters in the input.
Examples:
Bit Counting in Golang
The challenge
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of
1234is10011010010, so the function should return5in this caseThe solution in Golang
Option 1:
package solution import "math/bits" func CountBits(n uint) int { return bits.OnesCount(n) }Option 2:
How to Find Next Higher Number with Same Bits in Golang
The challenge
Find the next higher number (int) with same ‘1’- Bits.
I.e. as much
1bits as before and output next higher than input. Input is always an int in between 1 and 1«30 (inclusive). No bad cases or special tricks…Examples:
Input: 129 => Output: 130 (10000001 => 10000010) Input: 127 => Output: 191 (01111111 => 10111111) Input: 1 => Output: 2 (01 => 10) Input: 323423 => Output: 323439 (1001110111101011111 => 1001110111101101111)The solution in Golang
Option 1:
How to Find the First Non-Repeating Character in Golang
The challenge
Write a function named
first_non_repeating_letterthat takes a string input, and returns the first character that is not repeated anywhere in the string.For example, if given the input
'stress', the function should return't', since the letter t only occurs once in the string, and occurs first in the string.As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input
'sTreSS'should return'T'.How to Find the Last Fibonacci Digit in Golang
The challenge
Return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).
LastFibDigit(1) == 1 LastFibDigit(2) == 1 LastFibDigit(3) == 2 LastFibDigit(1000) == 5 LastFibDigit(1000000) == 5The solution in Golang
Option 1:
package solution func LastFibDigit(n int) int { n %= 60 a, b := 0, 1 for i := 0; i<n; i++ { a, b = b, a+b } return a % 10 }Option 2:
How to Validate an IP Address in Golang
The challenge
Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between `` and
255, inclusive.Valid inputs examples:
1.2.3.4 123.45.67.89Invalid input examples:
1.2.3 1.2.3.4.5 123.456.78.90 123.045.067.089Notes:
- Leading zeros (e.g.
01.02.03.04) are considered invalid - Inputs are guaranteed to be a single string
The solution in Golang
Option 1:
package solution import "net" func Is_valid_ip(ip string) bool { if r := net.ParseIP(ip); r == nil { return false } return true }Option 2:
How to Fold an Array in Java
The challenge
In this challenge, you have to write a method that folds a given array of integers by the middle x-times.
An example says more than a thousand words:
Fold 1-times: [1,2,3,4,5] -> [6,6,3] A little visualization (NOT for the algorithm but for the idea of folding): Step 1 Step 2 Step 3 Step 4 Step5 5/ 5| 5\ 4/ 4| 4\ 1 2 3 4 5 1 2 3/ 1 2 3| 1 2 3\ 6 6 3 ----*---- ----* ----* ----* ----* Fold 2-times: [1,2,3,4,5] -> [9,6]As you see, if the count of numbers is odd, the middle number will stay. Otherwise, the fold-point is between the middle-numbers, so all numbers would be added in a way.
Formatting Strings with Fmt in Golang
Fmtprovides printing to standard output (usually the console) and formatting of strings capabilities.The basics of Print and Println
The main difference between
fmt.Printandfmt.Printlnis that you only get a newline/carriage return by default with the second one. Other than that, you can make use of either for string formatting.Firstly, we need to import the
fmtmodule as follows:package main import "fmt" // <--- include fmt func main() { // main }Example of fmt.Print
fmt.Print("This is a Print test") // "This is a Print test"This will print to standard output without a newline at the end.
Delete Occurrences of an Element if it occurs more than N times in Java
The challenge
Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].
Examples
// return [20,37,21] EnoughIsEnough.deleteNth(new int[] {20,37,20,21}, 1) // return [1, 1, 3, 3, 7, 2, 2, 2] EnoughIsEnough.deleteNth(new int[] {1,1,3,3,7,2,2,2,2}, 3)The solution in Java code
Option 1:
How to Read from Standard Input in Golang
Reading from “standard input” is really useful if you are making a command-line application and require user input.
package main import ( "bufio" "os" "fmt" ) func main() { reader := bufio.NewReader(os.Stdin) s, _ := reader.ReadString('\n') fmt.Printf(s) }First setup a new
bufioreader, then useReadStringfunction, with a default wait character, which we have set to a newline (\n).The application will pause at this point and wait for user input before proceeding.
How to Install Golang on WSL/WSL2
If you need to install Golang on WSL under Windows 10 or higher, you can follow these few steps.
First remove any old versions lying around
sudo rm -rf /usr/local/go* && sudo rm -rf /usr/local/goDetermine the latest Go version
Go to https://golang.org/dl/ and find out what the latest version is. At the time of writing this, Go is on version 1.16.
Install Go
Make sure to replace
1.16below with the updated version as required.How to Validate Phone Numbers in Java
The challenge
Write a function that accepts a string, and returns true if it is in the form of a phone number.
Assume that any integer from 0-9 in any of the spots will produce a valid phone number.Only worry about the following format:
(123) 456-7890 (don’t forget the space after the close parentheses)Examples:
"(123) 456-7890" => true "(1111)555 2345" => false "(098) 123 4567" => falseThe solution in Java code
Option 1:
How to Sort Array by Frequency in Java
The challenge
Sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value.
Solution.sortByFrequency(new int[]{2, 3, 5, 3, 7, 9, 5, 3, 7}); // Returns {3, 3, 3, 5, 5, 7, 7, 2, 9} // We sort by highest frequency to lowest frequency. // If two elements have same frequency, we sort by increasing value.The solution in Java code
Option 1:
How to Calculate String Rotation in Java
The challenge
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. The check should be case-sensitive.
For instance, take the strings “fatigue” and “tiguefa”. In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. If the second string isn’t a valid rotation of the first string, the method returns -1.
Compare Strings by Sum of Chars in Java
The challenge
Compare two strings by comparing the sum of their values (ASCII character code).
- For comparing treat all letters as UpperCase
nullshould be treated as empty strings- If the string contains other characters than letters, treat the whole string as it would be empty
Your method should return
true, if the strings are equal andfalseif they are not equal.Examples:
"AD", "BC" -> equal "AD", "DD" -> not equal "gf", "FG" -> equal "zz1", "" -> equal (both are considered empty) "ZzZz", "ffPFF" -> equal "kl", "lz" -> not equal null, "" -> equalThe solution in Java code
Option 1:
How to Add Two Integers Without Arithmetic Operator in Java
The challenge
Given two integers a, b, find The sum of them, BUT You are not allowed to use the operators + and –
Notes
- The numbers (a,b) may be positive , negative values or zeros .
- Returning value will be an integer .
- Java: the following methods are prohibited: addExact, average, collect, decrement, increment, nextAfter, nextDown, nextUp, reduce, subtractExact, sum, summing .
The following classes are prohibited: BigDecimal and BigInteger .
Examples
Counting Method VarArgs in Java
The challenge
Count how many arguments a method is called with.
Examples
args_count(1, 2, 3) -> 3 args_count(1, 2, 3, 10) -> 4The solution in Java code
Some languages refer to this as the
spread operator. In Java, this is called aVarArg, which means a Variable Amount of Arguments.Simply prepend the argument’s name with three dots (
...) and then refer to it like an array of elements.class Arguments { public static int countArgs(Object... args) { return args.length; } }Alternatively, you could also use a
streamon it:How to Sum Consecutives in Java
The challenge
You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list.
Extra credit if you solve it in one line. You can assume there is never an empty list/array and there will always be an integer.
Same meaning: 1 == 1
1 != -1
Examples:
[1,4,4,4,0,4,3,3,1] # should return [1,12,0,4,6,1] """So as you can see sum of consecutives 1 is 1 sum of 3 consecutives 4 is 12 sum of 0... and sum of 2 consecutives 3 is 6 ...""" [1,1,7,7,3] # should return [2,14,3] [-5,-5,7,7,12,0] # should return [-10,14,12,0]The solution in Java code
Option 1:
Replacing Occurences of Words in Java
The challenge
You are given a string. You must replace any occurrence of the sequence
coveragebycovfefe, however, if you don’t find the wordcoveragein the string, you must addcovfefeat the end of the string with a leading space.The solution in Java code
Option 1:
public class Covfefe { public static String covfefe(String tweet) { return tweet.contains("coverage") ? tweet.replaceAll("coverage", "covfefe") : tweet+" covfefe"; } }Option 2:
Convert String to LeetSpeak in Java
The challenge
Your task is to write a function
toLeetSpeakthat converts a regular english sentence to Leetspeak.More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet
Consider only uppercase letters (no lowercase letters, no numbers) and spaces.
For example:
toLeetSpeak("LEET") returns "1337"In this challenge we use a simple LeetSpeak dialect. Use this alphabet:
{ A : '@', B : '8', C : '(', D : 'D', E : '3', F : 'F', G : '6', H : '#', I : '!', J : 'J', K : 'K', L : '1', M : 'M', N : 'N', O : '0', P : 'P', Q : 'Q', R : 'R', S : '$', T : '7', U : 'U', V : 'V', W : 'W', X : 'X', Y : 'Y', Z : '2' }The solution in Java code
Option 1:
Ordered Count of Characters in Python
The challenge
Count the number of occurrences of each character and return it as a list of tuples in order of appearance. For empty output return an empty list.
Example:
ordered_count("abracadabra") == [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]The solution in Python code
Option 1:
from collections import Counter def ordered_count(input): c = Counter(input) return sorted(list(c.items()), key=lambda x: input.index(x[0]))Option 2:
def ordered_count(_input): l = [] for i in _input: if i not in l: l.append(i) return [(i, _input.count(i)) for i in l]Option 3:
Credit Card Issuer Checking in Java
The challenge
Given a credit card number we can determine who the issuer/vendor is with a few basic knowns.
Complete the function
getIssuer()that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the stringUnknown.| Card Type | Begins With | Number Length | |------------|----------------------|---------------| | AMEX | 34 or 37 | 15 | | Discover | 6011 | 16 | | Mastercard | 51, 52, 53, 54 or 55 | 16 | | VISA | 4 | 13 or 16 |Examples
Find Count of Most Frequent Item in an Array in Java
The challenge
Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return ``
Example
input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] ouptut: 5The solution in Java code
Option 1:
import java.util.*; public class Solution { public static int mostFrequentItemCount(int[] collection) { if (collection.length==0) return 0; Map<Integer, Integer> m = new HashMap<>(); for (Integer i : collection) m.merge(i, 1, Integer::sum); return Collections.max(m.values()); } }Option 2:
Return Nth Smallest Element in Java
The challenge
Given an array/list [] of integers, Find the Nth smallest element in this array of integers
Notes
- Array/list size is at least 3 .
- Array/list’s numbers could be a mixture of positives , negatives and zeros .
- Repetition in array/list’s numbers could occur, so don’t Remove Duplications .
Examples
nthSmallest({3,1,2} ,2) ==> return (2) nthSmallest({15,20,7,10,4,3} ,3) ==> return (7) nthSmallest({2,169,13,-5,0,-1} ,4) ==> return (2)The solution in Java code
Option 1:
What temperature does your Mac CPU idle at?
Sometimes you will find that your Mac is running very hot, and you may want to keep track of it over time to see if it’s persistent or only a spike.
There are tools like Intel’s Power Widget, or even the TurboBoostSwitcher that will show you graphs of these sort of things, but what about getting this information directly from the CLI?
You’re in luck!
sudo powermetrics --samplers smc | grep -i "CPU die temperature"Split String into Parts in Java
The challenge
Split a given string into different strings of equal size.
Example:
Split the below string into other strings of size #3 'supercalifragilisticexpialidocious' Will return a new string 'sup erc ali fra gil ist ice xpi ali doc iou s'Assumptions:
String length is always greater than 0 String has no spaces Size is always positiveThe solution in Java code
Option 1:
public class InParts { public static String splitInParts(String s, int partLength) { StringBuilder sb = new StringBuilder(); char[] c = s.toCharArray(); int k = 0; for (int i=0; i<c.length; i++) { sb.append(c[i]); if (k==partLength-1) { sb.append(" "); k = -1; } k++; } return sb.toString().trim(); } }Option 2:
[Solved] ERROR 1030 (HY000): Got error 168 from storage engine
If you are getting the following error in MySQL:
ERROR 1030 (HY000): Got error 168 from storage engineThen this usually means that your server has run out of disk space!
This is never a good thing, but can be resolved by simply deleting some files on the server that you don’t need.
Solution 1: Delete some files
If you have some files on the server that you can delete to free up some space, then do so.
Largest Pair Sum in Array in Python
The challenge
Given a sequence of numbers, find the largest pair sum in the sequence.
For example
[10, 14, 2, 23, 19] --> 42 (= 23 + 19) [99, 2, 2, 23, 19] --> 122 (= 99 + 23)Input sequence contains minimum two elements and every element is an integer.
The solution in Python code
Option 1:
def largest_pair_sum(numbers): return sum(sorted(numbers)[-2:])Option 2:
def largest_pair_sum(numbers): max1 = max(numbers) numbers.remove(max1) max2 = max(numbers) return max1 + max2Option 3:
Alphabet Symmetry in Python
The challenge
Consider the word
"abode". We can see that the letterais in position1andbis in position2. In the alphabet,aandbare also in positions1and2. Notice also thatdandeinabodeoccupy the positions they would occupy in the alphabet, which are positions4and5.Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word. For example,
Exes and Ohs in Java
The challenge
Check to see if a string has the same amount of ‘x’s and ‘o’s. The method must return a boolean and be case insensitive. The string can contain any char.
Examples input/output:
XO("ooxx") => true XO("xooxx") => false XO("ooxXm") => true XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true XO("zzoo") => falseThe solution in Java code
Option 1:
import java.util.*; public class XO { public static boolean getXO (String str) { Map<String, Integer> m = new HashMap<>(); m.put("x", 0); m.put("o", 0); for (int i = 0; i < str.length(); i++){ char c = str.charAt(i); if (Character.toLowerCase(c)=='x') m.put("x", m.get("x")+1); if (Character.toLowerCase(c)=='o') m.put("o", m.get("o")+1); } return m.get("x")==m.get("o"); } }Option 2:
Sum of Odd Cubed Numbers in Python
The challenge
Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return
Noneif any of the values aren’t numbers.Note: Booleans should not be considered as numbers.
The solution in Python code
Option 1:
def cube_odd(arr): if any(type(x) is not int for x in arr): return None return sum(x ** 3 for x in arr if x % 2 != 0)Option 2:
Halving Sum in Python
The challenge
Given a positive integer
n, calculate the following sum:n + n/2 + n/4 + n/8 + ...All elements of the sum are the results of integer division.
Example
25 => 25 + 12 + 6 + 3 + 1 = 47The solution in Python code
Option 1:
def halving_sum(n): total = [n] while n>=1: n = int(n/2) total.append(n) return sum(total)Option 2:
def halving_sum(n): s=0 while n: s+=n ; n>>=1 return sOption 3:
Convert a LinkedList to a String in Python
The challenge
Preloaded for you is a class, struct, or derived data type
Node(depending on the language) used to construct linked lists in this challenge:class Node(): def __init__(self, data, next = None): self.data = data self.next = nextCreate a function
stringifywhich accepts an argumentlist/$listand returns a string representation of the list. The string representation of the list starts with the value of the currentNode, specified by itsdata/$data/Dataproperty, followed by a whitespace character, an arrow, and another whitespace character (" -> "), followed by the rest of the list. The end of the string representation of a list must always end withNone. For example, given the following list:Most Digits from List in Python
The challenge
Find the number with the most digits.
If two numbers in the argument array have the same number of digits, return the first one in the array.
The solution in Python code
Option 1:
def find_longest(xs): return max(xs, key=lambda x: len(str(x)))Option 2:
def find_longest(arr): arr.sort(reverse=True) return arr[0]Option 3:
def find_longest(arr): max_lenght = 0 max_index = 0 for cur_num in arr: lenght = len(str(cur_num)) if lenght > max_lenght: max_lenght = lenght max_index = arr.index(cur_num) return arr[max_index]Test cases to validate our solution
import test from solution import find_longest @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(find_longest([1, 10, 100]), 100) test.assert_equals(find_longest([9000, 8, 800]), 9000) test.assert_equals(find_longest([8, 900, 500]), 900) test.assert_equals(find_longest([3, 40000, 100]), 40000) test.assert_equals(find_longest([1, 200, 100000]), 100000) @test.describe("Random tests") def random_tests(): from random import randint from functools import reduce sol=lambda arr: reduce(lambda a,b: b if len(str(a))<len(str(b)) else a,arr) for _ in range(40): arr=[randint(1,10**randint(1,20)) for q in range(randint(1,50))] expected = sol(arr) @test.it(f"Testing for find_longest({arr})") def _(): test.assert_equals(find_longest(arr[:]),expected)Check if all Values in Array are Smaller in Python
The challenge
You will be given an
arrayand alimitvalue. You must check that all values in the array are below or equal to the limit value. If they are, returntrue. Else, returnfalse.You can assume all values in the array are numbers.
The solution in Python code
Option 1:
def small_enough(array, limit): return True if max(array)<=limit else FalseOption 2:
def small_enough(array, limit): return max(array)<=limitOption 3:
Maximum Product from List of Integers in Python
The challenge
Given an array of integers, Find the maximum product obtained from multiplying 2 adjacent numbers in the array.
Notes
- Array/list size is at least 2.
- Array/list numbers could be a mixture of positives, negatives also zeroes .
Input >Output Examples
adjacentElementsProduct([1, 2, 3]); ==> return 6Explanation:
The maximum product is obtained from multiplying
2 * 3 = 6, and they’re adjacent numbers in the array.adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]); ==> return 50Explanation:
Max product obtained from multiplying
5 * 10 = 50 .Sum of Array Singles in Python
The challenge
You are given an array of numbers in which two numbers occur once and the rest occur only twice. Your task is to return the sum of the numbers that occur only once.
For example,
repeats([4,5,7,5,4,8]) = 15because only the numbers7and8occur once, and their sum is15. Every other number occurs twice.The solution in Python code
Option 1:
def repeats(arr): count = [] for i in arr: if i not in count: count.append(i) else: count.remove(i) return sum(count)Option 2:
Flatten and Sort an Array in Python
The challenge
Given a two-dimensional array of integers, return the flattened version of the array with all the integers in the sorted (ascending) order.
Example:
Given [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your function should return [1, 2, 3, 4, 5, 6, 7, 8, 9].
The solution in Python code
Option 1:
def flatten_and_sort(array): a = [] for b in array: for c in b: a.append(c) return sorted(a)Option 2:
Playing the Alphabet War in Python
The challenge
Introduction
There is a war and nobody knows – the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began.Task
Write a function that accepts
fightstring consists of only small letters and return who wins the fight. When the left side wins returnLeft side wins!, when the right side wins returnRight side wins!, in other case returnLet's fight again!.Sum of numbers from 0 to N in Python
The challenge
We want to generate a function that computes the series starting from 0 and ending until the given number.
Example:
Input: > 6
Output: 0+1+2+3+4+5+6 = 21
Input: > -15
Output: -15<0
Input: > 0
Output: 0=0
The solution in Python code
Option 1:
def show_sequence(n): if n == 0: return "0=0" elif n < 0: return str(n) + "<0" else: counter = sum(range(n+1)) return '+'.join(map(str, range(n+1))) + " = " + str(counter)Option 2:
Sorted? yes? no? how? ..in Python
The challenge
Complete the method which accepts an array of integers, and returns one of the following:
"yes, ascending"– if the numbers in the array are sorted in an ascending order"yes, descending"– if the numbers in the array are sorted in a descending order"no"– otherwise
You can assume the array will always be valid, and there will always be one correct answer.
Complete the method which accepts an array of integers, and returns one of the following:
How to Fix String Casing in Python
The challenge
You will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on:
- make as few changes as possible.
- if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase.
For example:
solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase. solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase. solve("coDE") = "code". Upper == lowercase. Change all to lowercase.The solution in Python code
Option 1:
How to Remove Duplicate Words from a String in Python
The challenge
Remove all duplicate words from a string, leaving only single (first) words entries.
Example:
Input:
‘alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
Output:
‘alpha beta gamma delta'
The solution in Python code
Option 1:
def remove_duplicate_words(s): def unique_list(l): ulist = [] [ulist.append(x) for x in l if x not in ulist] return ulist return ' '.join(unique_list(s.split()))Option 2:
def remove_duplicate_words(s): return ' '.join(dict.fromkeys(s.split()))Option 3:
How to Validate a Regex PIN Code in Python
The challenge
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return
true, else returnfalse.Examples
"1234" --> true "12345" --> false "a234" --> falseThe solution in Python code
Option 1:
def validate_pin(pin): return len(pin) in (4, 6) and pin.isdigit()Option 2:
import re def validate_pin(pin): return bool(re.fullmatch("\d{4}|\d{6}", pin))Option 3:
Combine strings and remove duplicates in Python
The challenge
Take 2 strings
s1ands2including only letters fromatoz. Return a new sorted string, the longest possible, containing distinct letters – each taken only once – coming from s1 or s2.Examples:
a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"The solution in Python code
Option 1 (Using a Dictionary):
def longest(a1, a2): a3 = list(dict.fromkeys(sorted(a1+a2))) return "".join(a3)Option 2 (Using a Set):
How to Repeat by String Index in Golang
The challenge
Create a function that repeats each character by the amount of it’s index value of the original string.
Examples:
accum("abcd") -> "A-Bb-Ccc-Dddd" accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" accum("cwAt") -> "C-Ww-Aaa-Tttt"The parameter of
accumis a string that includes only letters froma..zandA..Z.The solution in Golang
Option 1:
package solution import "strings" func Accum(s string) string { words := make([]string, len(s)) for i, c := range s { words[i] = strings.Title(strings.Repeat(strings.ToLower(string(c)), i+1)) } return strings.Join(words, "-") }Option 2:
How to make an arithmetic function in Java
The challenge
Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them.
aandbwill both be positive integers, andawill always be the first number in the operation, andbalways the second.The four operators are “add”, “subtract”, “divide”, “multiply”.
A few examples:
arithmetic(5, 2, "add") => returns 7 arithmetic(5, 2, "subtract") => returns 3 arithmetic(5, 2, "multiply") => returns 10 arithmetic(5, 2, "divide") => returns 2.5ArithmeticFunction.arithmetic(5, 2, "add") => returns 7 ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3 ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10 ArithmeticFunction.arithmetic(5, 2, "divide") => returns 2The solution in Java code
Option 1:
Calculate the Third Angle of a Triangle in Go
The challenge
You are given two interior angles (in degrees) of a triangle.
Write a function to return the 3rd.
Note: only positive integers will be tested.
The solution in Golang
Option 1:
package solution func OtherAngle(a int, b int) int { return 180-a-b }Option 2:
package solution func OtherAngle(a int, b int) int { if a + b > 180{ return -1 } return 180 - a - b }Option 3:
Return Short Long Short in Python
The challenge
Given 2 strings,
aandb, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty ( length `` ).For example:
solution("1", "22") # returns "1221" solution("22", "1") # returns "1221"The solution in Python code
Option 1:
def solution(a, b): if a.isdigit(): if a<b: return f"{a}{b}{a}" else: return f"{b}{a}{b}" else: if len(a)<len(b): return f"{a}{b}{a}" else: return f"{b}{a}{b}"Option 2:
Hello, Name or World in Python
The challenge
Define a method
hellothatreturns“Hello, Name!” to a givenname, or says Hello, World! if name is not given (or passed as an empty String).Assuming that
nameis aStringand it checks for user typos to return a name with a first capital letter (Xxxx).Examples:
hello "john" => "Hello, John!" hello "aliCE" => "Hello, Alice!" hello => "Hello, World!" <em># name not given</em> hello "" => "Hello, World!" <em># name is an empty String</em>The solution in Python code
Option 1:
Add Length to Strings in Python
The challenge
What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array?
add_length('apple ban') => ["apple 5", "ban 3"] add_length('you will win') => ["you 3", "will 4", "win 3"]Your task is to write a function that takes a String and returns an Array/list with the length of each word added to each element.
How to Reversing Words in a String in Python
The challenge
Write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:
As the input may have trailing spaces, you will also need to ignore unnecessary whitespace.
Example (Input –> Output)
"Hello World" --> "World Hello" "Hi There." --> "There. Hi"The solution in Python code
Option 1:
import re def reverse(st): return " ".join(re.sub('\s+', ' ', st).strip().split(" ")[::-1])Option 2:
How to Remove Duplicates from List in Python
The challenge
Define a function that removes duplicates from an array of numbers and returns it as a result.
The order of the sequence has to stay the same.
The solution in Python code
Option 1:
def distinct(seq): return list(dict.fromkeys(seq))Option 2:
distinct = lambda s: [e for i,e in enumerate(s) if e not in s[:i]]Option 3:
def distinct(seq): result = [] seen = set() for a in seq: if a not in seen: result.append(a) seen.add(a) return resultTest cases to validate our solution
import test from solution import distinct @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(distinct([1]), [1]) test.assert_equals(distinct([1, 2]), [1, 2]) test.assert_equals(distinct([1, 1, 2]), [1, 2]) test.assert_equals(distinct([1, 1, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) test.assert_equals(distinct([1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 7, 7]), [1, 2, 3, 4, 5, 6, 7])How to Format Dollars and Cents in Python
The challenge
The company you work for has just been awarded a contract to build a payment gateway. In order to help move things along, you have volunteered to create a function that will take a float and return the amount formatting in dollars and cents.
39.99 becomes $39.99The rest of your team will make sure that the argument is sanitized before being passed to your function although you will need to account for adding trailing zeros if they are missing (though you won’t have to worry about a dangling period).
Return `5` without any numbers in Python
The challenge
Write a function that always returns
5Sounds easy right? Just bear in mind that you can’t use any of the following characters:
0123456789*+-/The solution in Python code
Option 1:
def unusual_five(): return len(['a','b','c','d','e'])Option 2:
def unusual_five(): return len("five!")Option 3:
def unusual_five(): return (int(True << True << True ^ True))Option 4:
def unusual_five(): return "fiftyfive divided by eleven".count("e")Test cases to validate our solution
import test from solution import unusual_five @test.describe("Fixed Tests") def fixed_tests(): @test.it('Should return 5') def basic_test_cases(): test.assert_equals(unusual_five(),5,"lol")How to Generate Range of Integers in Python
The challenge
Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max)
Task
Implement a function named
generate_range(2, 10, 2) # should return list of [2,4,6,8,10] generate_range(1, 10, 3) # should return list of [1,4,7,10]generate_range(2, 10, 2) # should return array of [2, 4, 6, 8, 10] generate_range(1, 10, 3) # should return array of [1, 4, 7, 10]Note
- min < max
- step > 0
- the range does not HAVE to include max (depending on the step)
The solution in Python code
Option 1:
Blue/Green Deployment Techniques in AWS
What are Blue/Green Deployments?
“Blue/Green Deployments” is a software deployment methodology. A terminology to suggest two mostly equal states of potential different deployable artefacts.
Within the context of Amazon Web Services (AWS), there are a couple of ways to do this.
Let’s explore the two most common ones, then extend that theory to a third one.
Thereafter, we will touch on two more that could be looked at.
1. Route53
Update the DNS routing. With this technique, there is a duplicate stack for both the Blue and the Green environments, and Route53 is utilised to point the DNS to a specific point. It is extremely fast and simple to rollback using this method, by simply changing the DNS records back to what they were before.
How to Calculate Powers of 2 in Python
The challenge
Complete the function that takes a non-negative integer
nas input, and returns a list of all the powers of 2 with the exponent ranging from 0 ton(inclusive).Examples
n = 0 ==> [1] # [2^0] n = 1 ==> [1, 2] # [2^0, 2^1] n = 2 ==> [1, 2, 4] # [2^0, 2^1, 2^2]The solution in Python code
Option 1:
def powers_of_two(n): out = [] for i in range(n+1): out.append(2**i) return outOption 2:
How to Get Planet Name By ID in Python
The challenge
Create a function that takes in an
idand returns theplanet name.The solution in Python code
Option 1:
def get_planet_name(id): return { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus" , 8: "Neptune" }[id]Option 2:
def get_planet_name(id): return ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"][id-1]Option 3:
def get_planet_name(id): if id == 1: return "Mercury" elif id == 2: return "Venus" elif id == 3: return "Earth" elif id == 4: return "Mars" elif id == 5: return "Jupiter" elif id == 6: return "Saturn" elif id == 7: return "Uranus" elif id == 8: return "Neptune"Test cases to validate our solution
import test from solution import get_planet_name @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(get_planet_name(2), 'Venus') test.assert_equals(get_planet_name(5), 'Jupiter') test.assert_equals(get_planet_name(3), 'Earth') test.assert_equals(get_planet_name(4), 'Mars') test.assert_equals(get_planet_name(8), 'Neptune') test.assert_equals(get_planet_name(1), 'Mercury')How to Make a Directory if Not Exists in Python
If you want to create a directory in Python, but only if it doesn’t exist, you have the following option.
Using Python 3.5 or newer?
from pathlib import Path Path("/your/directory").mkdir(parents=True, exist_ok=True)Alternative option
import os if not os.path.exists("/your/directory"): os.makedirs("/your/directory")Square(n) Sum in Python
The challenge
Complete the square sum function so that it squares each number passed into it and then sums the results together.
For example, for
[1, 2, 2]it should return9because1^2 + 2^2 + 2^2 = 9.Complete the square sum function so that it squares each number passed into it and then sums the results together.
For example, for
[1, 2, 2]it should return9because1^2 + 2^2 + 2^2 = 9.How to Fill an Array in Python
The challenge
We want an array, but not just any old array, an array with contents!
Write a function that produces an array with the numbers `` to
N-1in it.For example, the following code will result in an array containing the numbers `` to
4:arr(5) # => [0,1,2,3,4]Note: The parameter is optional. So you have to give it a default value.
The solution in Python code
Option 1:
How to Fix the ‘Bad Interpreter’ Error from AWS and Python 3.7
This error often looks something like:
.zshrc: /usr/local/bin/aws: bad interpreter: /usr/local/opt/python/bin/python3.6: no such file or directoryReinstall AWSCLI
If you have started getting the
Bad Interpretererror when you callawscli, then you can easily fix it by running:brew reinstall awscliForce link the version
Then make sure to link to the correct version:
brew link --overwrite awscliRetrieve records from MSSQLServer in Python
The below Python code will create a connection to a MSSQLServer instance, and retrieve data from it back into a variable called
tblResults.# use pyodbc for database connection import pyodbc # keep our database credentials in a store secrets = { 'host': '<db_host>', 'Name': '<db_name>', 'username': '<db_username>', 'password': '<db_password>', } # create a connection string conn_str = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER=tcp:{secrets['host']};DATABASE={secrets['Name']};UID={secrets['username']};PWD={secrets['password']}" # create a connection to the database conn = pyodbc.connect(conn_str) # a reusable function to get data from def sql_get(sql, conn): cursor = conn.cursor() cursor.execute(sql) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results # some variable to use in the SQL statement below something = 13 # make a database connection and return the results into a variable tblResults = sql_get( f"""SELECT * FROM tblName WHERE something='{something}'""" , conn)How to Remove Trailing Zeroes in Python
The challenge
Numbers ending with zeros are boring.
They might be fun in your world, but not here.
Get rid of them. Only the ending ones.
1450 -> 145 960000 -> 96 1050 -> 105 -1050 -> -105The solution in Python code
Option 1:
def no_boring_zeros(n): n = str(n) for i in range(len(n)-1, 0, -1): if n[i]=="0": n = n[:-1:] else: return int(n) return int(n)Option 2:
def no_boring_zeros(n): try: return int(str(n).rstrip('0')) except ValueError: return 0Option 3:
How to use Profilers in Python
When you have performance problems in your Python application, you can use a Profiler to help you.
Step 1: Using cProfile
Your first option is to run your application with
-m cProfilein the cli.Let’s take an example application that is run as follows:
python app.pyWe can run it with a Profiler by doing the following:
python -m cProfile -o outfile app.pyThis will give you a report that shows where most of the time is spent while running your app.
If you can’t Sleep, just count Sheep in Python
The challenge
Given a non-negative integer,
3for example, return a string with a murmur:"1 sheep...2 sheep...3 sheep...". Input will always be valid, i.e. no negative integers.The solution in Python code
Option 1:
def count_sheep(n): sheep = '' for i in range(n): sheep+=f"{i+1} sheep..." return sheepOption 2:
def count_sheep(n): return ''.join(f"{i} sheep..." for i in range(1,n+1))Option 3:
def count_sheep(n): return ('{} sheep...'*n).format(*list(range(1,n+1)))Test cases to validate our solution
import test from solution import count_sheep @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(count_sheep(1), "1 sheep..."); test.assert_equals(count_sheep(2), "1 sheep...2 sheep...") test.assert_equals(count_sheep(3), "1 sheep...2 sheep...3 sheep...")Key-Value CLI Arguments in Python
If you have a CommandLine application (CLI) written in Python, you have a number of ways that you can take arguments from the user.
You could take the order from the user and assign those to variables:
import sys print( sys.argv )This will give you a list of all the space separated values.
So if your app is called like:
python app.py var1 var2 # ['app.py', 'var1', 'var2']As you can see,
sys.argvis a list and the arguments start from the second index location.How to use a Translation Table to Replace Characters in Python
Python provides the ability to create Translation Tables.
our_text = "This is an example of some text" translation_table = str.maketrans("abefilostz", "4636110572") print(our_text) #This is an example of some text print(our_text.translate(translation_table)) # Th15 15 4n 3x4mp13 06 50m3 73x7First we create a Translation Table by calling
str.maketrans(x, y, z), passing in our characters we want to translate from and to.Then we apply our
translate(table)to a string using our newly created Translation Table.How to Calculate the Sum of all Numbers in a String in Python
Let’s take the following string:
numbers = "this 1 2 3 4 5 is not a 8 9 10"How can we sum up all the numbers in this string?
print(sum([int(num) for num in numbers.split(" ") if num.isnumeric()])) #42In the above code snippet, we split the string by the space character, then loop through it and ignore anything that is not numeric. Then we sum up the numbers that are remaining.
How to Find all Permutations of a String in Python
Python comes with a very useful module called
itertools, which allows us to calculate permutations directly.from itertools import permutations perms = [''.join(p) for p in set(permutations('hello'))] print(perms) print(len(perms))This will result in 60 permutations:
#['helol', 'heoll', 'ehlol', 'eholl', 'ollhe', 'lheol', 'lhoel', 'lehol', 'leohl', 'hoell', 'holel', 'eohll', 'eolhl', 'olhel', 'olehl', 'lhelo', 'lhleo', 'lehlo', 'lelho', 'hlelo', 'hlleo', 'elhlo', 'ellho', 'lhloe', 'lhole', 'leloh', 'leolh', 'hlloe', 'hlole', 'elloh', 'elolh', 'lohel', 'loehl', 'oelhl', 'elhol', 'ohlel', 'olleh', 'holle', 'eollh', 'olhle', 'olelh', 'ehllo', 'hello', 'ohlle', 'oellh', 'llheo', 'lleho', 'llhoe', 'lleoh', 'llohe', 'lloeh', 'oehll', 'elohl', 'lohle', 'loelh', 'lolhe', 'loleh', 'hleol', 'hloel', 'ohell'] #60How to Find all Permutations without Itertools
def permutations(string): if len(string) == 1: return string recursive_perms = [] for c in string: for perm in permutations(string.replace(c,'',1)): recursive_perms.append(c+perm) return set(recursive_perms) perms = permutations('hello') print(perms) print(len(perms))This will give us 60 items:
How to Fix ‘no basic auth credentials’ with Docker and AWS ECR
If you are trying to push a Docker image to AWS ECR (Elastic Container Registry) and you get a
no basic auth credentialserror. Then you can easily fix it as follows!Replicating the
no basic auth credentialserrorYou ran something like this:
docker tag <image> <account>.dkr.ecr.<region>.amazonaws.com/<app> docker push <image> <account>.dkr.ecr.<region>.amazonaws.com/<app>You saw something like this:
Using default tag: latest The push refers to repository [<account>.dkr.ecr.<region>.amazonaws.com/<app>] 2e6d5f7bxxxx: Preparing d8db3303xxxx: Preparing 32f366d6xxxx: Preparing no basic auth credentialsHow to fix the problem
no basic auth credentialserrorHow to Reverse Words or Sentences in Python
Let’s take the following sentence:
words = "These are some words"We can use
slicesto reverse the order of the string:print( words[::-1] ) #sdrow emos era esehTLet’s say we wanted to reverse each word in the sentence, but keep the order of words.
We can once again use
slices, but we will compliment it with alist comprehension:print( " ".join([word[::-1] for word in words.split(" ")]) ) #esehT era emos sdrowHow to Reverse words without using inbuilt modules
Let’s take this a bit further. Let’s say that we were not allowed to use our cool new
slicetoy, how could we reverse a string?How to solve AttributeError: ‘int’ object has no attribute ‘split’ – make: [sharedmods] Error 1
If you get the following error while trying to install something via Homebrew
AttributeError: 'int' object has no attribute 'split' - make: *** [sharedmods] Error 1The solution to this Homebrew issue
First try to solve the actual Homebrew issues:
git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallowThis will then allow you to update:
homebrew updateThen:
brew tap aws/tap brew install aws-sam-cliWorst case scenario solution
Then you can solve it like this:
sudo rm -rf /Library/Developer/CommandLineTools sudo xcode-select --install brew doctor brew updateHow the error looks
==> Installing dependencies for aws/tap/aws-sam-cli: [email protected] ==> Installing aws/tap/aws-sam-cli dependency: [email protected] ==> ./configure --prefix=/usr/local/Cellar/[email protected]/3.8.6_2 --enable-ipv6 --datarootdir=/usr/local/Cellar/[email protected]/3.8.6_2/share --datadir=/usr/local/Cellar/python ==> make Last 15 lines from ~/Library/Logs/Homebrew/[email protected]/02.make: self.run_command(cmd_name) File "/private/tmp/[email protected]/Python-3.8.6/Lib/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/private/tmp/[email protected]/Python-3.8.6/Lib/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/private/tmp/[email protected]/Python-3.8.6/Lib/distutils/command/build_ext.py", line 340, in run self.build_extensions() File "./setup.py", line 320, in build_extensions self.detect_modules() File "./setup.py", line 1695, in detect_modules self.detect_readline_curses() File "./setup.py", line 930, in detect_readline_curses (tuple(int(n) for n in dep_target.split('.')[0:2]) AttributeError: 'int' object has no attribute 'split' make: *** [sharedmods] Error 1How to Push a Docker image to AWS ECR
By default, Docker pushes its images to Docker Hub.
While Docker Hub is a great way to share both your public and private images, you may find the rest of your infrastructure on one of the prominent cloud providers.
In this instance, you are using many of the other AWS resources, so why not use Elastic Container Registry – or ECR for short – instead?
In this guide, we will replace
<region>with your desired region in AWS. That could look something likeeu-west-2orus-east-1perhaps.Complete Guide: How to Base64 Encode a String in Python | Python Base64 Encoding Explained
How to Base64 Encode a String in Python: A Comprehensive Guide
Welcome to our comprehensive guide on how to
python base64 encodea string in Python. Whether you’re a beginner or an experienced Python developer, this guide will equip you with the knowledge and techniques to perform efficient and accurate base64 encoding. Let’s dive in and explore the world of Python base64 encoding together!Understanding Python’s base64 Module
Python’s built-in
base64module provides a convenient way to encode and decode data using the base64 encoding scheme. Before we proceed, let’s ensure we have thebase64module imported:How to Get 10 Random Numbers in Python
The
randommodule allows you to generatechoices.import random print(random.choices([i for i in range(1000)], k=10))This might give us back something like:
[635, 450, 26, 829, 786, 563, 294, 586, 893, 953]Explaining
random.choiceandrandom.choicesrandom.choicetakes asequenceas a parameter and return a single random item from it.While
random.choicestakes a sequence as a parameter and returns a few random items from it. You can specify how many random items to return by populating thek=parameter, as above.Get the Middle Character in Python
The challenge
Return the middle character of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters.
Examples:
getMiddle("test") # should return "es" getMiddle("testing") # should return "t" getMiddle("middle") # should return "dd" getMiddle("A") # should return "A"Input
A word (string) of length
0 < str < 1000(In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.Convert String to Datetime in Python
If you have a
stringand want to create aDatetimeobject out of it in Python, then you can use the Datetime Parse Time method, as follows:from datetime import datetime your_datetime = datetime.strptime('May 31 2021 1:23PM', '%Y-%m-%d')There are 2 very useful functions of
datetime, namely:strptime– Parse a stringstrftime– Format a string
A common format you may be looking for is:
%Y-%m-%d %H:%M:%SHow to Abort SQL statements after a set time in MariaDB
Sometimes you don’t want a
SELECTquery to run for more than a set amount of time.This is a roundabout way to make your server doesn’t die from slow-running queries.
Obviously, you should tweak your database and potentially run your SELECT queries through an EXPLAIN plan first. This allows you to create appropriate indexes and find why things are slow in the first place.
But: sometimes you still find yourself wanting to kill queries that may run over a certain amount of time.
Multiprocessing Pools in Python
Python ships with a
multiprocessingmodule that allows your code to run functions in parallel by offloading calls to available processors.In this guide, we will explore the concept of Pools and what a
Poolinmultiprocessingis.A Python snippet to play with
Let’s take the following code.
import random, time def calculate_something(i): time.sleep(5) print(random.randint(10, 100)*i) for i in range(5): calculate_something(i)This function will take about 5*5seconds to complete (25seconds?)
How to Double Characters in Python
The challenge
Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
double_char("String") ==> "SSttrriinngg" double_char("Hello World") ==> "HHeelllloo WWoorrlldd" double_char("1234!_ ") ==> "11223344!!__ "The solution in Python code
This can easily be done by looping through each character and appending it to a list, which we then join and return at the end:
def double_char(s): out = [] for i in s: out.append(i+""+i) return "".join(out)However, we could simplify this down to a single list comprehension:
How to Reverse Words in Python
The challenge
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps"The solution in Python code
Option 1:
def reverse_words(text): out = [] for word in text.split(" "): out.append(word[::-1]) return " ".join(out)Option 2:
def reverse_words(str): return ' '.join(s[::-1] for s in str.split(' '))Option 3:
How to Count by X in Python
The challenge
Create a function with two arguments that will return an array of the first (n) multiples of (x).
Assume both the given number and the number of times to count will be positive numbers greater than 0.
Return the results as a list.
Examples
count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10] count_by(2,5) #should return [2,4,6,8,10]The solution in Python code
Option 1:
def count_by(x, n): out = [] for i in range(n): out.append(x*(i+1)) return outOption 2:
Calculate the Sum of Pairs in Python
The challenge
Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
sum_pairs([11, 3, 7, 5], 10) # ^--^ 3 + 7 = 10 == [3, 7] sum_pairs([4, 3, 2, 3, 4], 6) # ^-----^ 4 + 2 = 6, indices: 0, 2 * # ^-----^ 3 + 3 = 6, indices: 1, 3 # ^-----^ 2 + 4 = 6, indices: 2, 4 # * entire pair is earlier, and therefore is the correct answer == [4, 2] sum_pairs([0, 0, -2, 3], 2) # there are no pairs of values that can be added to produce 2. == None/nil/undefined (Based on the language) sum_pairs([10, 5, 2, 3, 7, 5], 10) # ^-----------^ 5 + 5 = 10, indices: 1, 5 # ^--^ 3 + 7 = 10, indices: 3, 4 * # * entire pair is earlier, and therefore is the correct answer == [3, 7]Negative numbers and duplicate numbers can and will appear.
How to break a list into multiple lists (with maximum size) in Python
If you have a large list and want to create smaller lists of it, with a maximum amount of elements, then:
commands = [str(i) for i in range(100)] print(len(commands)) #100 chunks = [commands[x:x+5] for x in range(0, len(commands), 5)] print(len(chunks)) #20 print(chunks)This will look like:
[ ['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9'], ['10', '11', '12', '13', '14'], ['15', '16', '17', '18', '19'], ['20', '21', '22', '23', '24'], ['25', '26', '27', '28', '29'], ['30', '31', '32', '33', '34'], ['35', '36', '37', '38', '39'], ['40', '41', '42', '43', '44'], ['45', '46', '47', '48', '49'], ['50', '51', '52', '53', '54'], ['55', '56', '57', '58', '59'], ['60', '61', '62', '63', '64'], ['65', '66', '67', '68', '69'], ['70', '71', '72', '73', '74'], ['75', '76', '77', '78', '79'], ['80', '81', '82', '83', '84'], ['85', '86', '87', '88', '89'], ['90', '91', '92', '93', '94'], ['95', '96', '97', '98', '99'] ]Get all dates between two dates inclusive in Python
If you want to print out a list of all dates between 2 dates (a date range), then you can use the following script:
from datetime import date, timedelta start_date = date(2021, 5, 31) end_date = date(2021, 7, 28) delta = end_date - start_date for i in range(delta.days + 1): day = start_date + timedelta(days=i) print(day)This will result in the following range:
2021-05-31 2021-06-01 ... 2021-07-27 2021-07-28To make sure that you get the format you want back:
How to Append a Python Dictionary to a Pandas DataFrame
If you want to append a Python dictionary to a Pandas DataFrame, you can do this:
# Create a new DataFrame output = pd.DataFrame() # Append the dictionary by ignoring the index output = output.append(dictionary, ignore_index=True) # View the new DataFrame print(output.head())Notice the reassignment
output = output.append(...)Get Secret from AWS Secrets Manager in Python
You can store secrets in AWS Secret Manager and reference their ARN in AWS Systems Secret Manager.
The below snippet allows you to specify the associated
parameterto get the secret value.import boto3 ssm = boto3.client('ssm') secretsmanager = boto3.client('secretsmanager') parameter = ssm.get_parameter(Name="/your/parameter/name", WithDecryption=True) secret = secretsmanager.get_secret_value(SecretId=parameter['Parameter']['Value']) secret = json.loads(secret['SecretString']) print(secret)How to do Binary Addition in Python
The challenge
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before or after the addition.
The binary number returned should be a string.
Examples:
add_binary(1, 1) == "10" (1 + 1 = 2 in decimal or 10 in binary) add_binary(5, 9) == "1110" (5 + 9 = 14 in decimal or 1110 in binary)The solution in Python code
There are multiple ways to solve an
int to binary stringproblem in Python.How to Auto-Adjust Excel column widths with pandas.ExcelWriter
You have successfully written your
pandasDataframeto an Excel file, but when you open it, all the columns are squashed up against each other.There is an easy fix to auto-adjusting your column widths.
Auto Adjusting Column Widths in Pandas
writer = pd.ExcelWriter('file.xlsx') df.to_excel(writer, sheet_name='sheetName', index=False, na_rep='NaN') for column in df: column_length = max(df[column].astype(str).map(len).max(), len(column)) col_idx = df.columns.get_loc(column) writer.sheets['sheetName'].set_column(col_idx, col_idx, column_length) writer.save()How to Sort the Odd in Python
The challenge
You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.
Examples
[7, 1] => [1, 7] [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]The solution in Python code
Option 1:
Calculate the Sum of the two lowest positive integers in Python
The challenge
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like
[19, 5, 42, 2, 77], the output should be7.[10, 343445353, 3453445, 3453545353453]should return3453455.The solution in Python code
Option 1:
def sum_two_smallest_numbers(numbers): return sum(sorted(numbers)[:2])Option 2:
def sum_two_smallest_numbers(num_list): num_list.sort() return num_list[0] + num_list[1]Option 3:
Unique In Order in Python
The challenge
Implement the function
unique_in_orderwhich takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.For example:
unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3]The solution in Python code
Option 1:
def unique_in_order(iterable): result = [] prev = None for char in iterable[0:]: if char != prev: result.append(char) prev = char return resultOption 2:
How to Change the Hostname on Linux
On Linux, you can change the
hostnameby using thehostnamectlcommand.How to Set the Hostname on Linux
sudo hostnamectl set-hostname <new-hostname>For example:
sudo hostnamectl set-hostname server1At this point, you will need to logout and back in to see the changes have taken effect.
How to Deploy a Docker Container to Kubernetes
Once you have a Docker container, it is really simple to deploy containers to Kubernetes.
Generate a Deployment YAML
kubectlprovides a fantastic way to help generate deployment yamls.kubectl create deployment <app_name> --image=<some/image> --dry-run=client -o yaml > <deployment_file_name>.yamlPerform the Deployment
Now that we have a deployment yaml, we can simply run:
kubectl apply -f <deployment_file_name>.yamlWhat next?
Next you might want to add a Service so that the deployment is available to the world.
How to Replace Characters with Alphabet Positions in Python
The challenge
Given a string, replace every letter with its position in the alphabet.
If anything in the text isn’t a letter, ignore it and don’t return it.
"a" = 1,"b" = 2, etc.Example
alphabet_position("The sunset sets at twelve o'clock.")Should return
"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"(as a string)Returning Highest and Lowest in Python
The challenge
You are given a string of space-separated numbers and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1" high_and_low("1 2 -3 4 5") # return "5 -3" high_and_low("1 9 3 4 -5") # return "9 -5"Notes:
- All numbers are valid
Int32, no need to validate them. - There will always be at least one number in the input string.
- Output string must be two numbers separated by a single space, and highest number is first.
The solution in Python code
Option 1:
How to Subtract Arrays in Python
The challenge
Implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list
a, which are present in listbkeeping their order.arrayDiff([1,2],[1]) == [2]If a value is present in
b, all of its occurrences must be removed from the other:arrayDiff([1,2,2,2,3],[2]) == [1,3]The solution in Python
Option 1:
def array_diff(a, b): return [x for x in a if x not in b]Option 2:
How to Detect if Numbers are in Order in Golang
The challenge
In this challenge, your function receives an array of integers as input. Your task is to determine whether the numbers are in ascending order. An array is said to be in ascending order if there are no two adjacent integers where the left integer exceeds the right integer in value.
For the purposes of this challenge, you may assume that all inputs are valid, i.e. non-empty arrays containing only integers.
Alternate Capitalization in Golang
The challenge
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `` will be considered even.
For example,
capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples.The input will be a lowercase string with no spaces.
The solution in Golang
Option 1:
package solution import "unicode" func Capitalize(s string) []string { a, b := []rune(s),[]rune(s) for i := range a { if i%2 == 0 { a[i] = unicode.ToUpper(a[i]) } else { b[i] = unicode.ToUpper(b[i]) } } return []string{string(a), string(b)} }Option 2:
Check if a String is Uppercase in Golang
The challenge
Create a method
IsUpperCaseto see whether the string is ALL CAPS. For example:type MyString string MyString("c").IsUpperCase() == false MyString("C").IsUpperCase() == true MyString("hello I AM DONALD").IsUpperCase() == false MyString("HELLO I AM DONALD").IsUpperCase() == true MyString("ACSKLDFJSgSKLDFJSKLDFJ").IsUpperCase() == false MyString("ACSKLDFJSGSKLDFJSKLDFJ").IsUpperCase() == trueIn this challenge, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
How to UpperCase a String in Golang
In Go, there are multiple ways to make a
stringUpperCase, each of them are by using thestringspackage.Option 1 (
strings.ToUpper):func ToUpper(str string) stringpackage main import ( "fmt" "strings" ) func main() { str1 := "This is a Test" fmt.Println(strings.ToUpper(str1)) // "THIS IS A TEST" }Option 2 (
strings.ToTitle):func ToTitle(str string) stringpackage main import ( "fmt" "strings" ) func main() { str1 := "This is a Test" fmt.Println(strings.ToTitle(str1)) // "THIS IS A TEST" }Return the Shortest Words in Golang
The challenge
Given a string of words, return the length of the shortest word(s).
The input string will never be empty and you do not need to account for different data types.
The solution in Golang
Option 1:
package solution import "strings" func FindShort(s string) int { shortest := len(s) for _, word := range strings.Split(s, " ") { if len(word) < shortest { shortest = len(word) } } return shortest }Option 2:
How to Solve Pascal’s Triangle in Python
The challenge
Given an integer
numRows, return the first numRows of Pascal’s triangle.In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1 Output: [[1]]
Constraints:
1 <= numRows <= 30
The solution in Python code
class Solution: def generate(self, numRows: int) -> List[List[int]]: triangle = [[1]] for j in range(1, numRows): prev = triangle[-1] triangle.append([1] + [prev[i]+prev[i+1] for i in range(len(prev)-1)] + [1]) return triangleCreating a Multiplication Table for a Number in Golang
The challenge
Your goal is to return multiplication table for
numberthat is always an integer from 1 to 10.For example, a multiplication table (string) for
number == 5looks like below:1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50P. S. You can use
\nin string to jump to the next line.How to Remove Duplicates in an Array in Golang
The challenge
Remove the left-most duplicates from a list of integers and return the result.
// Remove the 3's at indices 0 and 3 // followed by removing a 4 at index 1 solve([3, 4, 4, 3, 6, 3]); // => [4, 6, 3]The solution in Golang
Option 1:
package solution func Solve(arr []int) (res []int) { visited := map[int]bool{} for i := len(arr) - 1; i >= 0; i-- { n := arr[i] if visited[n] { continue } visited[n] = true res = append([]int{n}, res...) } return }Option 2:
How to Dry Potatoes in Golang
The challenge
All we eat is water and dry matter.
John bought potatoes: their weight is 100 kilograms. Potatoes contain water and dry matter.
The water content is 99 percent of the total weight. He thinks they are too wet and puts them in an oven – at low temperature – for them to lose some water.
At the output the water content is only 98%.
What is the total weight in kilograms (water content plus dry matter) coming out of the oven?
How to Reverse or Rotate in Golang
The challenge
The input is a string
strof digits. Cut the string into chunks (a chunk here is a substring of the initial string) of sizesz(ignore the last chunk if its size is less thansz).If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.
How to use Coroutines in Kotlin
Coroutines are a way to handle multithreading in Kotlin, read more about it from the official docs:
https://kotlinlang.org/docs/coroutines-overview.html
An example of a Coroutine in Kotlin
val runBlocking = runBlocking { sleep(5) delay(1_000L) launch { delay(1_100L) note("inside launch") } note("outside launch") }Introducing the
suspendkeywordcoroutineScopesneed to be in wrappingsuspend:suspend fun coroutineFunction(): String { return coroutineScope { launch { println("test") } "we return this string" } } runBlocking { println(coroutineFunction()) }Making Asynchronous API calls using Coroutines
suspend fun call2Apis() { val call1 = async { delay(1_000L) println("got data from api1 @ ${Instant.now()}") "some data from api1" } val call2 = async P delay(1_500L) println("got data from api2 @ ${Instant.now()}") "some data from api2" } println(call1.await() + " ${Instant.now()}") println(call2.await() + " ${Instant.now()}") } runBlocking { call2Apis() } sleep(2)Sharing states between Coroutines
Simply return a
coroutineScope.The Pair Type in Kotlin
val pair: Pair<String, Int> = "myKey" to 2What is a Pair Type?
A utility class when you want to return 2 values that are not related to one another.
Some examples
val (a, b) = Pair(1, "x") println(a) // 1 println(b) // xAlterantively, you could use:
val p = Pair("x", "y") println(p) // (x, y)You can refer to it as
firstandsecondval p = Pair("x", "y") println(p.first) // x println(p.second) // yThis is great for returning multiple values from a function.
Get which Quarter of the Year in Golang
The challenge
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.
The solution in Golang
Option 1:
package solution func QuarterOf(month int) int { return (month + 2) / 3 }Option 2:
How to Sum The Strings in Python
The challenge
Create a function that takes 2 nonnegative integers in form of a string as an input, and outputs the sum (also as a string):
Example: (Input1, Input2 –>Output)
"4", "5" --> "9" "34", "5" --> "39"Notes:
- If either input is an empty string, consider it as zero.
- Inputs and the expected output will never exceed the signed 32-bit integer limit (
2^31 - 1)
The solution in Python code
Option 1:
Fixing: ImmutableService requires getRowNodeId() callback to be implemented, your row data need IDs
If you have gotten this error before, then you have been trying to implement a
rowDatamapping onto Ag-Grid.. and failed!ImmutableService requires getRowNodeId() callback to be implemented, your row data need IDsHow to fix the ‘Your row data need IDs’ error
The good thing, is that it’s actually quite an easy fix:
Make sure that you have implemented the
getRowNodeIdfunction to return an actualid:this.getRowNodeId = function(data) { return data.id; //id is a field here };Worst case scenario, you could always return a random number here, but that is not recommended; but it certainly does help if you’re in a sticky situation:
How to Undo the most recent local commits in Git
If you have accidentally committed the wrong files into Git, but haven’t yet pushed it to the server, you can recover, or undo your commit as follows:
How to Undo a Commit and Redo it
You have just committed a file, and find yourself here;
We will call this “your accident location”.
Step 1
git commit -m "This is what you've just done"Step 2
Start by resetting:
git reset HEAD~Step 3
Now you can edit your files as required.
Deconstruction in Kotlin
There are times when you need to extract an object into a number of variables.
Let’s take the example below:
val (id, name, position, department) = employeeIn Kotlin, this is known as a
destructuring declaration. These new variables can now be used independently.The compilation thereof would look something like this, but is not required:
val id = employee.component1() val name = employee.component2() val position = employee.component3() val department = employee.component4()Returning multiple values from a Function
Much like deconstruction of variables and collections, functions too can return multiple values.
Playing with passphrases in Python
The challenge
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following:
choose a text in capital letters including or not digits and non alphabetic characters,
- shift each letter by a given number but the transformed letter must be a letter (circular shift),
- replace each digit by its complement to 9,
- keep such as non alphabetic and non digit characters,
- downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
- reverse the whole result.
Example:
your text: “BORN IN 2015!”, shift 1
What is a Unit in Kotlin?
Unitcorresponds to thevoidkeyword in Java.What is a
Unitin Kotlin?If you have a function that does not return a value, you can return a
Unitobject.Generally, you would return a
Unitin Kotlin where you would traditionally return avoidin Java.fun doesntReturnAnythign(): Unit { val one = 1 }How to declare a Function in Kotlin?
Functions are reusable pieces of code, often called Blocks, that as the name suggests, act as building blocks to piece together a program.
Each language has its own keyword for defining a function block.
What is
fun?The
funkeyword in Kotlin denotes a function, or method to wrap a reusable code block.funprepends the name of a function as illustrated below.fun functionName(): String { return "A String" }The structure of a Kotlin function
The function can take any number of parameters, and a return type.
The differences between Val and Var in Kotlin
Among all the many keywords that Kotlin comes with, there exists
valandvar. What are they used for? What are the differences, and why would you use one over another?They are both used to declare variables in Kotlin. But how are they different?
What is
val?valis used to declare a variable that is read-only, and who’s value does not change.Note that this only applies to the parent variable, and not it’s properties. The properties of the variable are still mutable.
Automatically Resize All Columns to Fit in Ag-Grid
If you have an Ag-Grid, and want to automatically resize all the columns to fit the width of the viewport, you can use this hack.
The implementation
/** * resizes the columns to fit the width of the grid * @param allowShrink if false, columns will NOT be resized when there is no "empty" horizontal space * https://stackoverflow.com/questions/55587083/ag-grid-sizecolumnstofit-only-when-there-is-space-available-in-the-total-grid-wi#answer-60753786 */ public resizeColumnsToFit(allowShrink = true) { if (this.gridApi) { if (allowShrink) { this.gridApi.sizeColumnsToFit(); } else { /** * this is a "hacK" - there is no way to check if there is "empty" space in the grid using the * public grid api - we have to use the internal tools here. * it could be that some of this apis will change in future releases */ const panel = this.gridApi["gridPanel"]; const availableWidth = this.gridApi["gridPanel"].eBodyViewport.clientWidth; const columns = this.gridApi["gridPanel"]["columnController"].getAllDisplayedColumns(); const usedWidth = this.gridApi["gridPanel"]["columnController"].getWidthOfColsInList(columns); if (usedWidth < availableWidth) this.gridApi.sizeColumnsToFit() } } }How to use this code
Make sure that the following is in your HTML, to trigger the
onRowDataChangedevent:How to Get All Rows in Ag-Grid
The easiest way to get the content of all rows’ data, back into a Javascript/Typescript array, is as follows.
Simply create a blank array, then loop through the rows of the grid and append each row to the array.
getAllRows() { let rowData = []; this.gridApi.forEachNode(node => rowData.push(node.data)); return rowData; }Find the Max Area of an Island in Python
The challenge
You are given an
m x nbinary matrixgrid. An island is a group of1‘s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.The area of an island is the number of cells with a value
1in the island.Return the maximum area of an island in
grid. If there is no island, return ``.Using Apache POI to Get or Create a Sheet in Excel using Java
Apache POI provides a mechanism to work with Excel documents.
However, it has a missing feature when you want to only create a new sheet if one with that name doesn’t already exist.
Luckily, it’s quite simple to get around this using the following code.
List<String> sheets = new ArrayList<>(); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { Sheet sheet = workbook.getSheetAt(i); sheets.add(sheet.getSheetName()); } Sheet sheet = sheets.contains(name) ? workbook.getSheet(name) : workbook.createSheet(name);The code uses the
workbookobject you pass it, checks to see if a sheet with the specified name exists and then only creates one if needed. Otherwise it returns a reference to the existing one.A Simplistic TCP Finite State Machine (FSM) in Python
The challenge
Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session.
The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given.
The input array of events will consist of one or more of the following strings:
How to Resolve Scaling Squared Strings in Java
The challenge
You are given a string of
nlines, each substring beingncharacters long. For example:s = "abcd\nefgh\nijkl\nmnop"We will study the “horizontal” and the “vertical” scaling of this square of strings.
A k-horizontal scaling of a string consists of replicating
ktimes each character of the string (except ‘\n’).- Example: 2-horizontal scaling of s: => “aabbccdd\neeffgghh\niijjkkll\nmmnnoopp”
A v-vertical scaling of a string consists of replicating
vtimes each part of the squared string.How to Build a Square in Python
The challenge
I will give you an integer. Give me back a shape that is as long and wide as the integer. The integer will be a whole number between 1 and 50.
Example
n = 3, so I expect a 3×3 square back just like below as a string:+++ +++ +++The solution in Python
Option 1:
def generateShape(i): return (i-1)*(('+'*i)+'\n')+('+'*i)Option 2:
def generateShape(integer): return '\n'.join('+' * integer for i in range(integer))Option 3:
Check if String EndsWith in Python
The challenge
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
strEndsWith('abc', 'bc') # returns true strEndsWith('abc', 'd') # returns falseThe solution in Python
def solution(string, ending): return string.endswith(ending)Test cases to validate our solution
test.assert_equals(solution('abcde', 'cde'), True) test.assert_equals(solution('abcde', 'abc'), False) test.assert_equals(solution('abcde', ''), True)How to add a Git Submodule to an existing codebase
Git submodules are a way of including another repository’s code into an existing codebase, without associating it’s code or tracking history in the parent repository.
Add a Git Submodule to an Existing Codebase
cd <parent_codebase_root> git submodule add <remote_url> <destination_folder>So let’s say that we have a project called
project_website, a repository at the following pathhttps://github.com/user/repo.gitand a target folder we’d like the submodule added to atuser_repo, we could construct our query like this:How to LowerCase a String in Python
Python comes with a built-in method on all
Stringtypes, by callinglower()on a String, you can immediately lower the case of that String.An example to LowerCase a String in Python
words = "These are some WORDS" words.lower() # <- How to lowerCase a String # output: these are some words"These are some WORDS".lower() # <- How to lowerCase a String # output: these are some wordsNow let’s try and see how it may look in a coding challenge:
How to Restart Sound Driver on a Mac
So for some strange reason, your audio has stopped playing through the Macbook Pro speakers, but if you plug in an external audio device, it still works? Or perhaps some other undesirable combination?
If so, you could just try restarting the computer. That usually fixes thing right?
But you have all those million apps open, all in unsaved states.. So rebooting is not the preferred approach.
Try the below option to give your Apple the kick it needs!
Number to Binary Conversion in Python
If you have a decimal number, and want to get it’s binary value, you can use the built-in
binmethod.decimal = 32 binary = bin(decimal) # '0b100000'We can see that it prepends the string with a
0b.Let’s remove this to return a usable binary value:
decimal = 32 binary = str(bin(decimal)[2:]) # '100000'Counting Binary Gaps with Python
The challenge
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
How to Delete a Secret in Kubernetes
Once you have a secret in Kubernetes, if you know it’s name, you can delete it.
How to find the secret name
You can get the secret name as follows:
kubectl get secretsThis will produce an output similar to:
NAME TYPE DATA AGE admin-user-pass Opaque 2 11sNow that we have the secret name, we can delete the secret
Deleting a Secret in Kubernetes
kubectl delete secret admin-user-passHow to Decode a Secret in Kubernetes
Secrets in Kubernetes are encoded using
base64.If you have the secret name, you can ask for its value. If not, then learn how to get a secret in Kubernetes.
How to retrieve the value of a secret in Kubernetes
kubectl get secret admin-user-pass -o jsonpath='{.data}'This will output a JSON as follows:
{"password":"amYzOTJoZjc4MmhmOTMyaAo=","username":"YWRtaW51c2VyCg=="}How to decode the value of a secret in Kubernetes
Values are always base64 encoded, so decoding it will look like this:
How to Verify a Secret in Kubernetes
You have created a secret, and would like to retrieve it.
Get a list of all the secrets in Kubernetes
kubectl get secretsThis will result in:
NAME TYPE DATA AGE admin-user-pass Opaque 2 11sHow to view a secret in Kubernetes
Now that we have our secret’s name, we can view it directly
kubectl describe secrets/admin-user-passWith the following output:
Name: admin-user-pass Namespace: default Labels: <none> Annotations: <none> Type: Opaque Data ==== password: 12 bytes username: 5 bytesHow to Create a Secret in Kubernetes
Secrets allow applications to not hardcode
usernames,passwordsor additional information such ashostnames,IP addressesor other protected/sensitive information.Create a Secret in Kubernetes
It’s simple to create a secret in Kubernetes. It can either be done
--from-fileor--from-literal.Option 1: From a File
echo -n 'adminuser' > ./username.txt echo -n 'jf392hf782hf932h' > ./password.txt kubectl create secret generic admin-user-pass \ --from-file=./username.txt \ --from-file=./password.txtThe result will be something like:
secret/admin-user-pass createdBy default, the key name is the filename, but we could also be explicit about this:
How to Divide an Array into Chunks in PHP
If you have a single-dimensional array, and want to break it into chunks, you can use the
array_chunksmethod.It takes 3 arguments:
- The input array / original array
- The length of the new array (how many dimensions to create)
- A boolean to preserve the original keys or not
<strong>array_chunk</strong>(array $array, int $length, bool $preserve_keys=<strong>false</strong> ):arrayAn example of dividing an array into chunks
Let’s take an initial starter array with 5 values
$input_array = array('a', 'b', 'c', 'd', 'e');If we said we would like to create 2 chunks:
How to setup Certbot wildcard certificate on Apache
Certbot allows simple, quick and free provisioning of SSL certificates using LetsEncrypt.
How to install Certbot
Option 1 (recommended)
sudo snap install core; sudo snap refresh core sudo snap install --classic certbot sudo ln -s /snap/bin/certbot /usr/bin/certbotOption 2
apt update apt install certbotHow to run Certbot
If you want to run the automated setup and get your certificate installed directly to apache, then:
sudo certbot --apacheIf you only want the certificate, then:
How to retrieve a Secret from AWS Secrets Manager in the CLI
If you have stored a secret in AWS using the Secrets Manager, it is possible to use the AWS CLI to retrieve this value at a later date.
aws secretsmanager get-secret-value --secret-id <ARN>The
arnis the Amazon Resource Name, which will look something like this:aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:<region>:<account>:<secretname>Get a Secret from AWS Secrets Manager using the CLI
aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:eu-west-1:4872719xxxxx:secret:NameOfOurSecret-xxxDetermine the Last Digits of N^2 == N in Java
The challenge
Let’s call an integer number
N‘green’ ifN²ends with all of the digits ofN. Some examples:5is green, because5² = 25and25ends with5.11is not green, because11² = 121and121does not end with11.376is green, because376² = 141376and141376ends with376.Your task is to write a function
greenthat returnsnth green number, starting with1–green (1) == 1How to Expose your App through a Service in Kubernetes
Once you have deployed an application into Kubernetes, it will not be available to the outside world.
For this to be possible, you need to expose it via a Service.
Services can be exposed in 4 different ways:
- ClusterIP (default) – Exposes the Service via an internal IP to the cluster (only available internally)
- NodePort – Exposes the Service via the same port on all Nodes
- LoadBalancer – Creates an external LoadBalancer in the current cloud
- ExternalName – Maps the Service to the
externalName, and returns a CNAME record with it’s value
How to Expose your App via a Service in Kubernetes
kubectl get podsto list your available pods.How to connect to Bash on a Kubernetes pod
If you find yourself needing to jump into a Kubernetes pod to either diagnose an issue, or run a particular command, you can use the
bashconnectivity functionality available fromkubectlitself.1. Get the pod name to connect to
First, you will need the pod name you want to connect to, you can get this by running
kubectl get podsThis will return a list similar to:
$ kubectl get pods NAME READY STATUS RESTARTS AGE kubernetes-bootcamp-fb5c67579-8tghg 1/1 Running 0 7m39sTake node of the
namecell for later use.How to get the Environment variables in a Kubernetes Pod
In this comprehensive guide, you will learn how to effectively get and list environment variables within a Kubernetes pod. Understanding how to work with environment variables is essential for managing and configuring applications running in Kubernetes clusters. We will cover step-by-step instructions to retrieve the environment variables of a pod, along with in-depth explanations and practical examples for a deeper understanding. By the end of this post, you will be proficient in using kubectl commands to handle environment variables in your Kubernetes environment.
How to find out Cluster Info in Kubernetes
In Kubernetes, a
clusteris a group of machines working together.By running the
kubectl cluster-infocommand, we can find out high level information about the Kubernetes cluster, such as:- What address the cluster is running from
- Where the CoreDNS is running from
Example use of KubeCtl Cluser Info
kubectl cluster-infowill return the following:$ kubectl cluster-info Kubernetes master is running at https://998a8a4d-354e-4203-bafb-2e25d7b39269.k8s.example.com CoreDNS is running at https://998a8a4d-354e-4203-bafb-2e25d7b39269.k8s.example.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.How to get more information about the cluster
You can also append the keyword
dumpto the above command to get a full output about the cluster.How to set and use a kubeconfig in Kubernetes
The
kubeconfigfile is the main configuration file that allows access to a Kubernetes cluster.When you first create your Kubernetes cluster, you are given a generated yaml file.
How to configure the kubeconfig file
The kubectl CLI has the followings preference in which kubeconfig file to use:
- by adding the
--kubeconfig <file> - by setting a
KUBECONFIGenvironment variable - by using the
$HOME/.kube/configfile on the local machine
How to Map over a List of Lists in Java
The challenge
Write a function which maps a function over the lists in a list:
public static <T,R> R[][] gridMap(Function<T,R> fn, T[][] list)Example 1:
int[][] x = {{1,2,3}, {4,5,6}}; gridMap(e -> e + 1, x); // {{2,3,4},{5,6,7}} gridMap(e -> e * e, x); // {{1,4,9},{16,25,36}}Example 2:
char[][] x = {{'h','E','l','l','O'},{'w','O','r','L','d'}}; gridMap(e -> Character.toUpperCase(e), x); // {{'H','E','L','L','O'},{'W','O','R','L','D'}}The solution in Java code
Option 1:
import java.util.function.Function; import java.util.Arrays; public class Solution { public static <T, R> Object[][] gridMap(Function<T, R> fn, T[][] list) { return Arrays.stream(list).map(xs -> Arrays.stream(xs).map(fn).toArray()).toArray(Object[][]::new); } }Option 2:
How to Differentiate a Polynomial in Java
The challenge
Create a function that differentiates a polynomial for a given value of
x.Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer.
Assumptions:
- There will be a coefficient near each
x, unless the coefficient equals1or-1. - There will be an exponent near each
x, unless the exponent equals `` or1. - All exponents will be greater or equal to zero
Examples:
Equation.differenatiate("12x+2", 3) ==> 12 Equation.differenatiate("x^2+3x+2", 3) ==> 9The solution in Java code
Option 1:
Find the Sums of Perfect Squares in Java
The challenge
The task is simply stated. Given an integer
n(3 < n < 10<sup>9</sup>), find the length of the smallest list of perfect squares which add up ton. Come up with the best algorithm you can; you’ll need it!Examples:
sum_of_squares(17) = 2
17 = 16 + 1 (4 and 1 are perfect squares).sum_of_squares(15) = 4
15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares.sum_of_squares(16) = 1
16 itself is a perfect square.
Time constraints:
[Solved] Error: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.4.4:repackage (repackage)
If you have come across this error when trying to build and deploy your Spring Boot Maven application then this post will help you!
Error: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.4.4:repackage (repackage)How to fix the Repackage Execute Goal Error
You need to make sure you have the
mainClassexplicitly defined under yourbuild->pluginas follows:<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.example.apps.YourApplication</mainClass> </configuration> </plugin> </plugins> </build>[Solved] No main manifest attribute Solution for Jar/Maven/Gradle/Spring Boot
You’ve built a Java project and packaged a .jar file.
You are ready to run it outside your IDE, or deploy it somewhere.
When you run it using
java -jar <your.jar>it says something like this:no main manifest attribute, in /src/project/target/your-jar-1.0-SNAPSHOT.jarHow to add a Manifest file
You need to create a
META-INF/MANIFEST.MFfile with the following content:Main-Class: com.mypackage.MyClassThe class name
com.mypackage.MyClassis the main class that has the public static void main(String[] args) entry point in your application.[Solved] Error – The following untracked working tree files would be overwritten by merge
So you just tried to do a
git pulland got the following error:error: The following untracked working tree files would be overwritten by merge:How to fix Untracked Working Trees Overwritten Merge
You can fix this error by first adding and stashing your local files before performing the pull.
git add * git stash git pullHow to Strip Script Tags in PHP
If you have some HTML input submitted from a user to your application, before saving it to the database, you may want to strip all
<script>tags so that you can prevent cross site scripting attacks and other potential issues.Below we use a Regular Expression to strip the script tag out of a variable.
$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);How to Make a Spiral in Java
The challenge
Your task, is to create a NxN spiral with a given
size.For example, spiral with size 5 should look like this:
00000 ....0 000.0 0...0 00000
and with the size 10:
0000000000 .........0 00000000.0 0......0.0 0.0000.0.0 0.0..0.0.0 0.0....0.0 0.000000.0 0........0 0000000000
Return value should contain array of arrays, of `` and
1, for example for given size5result should be:[[1,1,1,1,1],[0,0,0,0,1],[1,1,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]Because of the edge-cases for tiny spirals, the size will be at least 5.
Find the Longest Common Subsequence in Java
The challenge
from Wikipedia:
The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to all sequences in a set of sequences.
It differs from problems of finding common substrings: unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences.Task
Write a function
lcsthat accepts twostrings and returns their longest common subsequence as astring. Performance matters.Find First and Last Position of Element in Sorted Array in Java
The challenge
Given an array of integers
numssorted in ascending order, find the starting and ending position of a giventargetvalue.If
targetis not found in the array, return[-1, -1].Follow up: Could you write an algorithm with
O(log n)runtime complexity?Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3:
Input: nums = [], target = 0 Output: [-1,-1]
Constraints:
Determine if Number is a Power of Three in Java
The challenge
Given an integer
n, returntrueif it is a power of three. Otherwise, returnfalse.An integer
nis a power of three, if there exists an integerxsuch thatn == 3<sup>x</sup>.Example 1:
Input: n = 27 Output: true
Example 2:
Input: n = 0 Output: false
Example 3:
Input: n = 9 Output: true
Example 4:
Input: n = 45 Output: false
Constraints:
-2<sup>31</sup> <= n <= 2<sup>31</sup> - 1
The solution in Java code
Using
Math.log(n)divided byMath.log(3)we can get adoubleback which when rounded usingMath.roundwill result in a3being returned if the input number is a power of 3.How to Count Binary Substrings in Java
The challenge
Give a string
s, count the number of non-empty (contiguous) substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.Substrings that occur multiple times are counted the number of times they occur.
Example 1:
Input: "00110011" Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Notice that some of these substrings repeat and are counted the number of times they occur. Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
Example 2:
How to Download a CSV file using Javascript
Ever wanted to generate a CSV (comma separated values) file directly from the browser, using Javascript? Instead of going to the server..
Look no further!
Create a function to download a csv file
function downloadCsv(csvData: string, filename: string) { const blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' }); const dwldLink = document.createElement("a"); const url = URL.createObjectURL(blob); const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1; //if Safari open in new window to save file with random filename. if (isSafariBrowser) dwldLink.setAttribute("target", "_blank"); dwldLink.setAttribute("href", url); dwldLink.setAttribute("download", filename+ ".csv"); dwldLink.style.visibility = "hidden"; document.body.appendChild(dwldLink); dwldLink.click(); document.body.removeChild(dwldLink); }How to use our function
// define some data const data = 'Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8\n' + '12345,abc.de,AB1234567890,USD,01-Jan-21,100,10000000,1.23\n' + '12345,abc.de,AB1234567890,USD,01-Jan-21,100,10000000,\n' + '12345,abc.de,AB1234567890,USD,01-Jan-21,100,'; // define a file name const file = 'OurFile'; // use the function downloadCsv(data, file);Array Range between Integers in Java
The challenge
Complete the function that takes two integers (
a, b, wherea < b) and return an array of all integers between the input parameters, including them.For example:
a = 1 b = 4 //[1, 2, 3, 4]The solution in Java code
Option 1:
public class Solution { public static int[] between(int a, int b) { return java.util.stream.IntStream.rangeClosed(a, b).toArray(); } }Option 2:
public class Solution { public static int[] between(int a, int b) { int length = 0; for(int k = a; k <= b; k++){ length++; } int[] array = new int[length]; int first = a; for(int i = 0; i < length; i++){ array[i] = first; first++; } return array; } }Option 3:
How to clone a table structure in MySQL
I have often needed to clone a table without it’s data in MySQL.
Oftentimes this has been because I have a continually growing temporary table and I just need to clear up some disk space. And it’s a lot faster and more guaranteed than trying to delete and optimise the table.
Clone a table structure without it’s data
Let’s say that your table in question is called table1:
create table table1tmp like table1; drop table table1; rename table table1tmp to table1;If you run the above queries either in quick succession, or altogether in a single statement, you will notice that this is a very fast method even on very big tables.
Number of Rectangles in a Grid in Java
The challenge
Given a grid of size m x n, calculate the total number of rectangles contained in this rectangle. All integer sizes and positions are counted.
Examples:
numberOfRectangles(3, 2) == 18 numberOfRectangles(4, 4) == 100Here is how the 3×2 grid works (Thanks to GiacomoSorbi for the idea):
1 rectangle of size 3×2:
[][][] [][][]2 rectangles of size 3×1:
[][][]4 rectangles of size 2×1:
[][]2 rectangles of size 2×2
[][] [][]3 rectangles of size 1×2:
Longest vowel chain in Java
The challenge
The vowel substrings in the word
codewarriorsareo,e,a,io. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring. Vowels are any ofaeiou.The solution in Java code
Option 1:
import static java.util.stream.Stream.of; interface Solution { static int solve(String s) { return of(s.split("[^aeiou]")).mapToInt(String::length).max().orElse(0); } }Option 2:
Determine Unique String Characters in Java
The challenge
In this challenge, you will be given two strings
aandband your task will be to return the characters that are not common in the two strings.For example:
solve("xyab","xzca") = "ybzc" --The first string has 'yb' which is not in the second string. --The second string has 'zc' which is not in the first string.Notice also that you return the characters from the first string concatenated with those from the second string.
Difference of Volumes of Cuboids in Java
The challenge
In this simple exercise, you will create a program that will take two lists of integers,
aandb. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboidsaandb. You must find the difference of the cuboids’ volumes regardless of which is bigger.For example, if the parameters passed are
([2, 2, 3], [5, 4, 1]), the volume ofais 12 and the volume ofbis 20. Therefore, the function should return 8.Sort by binary ones in Java
The challenge
In this example you need to implement a function that sort a list of integers based on it’s binary representation.
The rules are simple:
- sort the list based on the amount of 1’s in the binary representation of each number.
- if two numbers have the same amount of 1’s, the shorter string goes first. (ex: “11” goes before “101” when sorting 3 and 5 respectively)
- if the amount of 1’s is same, lower decimal number goes first. (ex: 21 = “10101” and 25 = “11001”, then 21 goes first as is lower)
Examples:
Binomial Expansion in Java
The challenge
Write a program that can do some algebra. Write a function
expandthat takes in an expression with a single, one character variable, and expands it. The expression is in the form(ax+b)^nwhereaandbare integers which may be positive or negative,xis any single character variable, andnis a natural number. If a = 1, no coefficient will be placed in front of the variable. If a = -1, a “-” will be placed in front of the variable.Consecutive strings in Java
The challenge
You are given an array(list)
strarrof strings and an integerk. Your task is to return the first longest string consisting of k consecutive strings taken in the array.Examples
strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2 Concatenate the consecutive strings of strarr by 2, we get: treefoling (length 10) concatenation of strarr[0] and strarr[1] folingtrashy (" 12) concatenation of strarr[1] and strarr[2] trashyblue (" 10) concatenation of strarr[2] and strarr[3] blueabcdef (" 10) concatenation of strarr[3] and strarr[4] abcdefuvwxyz (" 12) concatenation of strarr[4] and strarr[5] Two strings are the longest: "folingtrashy" and "abcdefuvwxyz". The first that came is "folingtrashy" so longest_consec(strarr, 2) should return "folingtrashy". In the same way: longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"n being the length of the string array, if
n = 0ork > nork <= 0return “”.Determine the Highest Scoring Word in Java
The challenge
Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet:
a = 1, b = 2, c = 3etc.You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid.
Solving Speed Control in Java
The challenge
In John’s car the GPS records every
sseconds the distance travelled from an origin (distances are measured in an arbitrary but consistent unit). For example, below is part of a record withs = 15:x = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25]The sections are:
0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25We can calculate John’s average hourly speed on every section and we get:
Calculate Miles per Gallon to Kilometers per Litre in Java
The challenge
Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input).
Make sure to round off the result to two decimal points. If the answer ends with a 0, it should be rounded off without the 0. So instead of 5.50, we should get 5.5.
Some useful associations relevant to this challenge:
1 Imperial Gallon = 4.54609188 litresHow to Convert an Int to a List of Ints in Python
The challenge
Given a non-negative integer, return an array / a list of the individual digits in order.
Examples:
123 => [1,2,3] 1 => [1] 8675309 => [8,6,7,5,3,0,9]The solution in Python code
Option 1:
def digitize(n): return [int(d) for d in str(n)]Option 2:
def digitize(n): return list(map(int, str(n)))Option 3:
def digitize(n): lst = [] if n == 0: return [0] while n: n,r = divmod(n,10) lst.append(r) lst.reverse() return lstTest cases to validate our solution
import test from solution import digitize @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(digitize(123), [1,2,3]) test.assert_equals(digitize(1), [1]) test.assert_equals(digitize(0), [0]) test.assert_equals(digitize(1230), [1,2,3, 0]) test.assert_equals(digitize(8675309), [8,6,7,5,3,0,9])Find the Greatest Common Divisor in Java
The challenge
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.
The inputs
xandyare always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.The solution in Java code
Option 1 (using
Euclidean Algorithm):public class GCD { public static int compute(int x, int y) { return (x % y != 0) ? compute(y, x % y) : y; } }Option 2 (using a
loop):How to Create a Circular List in Python
The challenge
Create a Circular List
A circular list is of finite size, but can infititely be asked for its previous and next elements. This is because it acts like it is joined at the ends and loops around.
For example, imagine a CircularList of
[1, 2, 3, 4]. Five invocations ofnext()in a row should return 1, 2, 3, 4 and then 1 again. At this point, five invocations ofprev()in a row should return 4, 3, 2, 1 and then 4 again.How to Guess the Sequence in Java
The challenge
You must guess a sequence and it has something to do with the number given.
Example
x = 16 result = [1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9]The solution in Java code
Option 1:
import java.util.stream.IntStream; class Challenge { static int[] sequence(int x) { return IntStream.rangeClosed(1, x) .mapToObj(String::valueOf) .sorted() .mapToInt(Integer::parseInt) .toArray(); } }Option 2:
import java.util.*; class Challenge { static int[] sequence(int x) { String arr[] = new String[x]; for(int i =1;i<=x;i++){ arr[i-1]= ""+i; } Arrays.sort(arr); int[] tor = new int[x]; for(int i = 0;i<x;i++){ tor[i] = Integer.parseInt(arr[i]); } return tor ; } }Option 3:
Reversed sequence in Java
The challenge
Build a function that returns an array of integers from n to 1 where
n>0.Example :
n=5–>[5,4,3,2,1]The solution in Java code
Option 1:
public class Sequence{ public static int[] reverse(int n) { if (n<=0) return null; int[] out = new int[n]; for (int i=n, j=0; i>0; i--) { out[j] = i; j++; } return out; } }Option 2:
import java.util.stream.IntStream; public class Sequence{ public static int[] reverse(int n) { return IntStream.range(-n, 0).map(Math::abs).toArray(); } }Option 3:
Count the Digit in Java
The challenge
Take an integer
n (n >= 0)and a digitd (0 <= d <= 9)as an integer. Square all numbersk (0 <= k <= n)between 0 and n. Count the numbers of digitsdused in the writing of all thek**2. Callnb_dig(or nbDig or …) the function takingnanddas parameters and returning this count.Examples:
n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 We are using the digit 1 in 1, 16, 81, 100. The total count is then 4. nb_dig(25, 1): the numbers of interest are 1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441 so there are 11 digits `1` for the squares of numbers between 0 and 25.Note that
121has twice the digit1.Multiply all elements in an array in Java
The challenge
Create a function
multiplyAll/multiply_allwhich takes an array of integers as an argument. This function must return another function, which takes a single integer as an argument and returns a new array.The returned array should consist of each of the elements from the first array multiplied by the integer.
Example:
multiplyAll([1, 2, 3])(2) = [2, 4, 6];You must not mutate the original array.
The solution in Java code
Option 1:
[Solved] Fatal: refusing to merge unrelated histories in Git
You have received the dreaded
fatal: refusing to merge unrelated historieserror!You might find yourself asking one of the following questions:
- What is refusing to merge unrelated histories?
- How do you combine two unrelated histories?
- What is unrelated history in git?
- How do you fix unrelated branches?
Well look no further, below you will learn how to solve this problem quickly and also learn about why it happens in the first place.
Credit Card Mask in Java
The challenge
Usually when you buy something, you’re asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don’t want that shown on your screen. Instead, we mask it.
Your task is to write a function
maskify, which changes all but the last four characters into'#'.Examples
Maskify.Maskify("4556364607935616"); // should return "############5616" Maskify.Maskify("64607935616"); // should return "#######5616" Maskify.Maskify("1"); // should return "1" Maskify.Maskify(""); // should return "" // "What was the name of your first pet?" Maskify.Maskify("Skippy"); // should return "##ippy" Maskify.Maskify("Nananananananananananananananana Batman!"); // should return "####################################man!"The solution in Java code
Option 1:
How to Reverse a Number in Java
The challenge
Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321)
Numbers should preserve their sign; i.e. a negative number should still be negative when reversed.
Examples
123 -> 321 -456 -> -654 1000 -> 1The solution in Java code
Option 1:
public class ReverseNumber { public static int reverse(int number) { int result = 0; while(number != 0) { result = result * 10 + number % 10; number = number / 10; } return result; } }Option 2:
Positions Average in Java
The challenge
Suppose you have 4 numbers:
'0', '9', '6', '4'and 3 strings composed with them:s1 = "6900690040" s2 = "4690606946" s3 = "9990494604"Compare
s1ands2to see how many positions they have in common: `` at index 3,6at index 4,4at index 8 ie 3 common positions out of ten.Compare
s1ands3to see how many positions they have in common:9at index 1, `` at index 3,9at index 5 ie 3 common positions out of ten.Determine the Date by the Day Number in Java
The challenge
What date corresponds to the
nth day of the year?
The answer depends on whether the year is a leap year or not.Write a function that will help you determine the date if you know the number of the day in the year, as well as whether the year is a leap year or not.
The function accepts the day number and a boolean valueisLeapas arguments, and returns the corresponding date of the year as a string"Month, day".
Only valid combinations of a day number andisLeapwill be tested.Correct the time-string in Java
The challenge
- You have to create a method, that corrects a given time string.
- There was a problem in addition, so many of the time strings are broken.
- Time is formatted using the 24-hour clock, so from
00:00:00to23:59:59.
Examples
"09:10:01" -> "09:10:01" "11:70:10" -> "12:10:10" "19:99:99" -> "20:40:39" "24:01:01" -> "00:01:01"The solution in Java code
Option 1:
public class Solution { public static String timeCorrect(String timestring) { if (timestring == null || !timestring.matches("^\\d{2}:\\d{2}:\\d{2}$")) { return null; } String[] split = timestring.split(":"); int h = Integer.parseInt(split[0]); int m = Integer.parseInt(split[1]); int s = Integer.parseInt(split[2]); m += s / 60; s = s % 60; h += m / 60; m = m % 60; h = h % 24; return String.format("%02d:%02d:%02d", h, m, s); } }Option 2:
Shifter Words Challenge in Java
The challenge
You probably know that some characters written on a piece of paper, after turning this sheet 180 degrees, can be read, although sometimes in a different way. So, uppercase letters “H”, “I”, “N”, “O”, “S”, “X”, “Z” after rotation are not changed, the letter “M” becomes a “W”, and Vice versa, the letter “W” becomes a “M”.
We will call a word “shifter” if it consists only of letters “H”, “I”, “N”, “O”, “S”, “X”, “Z”, “M” and “W”. After turning the sheet, this word can also be read, although in a different way. So, the word “WOW “turns into the word “MOM”. On the other hand, the word “HOME” is not a shifter.
Find Maximum and Minimum Values of a List in Java
The challenge
Make two functions,
maxandminthat take a(n) array/vector of integerslistas input and outputs, respectively, the largest and lowest number in that array/vector.Examples
max({4,6,2,1,9,63,-134,566}) returns 566 min({-52, 56, 30, 29, -54, 0, -110}) returns -110 max({5}) returns 5 min({42, 54, 65, 87, 0}) returns 0Additionally
- You may consider that there will not be any empty arrays/vectors.
The solution in Java code
Option 1:
public class Solution { public int min(int[] list) { java.util.Arrays.sort(list); return list[0]; } public int max(int[] list) { java.util.Arrays.sort(list); return list[list.length-1]; } }Option 2:
Valid Parentheses in Java
The challenge
Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return
trueif the string is valid, andfalseif it’s invalid.Examples
"()" => true ")(()))" => false "(" => false "(())((()())())" => trueConstraints
0 <= input.length <= 100Along with opening (
() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g.[],{},<>).Boggle Word Checker in Java
The challenge
Write a function that determines whether a string is a valid guess in a Boggle board, as per the rules of Boggle. A Boggle board is a 2D array of individual characters, e.g.:
[ ['I','L','A','W'], ['B','N','G','E'], ['I','U','A','O'], ['A','S','R','L'] ]Valid guesses are strings which can be formed by connecting adjacent cells (horizontally, vertically, or diagonally) without re-using any previously used cells.
For example, in the above board “BINGO”, “LINGO”, and “ILNBIA” would all be valid guesses, while “BUNGIE”, “BINS”, and “SINUS” would not.
Build a pile of Cubes in Kotlin
The challenge
Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
Which x for that sum in Kotlin
The challenge
Consider the sequence
U(n, x) = x + 2x**2 + 3x**3 + .. + nx**nwhere x is a real number and n a positive integer.When
ngoes to infinity andxhas a correct value (iexis in its domain of convergenceD),U(n, x)goes to a finite limitmdepending onx.Usually given
xwe try to findm. Here we will try to findx(x real, 0 < x < 1) whenmis given (m real, m > 0).Reverse the bits in an integer in Java
The challenge
Write a function that reverses the bits in an integer.
For example, the number
417is110100001in binary. Reversing the binary is100001011which is267.You can assume that the number is not negative.
The solution in Java code
Option 1:
import static java.lang.Integer.*; interface BitsOfInteger { static int reverse_bits(int n) { return parseInt(new StringBuilder(toBinaryString(n)).reverse() + "", 2); } }Option 2:
public class BitsOfInteger { public static int reverse_bits(int n) { return Integer.parseInt(new StringBuilder().append(Integer.toBinaryString(n)).reverse().toString(), 2); } }Option 3:
Invert values in Kotlin
The challenge
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == []The solution in Kotlin code
Option 1:
fun invert(arr: IntArray) = arr.map { -it }.toIntArray()Option 2:
fun invert(arr: IntArray): IntArray { return IntArray(arr.size){ -arr[it] } }Option 3:
fun invert(arr: IntArray): IntArray { var x = 0 while (x < arr.size) { arr[x] = arr[x] * -1 x++ } return arr }Test cases to validate our solution
import org.junit.Assert.*; import org.junit.Test class TestExample { @Test fun testFixed() { assertArrayEquals(intArrayOf(-1,-2,-3,-4,-5), invert(intArrayOf(1,2,3,4,5))) assertArrayEquals(intArrayOf(-1,2,-3,4,-5), invert(intArrayOf(1,-2,3,-4,5))) assertArrayEquals(intArrayOf(), invert(intArrayOf())) assertArrayEquals(intArrayOf(0), invert(intArrayOf(0))) } }Spring Boot no main manifest attribute, in
You have created a ./target/
.jar and have tried to run it using java -jar <app>.jaryet receive aspring boot no main manifest attribute, in <app>.jarerror.Good thing is that this is really easy to solve!
You can generate your jar as follows instead:
mvn package spring-boot:repackageOr you could adjust your pom.xml so that you can generate your jar using a simple
mvn package:<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.example.Main</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin>Another option is to specify the following parent POM:
Moduli number system in Kotlin
The challenge
A number system with moduli is defined by a vector of k moduli,
[m1,m2, ···,mk].The moduli must be
pairwise co-prime, which means that, for any pair of moduli, the only common factor is1.In such a system each number
nis represented by a string"-x1--x2-- ... --xk-"of its residues, one for each modulus. The productm1 * ... * mkmust be greater than the given numbernwhich is to be converted in the moduli number system.Smallest possible sum in Kotlin
The challenge
Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required:
if X[i] > X[j] then X[i] = X[i] - X[j]When no more transformations are possible, return its sum (“smallest possible sum”).
For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below:
X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9 X_2 = [6, 9, 6] # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6 X_3 = [6, 3, 6] # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6 X_4 = [6, 3, 3] # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3 X_5 = [3, 3, 3] # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3The returning output is the sum of the final transformation (here 9).
Floating-point Approximation in Kotlin
The challenge
Given
- a semi-inclusive interval
I = [l, u)(l is in interval I but u is not)landubeing floating numbers(0 <= l < u), - an integer
n (n > 0) - a function
f: x (float number) -> f(x) (float number)
we want to return as a list the
nvalues:f(l), f(l + d), ..., f(u -d)whered = (u - l) / nMultiplication table in Kotlin
The challenge
Create an NxN multiplication table, of size provided in parameter.
for example, when given
sizeis 3:1 2 3 2 4 6 3 6 9for given example, the return value should be:
[[1,2,3],[2,4,6],[3,6,9]]The solution in Kotlin
Option 1:
package solution object Solution { fun multiplicationTable(size: Int) = Array<IntArray>(size) { i -> (1..size).map { it * (i + 1) }.toIntArray() } }Option 2:
package solution object Solution { fun multiplicationTable(size: Int): Array<IntArray> { return Array(size){i -> IntArray(size){(it + 1) * (i + 1)}} } }Option 3:
Strip Comments in Kotlin
The challenge
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas grapes bananas !applesThe output expected would be:
apples, pears grapes bananasThe code would be called like so:
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", charArrayOf('#', '!')) // result should == "apples, pears\ngrapes\nbananas"The solution in Kotlin
Option 1:
Experimenting with a sequence of complex numbers in Kotlin
The challenge
Consider the sequence
S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)wherezis a complex number andna positive integer (n > 0).When
ngoes to infinity andzhas a correct value (iezis in its domain of convergenceD),S(n, z)goes to a finite limitlimdepending onz.Experiment with
S(n, z)to guess the domain of convergenceDofSandlimvalue whenzis inD.pt-online-schema-change Add Index
Percona has a great toolkit that allows you to perform schema changes on a MySQL or MariaDB database without any downtime, it works by creating a new table with the same schema, making the changes to it and applying triggers for insertion, deletion and all updates, all while performing your valuable schema updates for you!
How to Add an Index to a MySQL or MariaDB database without downtime
pt-online-schema-change --alter 'add index ix_<COLUMN_NAME> (<COLUMN_NAME>)' D=<DATABASE_NAME>,t=<TABLE_NAME> --dry-runSums of Parts in Kotlin
The challenge
Let us consider this example (array written in general format):
ls = [0, 1, 3, 6, 10]Its following parts:
ls = [0, 1, 3, 6, 10] ls = [1, 3, 6, 10] ls = [3, 6, 10] ls = [6, 10] ls = [10] ls = []The corresponding sums are (put together in a list):
[20, 20, 19, 16, 10, 0]The function
parts_sums(or its variants in other languages) will take as parameter a listlsand return a list of the sums of its parts as defined above.Diophantine Equation in Kotlin
The challenge
In mathematics, a Diophantine equation is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied.
In this challenge we want to find all integers
x, y(x >= 0, y >= 0) solutions of a diophantine equation of the form:x2 – 4 * y2 = n
(where the unknowns are
xandy, andnis a given positive number) in decreasing order of the positive xi.Matrix Addition in Java
The challenge
Write a function that accepts two square matrices (
N x Ntwo dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of sizeN x N(square), containing only integers.How to sum two matrices:
Take each cell
[n][m]from the first matrix, and add it with the same[n][m]cell from the second matrix. This will be cell[n][m]of the solution matrix.Numbers that are a power of their sum of digits in Java
The challenge
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let’s see both cases with the details
8 + 1 = 9 and 92 = 81
512 = 5 + 1 + 2 = 8 and 83 = 512
Integer triangles in Java
The challenge
You have to give the number of different integer triangles with one angle of 120 degrees which perimeters are under or equal a certain value. Each side of an integer triangle is an integer value.
// number of integer triangles, give_triang(max. perimeter)with sides a, b, and c integers such that:
a + b + c <= max. perimeter
See some of the following cases
// No Integer triangles with perimeter under or equal five give_triang(5) // 0 // One integer triangle of (120 degrees). It's (3, 5, 7) give_triang(15) // 1 // Three triangles: (3, 5, 7), (6, 10, 14) and (7, 8, 13) give_triang(30) // 3 // (3, 5, 7), (5, 16, 19), (6, 10, 14), (7, 8, 13) and (9, 15, 21) are the triangles with perim under or equal 50. give_triang(50) // 5The solution in Java code
Option 1:
Minimum path in squares in Java
The challenge
You’re given a square consisting of random numbers, like so:
var square = [ [1,2,3], [4,8,2], [1,5,3] ];Your job is to calculate the minimum total cost when moving from the upper left corner to the coordinate given. You’re only allowed to move right or down.
In the above example the minimum path would be:
var square = [ [1,2,3], [_,_,2], [_,_,3] ];Giving a total of 11. Start and end position are included.
Pascal’s Diagonals in Java
The challenge
Create a function that returns an array containing the first
ldigits from thenth diagonal of Pascal’s triangle.n = 0should generate the first diagonal of the triangle (the ‘ones’). The first number in each diagonal should be 1.If
l = 0, return an empty array. Assume that bothnandlwill be non-negative integers in all test cases.The solution in Java code
Option 1:
Maximum Contiguous Sum in Java
The challenge
Given an unsorted array of integer values, find the maximum positive sum of any contiguous range within the array.
An array containing only negative values can return 0. Your solution should be efficient enough to not throw a timeout exception.
Example:
// returns 24 maxContiguousSum([3, -4, 8, 7, -10, 19, -3]); // returns 5 maxContiguousSum([-8, -10, -12, -2, -3, 5]);Visual example:
[3, -4, 8, 7, -10, 19, -3] |_____________| || \/ 24The solution in Java code
Option 1:
Fibonacci Streaming in Java
The challenge
You’re going to provide a needy programmer a utility method that generates an infinite sized, sequential
IntStreamwhich contains all the numbers in a fibonacci sequence.A fibonacci sequence starts with two
1s. Every element afterwards is the sum of the two previous elements. See:1, 1, 2, 3, 5, 8, 13, ..., 89, 144, 233, 377, ...The solution in Java code
Option 1:
import java.util.function.IntSupplier; import java.util.stream.IntStream; public class Utility { public static IntStream generateFibonacciSequence() { return IntStream.generate(new IntSupplier() { int a = 0; int b = 1; @Override public int getAsInt() { int x = a + b; a = b; b = x; return a; } }); } }Option 2:
Base-2 in Java
The challenge
In this challenge you must convert integers numbers from and to a negative-base binary system.
Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this advantage is countered by an increased complexity of arithmetic operations.
To help understand, the first eight digits (in decimal) of the Base(-2) system is:
Unique digits sequence in Java
The challenge
Consider the following series:
0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...There is nothing special between numbers `` and10.Let’s start with the number
10and derive the sequence.10has digits1and. The next possible number that does not have a `1` or a is22. All other numbers between10and22have a1or a ``.From
22, the next number that does not have a2is11. Note that30is also a possibility because it is the next higher number that does not have a2, but we must select the lowest number that fits and is not already in the sequence.Palindrome integer composition in Java
The challenge
The palindromic number
595is interesting because it can be written as the sum of consecutive squares:6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595.There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that
1 = 0^2 + 1^2has not been included as this problem is concerned with the squares of positive integers.Count IP Addresses in Java
The challenge
Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.
Examples
ips_between("10.0.0.0", "10.0.0.50") == 50 ips_between("10.0.0.0", "10.0.1.0") == 256 ips_between("20.0.0.10", "20.0.1.0") == 246The solution in Java code
Option 1:
public class CountIPAddresses { public static long ipsBetween(String start, String end) { return convertToLong(end) - convertToLong(start); } private static long convertToLong(String ip) { long res = 0; for (String s : ip.split("[.]") ) res = res * 256 + Long.parseLong(s); return res; } }Option 2:
Shortest Knight Path in Java
The challenge
Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other. The positions will be passed as two arguments in algebraic notation. For example,
knight("a3", "b5")should return 1.The knight is not allowed to move off the board. The board is 8×8.
For information on knight moves, see https://en.wikipedia.org/wiki/Knight_%28chess%29
For information on algebraic notation, see https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29
All Balanced Parentheses in Java
The challenge
Write a function that makes a list of strings representing all of the ways you can balance
npairs of parenthesesExamples
balancedParens(0) returns ArrayList<String> with element: "" balancedParens(1) returns ArrayList<String> with element: "()" balancedParens(2) returns ArrayList<String> with elements: "()()","(())" balancedParens(3) returns ArrayList<String> with elements: "()()()","(())()","()(())","(()())","((()))"The solution in Java code
Option 1:
import java.util.ArrayList; public class BalancedParens { public static ArrayList <String> balancedParens (int n) { ArrayList<String> lst = new ArrayList<>(); StringBuilder sb = new StringBuilder(); dfs(sb,lst,0,0,n); return lst; } private static void dfs(StringBuilder sb, ArrayList<String> lst, int open, int close, int max) { if (close==max) { lst.add(sb.toString()); return; } if (open>close) { sb.append(')'); dfs(sb,lst,open,close+1,max); sb.deleteCharAt(sb.length()-1); } if (open<max) { sb.append('('); dfs(sb,lst,open+1,close,max); sb.deleteCharAt(sb.length()-1); } } }Option 2:
Human readable duration format in Java
The challenge
Your task in order to complete this challenge is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.
The function must accept a non-negative integer. If it is zero, it just returns
"now". Otherwise, the duration is expressed as a combination ofyears,days,hours,minutesandseconds.It is much easier to understand with an example:
//returns "1 minute and 2 seconds" TimeFormatter.formatDuration(62) //returns "1 hour, 1 minute and 2 seconds" TimeFormatter.formatDuration(3662)For the purpose of this challenge, a year is 365 days and a day is 24 hours.
Simple string expansion in Java
The challenge
Consider the following expansion:
// because "ab" repeats 3 times solve("3(ab)") == "ababab" // because "a3(b)" == "abbb", which repeats twice. solve("2(a3(b))") == "abbbabbb"Given a string, return the expansion of that string.
Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will be no letters or numbers after the last closing parenthesis.
The solution in Java code
Option 1:
class Solution{ public static String solve(String s){ String new_s = ""; for(char ch : new StringBuilder(s).reverse().toString().toCharArray()) { if(Character.isDigit(ch)) new_s = new_s.repeat(Integer.parseInt(ch + "")); if(Character.isLetter(ch)) new_s = ch + new_s; } return new_s; } }Option 2:
Hamming Numbers in Java
The challenge
A Hamming number is a positive integer of the form 2i3j5k, for some non-negative integers i, j, and k.
Write a function that computes the _n_th smallest Hamming number.
Specifically:
- The first smallest Hamming number is 1 = 235
- The second smallest Hamming number is 2 = 2135
- The third smallest Hamming number is 3 = 2315
- The fourth smallest Hamming number is 4 = 2235
- The fifth smallest Hamming number is 5 = 2351
The 20 smallest Hamming numbers are given in example test fixture.
Block sequence in Java
The challenge
Consider the following array:
[1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...]If we join these blocks of numbers, we come up with an infinite sequence which starts with
112123123412345123456.... The list is infinite.You will be given an number (
n) and your task will be to return the element at that index in the sequence, where1 ≤ n ≤ 10^18. Assume the indexes start with1, not ``. For example:Roman Numerals Helper in Java
The challenge
Create a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Closest pair of points in linearithmic time in Java
The challenge
Given a number of points on a plane, your task is to find two points with the smallest distance between them in linearithmic O(n log n) time.
Example
1 2 3 4 5 6 7 8 9 1 2 . A 3 . D 4 . F 5 . C 6 7 . E 8 . B 9 . GFor the plane above, the input will be:
Find sum of top-left to bottom-right diagonals in Java
The challenge
Given a square matrix (i.e. an array of subarrays), find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on…
Examples
array = [[1, 2], [3, 4]] diagonal sum: 1 + 4 = 5array = [[5, 9, 1, 0], [8, 7, 2, 3], [1, 4, 1, 9], [2, 3, 8, 2]] diagonal sum: 5 + 7 + 1 + 2 = 15The solution in Java code
Option 1:
Sweeping trees in Java
The challenge
You will be given a list of strings representing nodes in a rooted tree. A visual representation of a very simple rooted tree could be:
+----+ |root| ++--++ | | +----+ +----+ v v +------+ +------+ |node A| |node B| +------+ +------+In this case, the root node has two children, nodes A and B. A more complex example would be:
+----+ |root| ++--++ | | +----+ +----+ v v +------+ +------+ |node A| |node B| +--+---+ +------+ | +-------------+ v v +------+ +------+ |Node C| |node D| +------+ +------+Here, The root has two children (nodes A and B), and node A in turn also has two children (nodes C and D). Each of these node strings contains three comma-separated values in the given order:
Detect Pangram in Java
The challenge
A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence “The quick brown fox jumps over the lazy dog” is a pangram, because it uses the letters A-Z at least once (case is irrelevant).
Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation.
The solution in Java code
Option 1 (using a Character loop):
Remove the parentheses in Java
The challenge
In this challenge you are given a string for example:
"example(unwanted thing)example"Your task is to remove everything inside the parentheses as well as the parentheses themselves.
The example above would return:
"exampleexample"Notes
- Other than parentheses only letters and spaces can occur in the string. Don’t worry about other brackets like
"[]"and"{}"as these will never appear. - There can be multiple parentheses.
- The parentheses can be nested.
The solution in Java code
Option 1:
What century is it in Java
The challenge
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation.
Examples
"1999" --> "20th" "2011" --> "21st" "2154" --> "22nd" "2259" --> "23rd" "1124" --> "12th" "2000" --> "20th"The solution in Java code
Option 1:
public class Solution{ public static String whatCentury(int year) { int century = (year + 99) / 100; if (century / 10 == 1) return century + "th"; switch(century % 10) { case 1: return century + "st"; case 2: return century + "nd"; case 3: return century + "rd"; default: return century + "th"; } } }Option 2:
Lost number in number sequence in Java
The challenge
An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted.
Example:
- The starting array sequence is
[1,2,3,4,5,6,7,8,9] - The mixed array with one deleted number is
[3,2,4,6,7,8,1,9] - Your function should return the int
5.
If no number was deleted from the array and no difference with it, your function should return the int ``.
Simple string reversal in Java
The challenge
In this challenge, we are going to reverse a string while maintaining the spaces (if any) in their original place.
For example:
solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space at index 3, so the string becomes "edo cruo" solve("your code rocks") = "skco redo cruoy". solve("andrew") = "werdna"More examples in the test cases. All input will be lower case letters and in some cases spaces.
int32 to IPv4 in Java
The challenge
Take the following IPv4 address:
128.32.10.1This address has 4 octets where each octet is a single byte (or 8 bits).
- 1st octet
128has the binary representation:10000000 - 2nd octet
32has the binary representation:00100000 - 3rd octet
10has the binary representation:00001010 - 4th octet
1has the binary representation:00000001
So
128.32.10.1==10000000.00100000.00001010.00000001Because the above IP address has 32 bits, we can represent it as the unsigned 32-bit number:
2149583361Perimeter of squares in a rectangle in Java
The challenge
The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It’s easy to see that the sum of the perimeters of these squares is :
4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:
Palindrome chain length in Java
The challenge
Number is a palindrome if it is equal to the number with digits in reversed order. For example,
5,44,171,4884are palindromes, and43,194,4773are not.Write a function which takes a positive integer and returns the number of special steps needed to obtain a palindrome. The special step is: “reverse the digits, and add to the original number”. If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.
String array duplicates in Java
The challenge
You are given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array.
For example:
dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"].dup(["kelless","keenness"]) = ["keles","kenes"].
Strings will be lowercase only, no spaces. See test cases for more examples.
The solution in Java code
Option 1 (using
StringBuilders):class Solution{ public static String[] dup(String[] arr){ String[] strings = new String[arr.length]; for (int h = 0; h < arr.length; h++) { String str = arr[h]; StringBuilder sb = new StringBuilder(); char current = 0; char last = 0; for (int i = 0; i < str.length(); i++) { current = str.charAt(i); if (current!=last) sb.append(current); last = current; } strings[h] = sb.toString(); } return strings; } }Option 2 (reusing the input array):
Even or Odd Array Sum in Java
The challenge
Given a list of numbers, determine whether the sum of its elements is odd or even.
Give your answer as a string matching
"odd"or"even".If the input array is empty consider it as:
[0](array with a zero).Example:
odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or_even([0, -1, -5]) == "even"The solution in Java code
Option 1 (using
streams):public class Solution { public static String oddOrEven (int[] array) { return (java.util.Arrays.stream(array).sum()%2==0) ? "even" : "odd"; } }Option 2 (using
forloop):String Permutations in Java
The challenge
In this challenge, you have to create all permutations of an input string and remove duplicates if present. This means you have to shuffle all letters from the input in all possible orders.
Examples:
Permutations.singlePermutations("a") // ["a"] Permutations.singlePermutations("ab") // ["ab", "ba"] Permutations.singlePermutations("aabb") // ["aabb","abab","abba","baab","baba","bbaa"]The order of the permutations doesn’t matter.
The solution in Java code
Option 1:
import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import java.util.List; class Permutations { public static List<String> singlePermutations(final String s) { return permute("", s); } private static List<String> permute(final String prefix, final String s) { return s.isEmpty() ? singletonList(prefix) : s.chars() .distinct() .mapToObj(i -> (char) i) .map(c -> permute(prefix + c, takeOut(s, c))) .flatMap(List::stream) .collect(toList()); } static String takeOut(final String s, final char c) { final int i = s.indexOf(c); return s.substring(0, i) + s.substring(i + 1); } }Option 2:
Remove a Specific Element of an Array in Java
The challenge
You will be given a certain array of length
n, such thatn > 4, having positive and negative integers but there will be no zeroes and all the elements will occur once in it.We may obtain an amount of
nsub-arrays of lengthn - 1, removing one element at a time (from left to right).For each subarray, let’s calculate the product and sum of its elements with the corresponding absolute value of the quotient,
q = SubProduct/SubSum(if it is possible, SubSum cannot be 0). Then we select the array with the lowest value of|q|(absolute value)Upside down numbers in Java
The challenge
Consider the numbers
6969and9116. When you rotate them180 degrees(upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as2or5don’t yield numbers when rotated.Given a range, return the count of upside down numbers within that range. For example,
solve(0,10) = 3, because there are only3upside down numbers>= 0 and < 10. They are0, 1, 8.Rotate matrix counter-clockwise N times in Java
The challenge
In this challenge your mission is to rotate matrix counter-clockwise
Ntimes.So, you will have 2 inputs:
1) matrix 2) a number, how many times to turn itAnd the output is turned matrix.
Example:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] times_to_turn = 1It should return this:
[[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]])Note: all matrixes will be square. Also, random tests will have big numbers in the input (times to turn)
Unable to import module “lambda_function”: No module named “pymysql”
If you receive the following error message when trying to run
pymysqlon AWS Lambda:Unable to import module "lambda_function": No module named "pymysql"then you can fix this by running a Custom Lambda Layer.To do this, you can boot up an EC2 instance (or a Linux instance anywhere else) and run the following set of commands:
#create module directory mkdir -p temp/python cd temp/python #install pymysql module pip install pymysql -t . cd .. #create a zip file using installed module zip -r9 ../pymysql.zip . #create the lambda layer aws lambda publish-layer-version --layer-name pymysql \ --description "pymysql for mysql access" \ --zip-file fileb://../pymysql.zip \ --compatible-runtimes python3.8Once this is done, you will be able to head back to AWS Lambda, click on
Layersand view your custom layer waiting there for you to use!Square Matrix Multiplication in Java
The challenge
Write a function that accepts two square (
NxN) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given.How to multiply two square matrices:
We are given two matrices, A and B, of size 2×2 (note: tests are not limited to 2×2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell
[0][0]of matrix C, you need to compute:A[0][0] * B[0][0] + A[0][1] * B[1][0].Count the divisible numbers in Java
The challenge
Complete the function that takes 3 numbers
x, y and k(wherex ≤ y), and returns the number of integers within the range[x..y](both ends included) that are divisible byk.More scientifically:
{ i : x ≤ i ≤ y, i mod k = 0 }Example
Given
x = 6, y = 11, k = 2the function should return3, because there are three numbers divisible by2between6and11:6, 8, 10Averages of numbers in Java
The challenge
Get the averages of these numbers
Write a method, that gets an array of integer-numbers and return an array of the averages of each integer-number and his follower, if there is one.
Example:
Input: [ 1, 3, 5, 1, -10] Output: [ 2, 4, 3, -4.5]If the array has 0 or 1 values or is null, your method should return an empty array.
The solution in Java code
Option 1:
Decimal to Factorial and Back in Java
The challenge
Coding decimal numbers with factorials is a way of writing out numbers in a base system that depends on factorials, rather than powers of numbers.
In this system, the last digit is always `` and is in base 0!. The digit before that is either
0 or 1and is in base 1!. The digit before that is either0, 1, or 2and is in base 2!, etc. More generally, the nth-to-last digit is always0, 1, 2, ..., nand is in base n!.Vowel Count in Java
The challenge
Return the number (count) of vowels in the given string.
We will consider
a, e, i, o, uas vowels for this challenge (but noty).The input string will only consist of lower case letters and/or spaces.
The solution in Java code
Option 1:
public class Vowels { public static int getCount(String str) { int vowelsCount = 0; char[] chars = str.toCharArray(); for (char c : chars) { if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') vowelsCount++; } return vowelsCount; } }Option 2:
Equal Sides Of An Array in Java
The challenge
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return
-1.For example:
Let’s say you are given the array
{1,2,3,4,3,2,1}:
Your function will return the index3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal6.Largest 5 digit number in a series in Java
The challenge
In the following 6 digit number:
28391091is the greatest sequence of 2 consecutive digits.In the following 10 digit number:
123456789067890is the greatest sequence of 5 consecutive digits.Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five-digit integer. The number passed may be as large as 1000 digits.
Next smaller number with the same digits in Java
The challenge
Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.
For example:
nextSmaller(21) == 12 nextSmaller(531) == 513 nextSmaller(2071) == 2017Return -1 (for
Haskell: returnNothing, forRust: returnNone), when there is no smaller number that contains the same digits. Also return -1 when the next smaller number with the same digits would require the leading digit to be zero.Count of positives / sum of negatives in Java
The challenge
Given an array of integers.
Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
If the input array is empty or null, return an empty array.
Example
For input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return[10, -65].The solution in Java code
Option 1:
Find the stray number in Java
The challenge
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Examples
[1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3The solution in Java code
Option 1:
import java.util.*; class Solution { static int stray(int[] numbers) { Map<Integer, Integer> map = new HashMap<>(); for (int i=0; i<numbers.length; i++) { Integer def = map.getOrDefault(numbers[i], 0); map.put(numbers[i], ++def); } for(Integer key : map.keySet()) { System.out.println(key); System.out.println(map.get(key)); if (map.get(key)==1) return key; } return 0; } }Option 2:
4 By 4 Skyscrapers in Java
The challenge
In a grid of 4 by 4 squares you want to place a skyscraper in each square with only some clues:
- The height of the skyscrapers is between 1 and 4
- No two skyscrapers in a row or column may have the same number of floors
- A clue is the number of skyscrapers that you can see in a row or column from the outside
- Higher skyscrapers block the view of lower skyscrapers located behind them
Can you write a program that can solve this puzzle?
How to Fix: package org.junit.jupiter.api does not exist
The problem
If you have received the
package org.junit.jupiter.api deos not existerror when trying to run a JUnit Java Test with Maven, it’s because of a missing dependency in your pom.xml file.The solution
Add the following
dependencyentry to yourpom.xmlfile:<dependencies> <!-- add the junit dependency here --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> </dependencies>How to Programmatically Filter ag-Grid Columns in Angular
You can easily control the column filtering in ag-Grid by using the
getFilterInstanceandsetModelmethods associated to the column you need filtering. Once done, remember to callonFilterChangedto apply your changes.// a list of all your items you want to filter // make sure to create a list of strings // a list of numbers won't work const listOfItems = data.map((row) => row.ComeColumnItem.toString()) // get the filter instance per column const filterInstance = this.gridApi?.getFilterInstance('YourColumnName') // get the existing model in-case you want to modify it const model = this.gridApi?.getModel() // or set a new one filterInstance?.setModel({ type: 'set', values: listOfItems }) // remember to apply the changes when done! this.gridApi?.onFilterChanged()Sum by Factors in Java
The challenge
Given an array of positive or negative integers
I= [i<sub>1</sub>,..,i<sub>n</sub>]you have to produce a sorted array P of the form
[ [p, sum of all i<sub>j</sub> of I for which p is a prime factor (p positive) of i<sub>j</sub>] ...]P will be sorted by increasing order of the prime numbers. The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages.
Count the divisors of a number in Java
The challenge
Count the number of divisors of a positive integer
n.Random tests go up to
n = 500000.Examples
numberOfDivisors(4) == 3 // 1, 2, 4 numberOfDivisors(5) == 2 // 1, 5 numberOfDivisors(12) == 6 // 1, 2, 3, 4, 6, 12 numberOfDivisors(30) == 8 // 1, 2, 3, 5, 6, 10, 15, 30The solution in Java code
Option 1:
public class FindDivisor { public long numberOfDivisors(int n) { long counter = 0; for(int i=1; i<=n; i++){ if(n % i == 0){ counter++; } } return counter; } }Option 2:
My smallest code interpreter in Java
The challenge
Inspired from real-world Brainf**k, we want to create an interpreter of that language which will support the following instructions:
>increment the data pointer (to point to the next cell to the right).<decrement the data pointer (to point to the next cell to the left).+increment (increase by one, truncate overflow: 255 + 1 = 0) the byte at the data pointer.-decrement (decrease by one, treat as unsigned byte: 0 – 1 = 255 ) the byte at the data pointer..output the byte at the data pointer.,accept one byte of input, storing its value in the byte at the data pointer.[if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching]command.]if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching[command.
The function will take in input…
Pick peaks in Java
The challenge
Write a function that returns the positions and the values of the “peaks” (or local maxima) of a numeric array.
For example, the array
arr = [0, 1, 2, 5, 1, 0]has a peak at position3with a value of5(sincearr[3]equals5).The output will be returned as a “Map<String,List>
with two key-value pairs:“pos”and“peaks”. If there is no peak in the given array, simply return{“pos” => [], “peaks” => []}`.Number of trailing zeros of N in Java
The challenge
Write a program that will calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * ... * NBe careful
1000!has 2568 digits…For more info, see: http://mathworld.wolfram.com/Factorial.html
Examples
zeros(6) = 1 // 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 // 12! = 479001600 --> 2 trailing zerosThe solution in Java code
Option 1:
Alphabetic Anagrams in Java
The challenge
Consider a “word” as any sequence of capital letters A-Z (not limited to just “dictionary words”). For any word with at least two different letters, there are other words composed of the same letters but in a different order (for instance, STATIONARILY/ANTIROYALIST, which happen to both be dictionary words; for our purposes “AAIILNORSTTY” is also a “word” composed of the same letters as these two).
We can then assign a number to every word, based on where it falls in an alphabetically sorted list of all words made up of the same group of letters. One way to do this would be to generate the entire list of words and find the desired one, but this would be slow if the word is long.
Remove file from Git without deleting locally
If you find yourself in a position where you have already committed some files to git, and they are in the remote repository already, but you want to remove them from you repository without deleting them locally, you can do the following:
Introducing the
git rm --cachedcommand:Remove a folder from Git
git rm --cached -r FolderNameRemove a file from git
git rm --cached SomeFile.extAnd then what?
Now that the files have been removed from the local git cache, you should probably either commit the changes you’ve made, or add an entry to your local
.gitignorefile and then commit the changes.Recover a secret string from random triplets in Java
The challenge
There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.
A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. “whi” is a triplet for the string “whatisup”.
As a simplification, you may assume that no letter occurs more than once in the secret string.
Range Extraction in Java
The challenge
A format for expressing an ordered list of integers is to use a comma separated list of either
- individual integers
- or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, ‘-‘. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example “12,13,15-17”
Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Reversed Words in Java
The challenge
Complete the solution so that it reverses all of the words within the string passed in.
Example:
ReverseWords.reverseWords("The greatest victory is that which requires no battle"); // should return "battle no requires which that is victory greatest The"The solution in Java code
Option 1 (using
StringBuilder):public class ReverseWords{ public static String reverseWords(String str){ String[] words = str.split(" "); StringBuilder sb = new StringBuilder(); for (int i=words.length-1; i>=0; i--) { sb.append(words[i]).append(" "); } return sb.toString().trim(); } }Option 2 (using
Arrays):CamelCase Method in Java
The challenge
Write a simple
CamelCasemethod for strings.All words must have their first letter capitalized without spaces.
Example:
// "HelloCase" camelCase("hello case"); // "CamelCaseWord" camelCase("camel case word");The solution in Java code
Option 1:
public class Solution { public static String camelCase(String str) { String[] words = str.trim().split("\\s+"); if (words.length==0) return ""; StringBuilder sb = new StringBuilder(); for (int i=0; i<words.length; i++) { String word = words[i]; if (word.length()>1) { String s = word.substring(0, 1).toUpperCase() + word.substring(1, word.length()); sb.append(s); } else { sb.append(word.toUpperCase()); } } return sb.toString(); } }Option 2:
Even or Odd in Java
The challenge
Create a function that takes an integer as an argument and returns “Even” for even numbers or “Odd” for odd numbers.
The solution in Java code
public class EvenOrOdd { public static String even_or_odd(int number) { return number%2==0 ? "Even" : "Odd"; } }Test cases to validate our solution
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class EvenOrOddTest { @Test public void testEvenOrOdd() { EvenOrOdd eoo = new EvenOrOdd(); assertEquals(eoo.even_or_odd(6), "Even"); assertEquals(eoo.even_or_odd(7), "Odd"); } }Square Every Digit in Java
The challenge
You need to square every digit of a number and concatenate them.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer.
The solution in Java code
Option 1:
public class SquareDigit { public int squareDigits(int n) { String result = ""; while (n != 0) { int digit = n % 10 ; result = digit*digit + result ; n /= 10 ; } return Integer.parseInt(result) ; } }Option 2:
Simple number sequence in Java
The challenge
You are given a string of numbers in sequence and your task will be to return the missing number. If there is no number missing or there is an error in the sequence, return
-1.For example:
missing("123567") = 4 missing("899091939495") = 92 missing("9899101102") = 100 missing("599600601602") = -1 -- no number missing missing("8990919395") = -1 -- error in sequence. Both 92 and 94 missing.The sequence will always be in ascending order.
Roman Numerals Encoder in Java
The challenge
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
First Variation on Caesar Cipher in Java
The challenge
The action of a Caesar cipher is to replace each plaintext letter (plaintext letters are from ‘a’ to ‘z’ or from ‘A’ to ‘Z’) with a different one a fixed number of places up or down the alphabet.
This program performs a variation of the Caesar shift. The shift increases by 1 for each character (on each iteration).
If the shift is initially 1, the first character of the message to be encoded will be shifted by 1, the second character will be shifted by 2, etc…
Century From Year in Java
The challenge
The first century spans from the year 1 up to and including the year 100, The second – from the year 101 up to and including the year 200, etc.
Task :
Given a year, return the century it is in.
Input, Output Examples
centuryFromYear(1705) returns (18) centuryFromYear(1900) returns (19) centuryFromYear(1601) returns (17) centuryFromYear(2000) returns (20)The solution in Java code
Option 1:
public class Solution { public static int century(int number) { return (number + 99) / 100; } }Option 2:
Find the Smallest Number in Java
The challenge
You have a positive number
nconsisting of digits. You can do at most one operation: Choosing the index of a digit in the number, remove this digit at that index and insert it back to another or at the same place in the number in order to find the smallest number you can get.#Task: Return an array or a tuple or a string depending on the language (see “Sample Tests”) with
Convert Array to Tree in Java
The challenge
You are given a non-null array of integers. Implement the method arrayToTree which creates a binary tree from its values in accordance to their order, while creating nodes by depth from left to right.
For example, given the array [17, 0, -4, 3, 15] you should create the following tree:
17 / \ 0 -4 / \ 3 15The class TreeNode is available for you:
class TreeNode { TreeNode left; TreeNode right; int value; TreeNode(int value, TreeNode left, TreeNode right) { this.value = value; this.left = left; this.right = right; } TreeNode(int value) { this(value, null, null); } @Override public boolean equals(Object other) { ... // Already implemented for you and used in test cases } ... }The solution in Java code
Option 1:
Common Denominators in Java
The challenge
You will have a list of rationals in the form
{ {numer_1, denom_1} , ... {numer_n, denom_n} } or [ [numer_1, denom_1] , ... [numer_n, denom_n] ] or [ (numer_1, denom_1) , ... (numer_n, denom_n) ]where all numbers are positive ints. You have to produce a result in the form:
(N_1, D) ... (N_n, D) or [ [N_1, D] ... [N_n, D] ] or [ (N_1', D) , ... (N_n, D) ] or {{N_1, D} ... {N_n, D}} or "(N_1, D) ... (N_n, D)"depending on the language (See Example tests)
Primes in Numbers in Java
The challenge
Given a positive number n > 1 find the prime factor decomposition of n. The result will be a string with the following form :
"(p1**n1)(p2**n2)...(pk**nk)"where
a ** bmeansato the power ofbwith the p(i) in increasing order and n(i) empty if n(i) is 1.
Example: n = 86240 should return "(2**5)(5)(7**2)(11)"The solution in Java code
Option 1:
public class PrimeDecomp { public static String factors(int lst) { String result = ""; for (int fac = 2; fac <= lst; ++fac) { int count; for (count = 0; lst % fac == 0; ++count) { lst /= fac; } if (count > 0) { result += "(" + fac + (count > 1 ? "**" + count : "") + ")"; } } return result; } }Option 2:
Maximum subarray sum in Java
The challenge
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
Max.sequence(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}); // should be 6: {4, -1, 2, 1}Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Validate Credit Card Number in Java
The challenge
Let’s implement the Luhn Algorithm, which is used to help validate credit card numbers.
Given a positive integer of up to 16 digits, return
trueif it is a valid credit card number, andfalseif it is not.Here is the algorithm:
- Double every other digit, scanning from right to left, starting from the second digit (from the right).Another way to think about it is: if there are an even number of digits, double every other digit starting with the first; if there are an odd number of digits, double every other digit starting with the second:
1714 ==> [1*, 7, 1*, 4] ==> [2, 7, 2, 4] 12345 ==> [1, 2*, 3, 4*, 5] ==> [1, 4, 3, 8, 5] 891 ==> [8, 9*, 1] ==> [8, 18, 1] - If a resulting number is greater than
9, replace it with the sum of its own digits (which is the same as subtracting9from it):[8, 18*, 1] ==> [8, (1+8), 1] ==> [8, 9, 1] or: [8, 18*, 1] ==> [8, (18-9), 1] ==> [8, 9, 1] - Sum all of the final digits:
[8, 9, 1] ==> 8 + 9 + 1 = 18 - Finally, take that sum and divide it by
10. If the remainder equals zero, the original credit card number is valid.18 (modulus) 10 ==> 8 , which is not equal to 0, so this is not a valid credit card number
The solution in Java code
Option 1:
Find the unique number using Java
The challenge
There is an array with some numbers. All numbers are equal except for one. Try to find it!
Solution.findUniq(new double[]{ 1, 1, 1, 2, 1, 1 }); // => 2 Solution.findUniq(new double[]{ 0, 0, 0.55, 0, 0 }); // => 0.55It’s guaranteed that array contains at least 3 numbers.
The tests contain some very huge arrays, so think about performance.
The solution in Java code
Option 1:
import java.util.Arrays; public class Solution { public static double findUniq(double[] arr) { Arrays.sort(arr); return arr[0] == arr[1] ? arr[arr.length-1]:arr[0]; } }Option 2:
Find The Parity Outlier in Java
The challenge
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer
N. Write a method that takes the array as an argument and returns this “outlier”N.Examples
[2, 4, 0, 100, 4, 11, 2602, 36] Should return: 11 (the only odd number) [160, 3, 1719, 19, 11, 13, -21] Should return: 160 (the only even number)The solution in Java
Option 1:
Find the missing letter using Java
The challenge
Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.
You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.Example:
[‘a’,‘b’,‘c’,’d’,‘f’] -> ‘e’ [‘O’,‘Q’,‘R’,‘S’] -> ‘P’
["a","b","c","d","f"] -> "e" ["O","Q","R","S"] -> "P"(Use the English alphabet with 26 letters!)
Determine the order of braces is valid using Java
The challenge
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return
trueif the string is valid, andfalseif it’s invalid.All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces:
()[]{}.What is considered Valid?
A string of braces is considered valid if all braces are matched with the correct brace.
[Solved] PKIX path building failed: unable to find valid certification path to requested target
The problem
It may happen to you that when you try and pull some Java dependencies, you will get the annoying
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targeterror.It may look something like this:
Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.4.0 from/to tpvr-ibm (https://nexus-***.***.***.***:8081/nexus/content/repositories/tpvr-ibm): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetThe solution (recommended)
- Go to URL in your browser:
- firefox – click on HTTPS certificate chain (the lock icon right next to URL address). Click
"more info" > "security" > "show certificate" > "details" > "export..". Pickup the name and choose file type example.cer - chrome – click on site icon left to address in address bar, select “Certificate” -> “Details” -> “Export” and save in format “Der-encoded binary, single certificate”.
- firefox – click on HTTPS certificate chain (the lock icon right next to URL address). Click
- Now you have file with keystore and you have to add it to your JVM. Determine location of cacerts files
- Windows:
C:\Program Files (x86)\Java\jre1.8.0_22\lib\security\cacerts - Mac:
/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home/jre/lib/security/cacerts
- Windows:
- Next import the
example.cerfile into cacerts in command line:
What commands to run
Navigate to the security path:
How to Find the odd int in Java
The challenge
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
The solution in Java code
Option 1 (using
streams):import static java.util.Arrays.stream; public class FindOdd { public static int findIt(int[] arr) { return stream(arr).reduce(0, (x, y) -> x ^ y); } }Option 2 (using
xor):public class FindOdd { public static int findIt(int[] A) { int odd = 0; for (int i : A) { odd ^= i; } return odd; } }Option 3 (using a
TreeSet):Count the number of Duplicates in Java
The challenge
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
Example
“abcde” -> 0
# no characters repeats more than once
“aabbcde” -> 2# 'a' and 'b'
“aabBcde” -> 2# 'a' occurs twice and 'b' twice (`b` and `B`)
“indivisibility” -> 1# 'i' occurs six times
“Indivisibilities” -> 2# 'i' occurs seven times and 's' occurs twice
“aA11” -> 2# 'a' and '1'
“ABBA” -> 2# 'A' and 'B' each occur twiceCalculating Simple Max Digit Sum in Java
The challenge
In this challenge, you will be given an integer
nand your task will be to returnthe largest integer that is <= n and has the highest digit sum.For example:
solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum. solve(10) = 9 solve(48) = 48. Note that 39 is also an option, but 48 is larger.Input range is
0 < n < 1e11The String Combat Challenge in Java
The challenge
After a long conflict, the rulers of Nek and Glo have decided that a final duel should decide the fate of their countries. Each ruler will select their best knights and send them into battle, one after another. The last standing team will win the crown.
But the knights don’t want to die for nothing, so they ask you, the wise technomagican, to derive which team will win. Can you help them?
Solving Single Word Pig Latin in Java
The challenge
Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules.
So, the goal of this challenge is to write a function that encodes a single word string to pig latin.
The rules themselves are rather easy:
-
The word starts with a vowel(a,e,i,o,u) -> return the original string plus “way”.
-
The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus “ay”.
Count the Days in Java
The challenge
Little Annie is very excited for upcoming events. She want’s to know how many days she have to wait for a specific event.
Your job is to help her out.
Task: Write a function which returns the number of days from today till the given date. The function will take a Date object as parameter. You have to round the amount of days.
If the event is in the past, return “The day is in the past!”
If the event is today, return “Today is the day!”
Else, return “x days”Java HashMap Create or Increment Value
If you are using a
HashMapto keep a running total of a series of elements, then you often need to increment aHashMapitem, but if it doesn’t exist in the map yet, then you need to rather create it.There are a number of ways to do this, let’s explore some of these.
Using Merge and Sum in Java 8
My absolute favourite is to use Java 8’s ability to do the below:
Get the Strongest even number in an interval in Java
The challenge
A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n.
For example, if n = 12, then
- 12 / 2 = 6
- 6 / 2 = 3
So we divided successively 2 times and we reached 3, so the strongness of 12 is
2.If n = 16 then
What time is it? in Java
The challenge
How many times have we been asked this simple question in our daily lives by family, friends and strangers alike?
In this challenge you take a look at your watch and answer this question in proper English. Sometimes you have your watch in 24h format and others in 12h. The AM/PM part of the time is always disregarded as the asker knows whether it’s morning or afternoon.
Requirements:
- Mind the punctuation for the full hours; o’clock is written as one word.
- Spacing between individual words is strictly limited to one space. Cardinal numbers greater than 20 are hyphenated (e.g. “twenty-one”).
- Input is always going to be a non-null string in the format \d{2}:\d{2}(\s?[ap]m)?
- Both 12h and 24h input may be present. In case of 12h input disregard the am/pm part.
- Remember that in 24h midnight is denoted as 00:00.
- There may or may not be a space between the minutes and the am/pm part in 12h format.
Examples:
toHumanTime("05:28 pm"); // twenty-eight minutes past five toHumanTime("12:00"); // twelve o'clock toHumanTime("03:45am"); // quarter to four toHumanTime("07:15"); // quarter past seven toHumanTime("23:30"); // half past eleven toHumanTime("00:01"); // one minute past twelve toHumanTime("17:51"); // nine minutes to sixThe solution in Java code
Option 1:
Building a String Pyramid in Java
The challenge
You have to build a pyramid.
This pyramid should be built from characters from a given string.
You have to create the code for these four methods:
public static String watchPyramidFromTheSide(String characters) public static String watchPyramidFromAbove(String characters) public static int countVisibleCharactersOfThePyramid(String characters) public static int countAllCharactersOfThePyramid(String characters)The first method (“FromTheSide”) shows the pyramid as you would see from the side.
The second method (“FromAbove”) shows the pyramid as you would see from above.
The third method (“CountVisibleCharacters”) should return the count of all characters, that are visible from outside the pyramid.
The forth method (“CountAllCharacters”) should count all characters of the pyramid. Consider that the pyramid is completely solid and has no holes or rooms in it.Cartesian coordinates from degree angle in Java
The challenge
Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rounded to 10 places).
For example:
coordinates(90,1)=> (0.0, 1.0)coordinates(45, 1)=> (0.7071067812, 0.7071067812)The solution in Java code
Option 1:
import java.awt.geom.Point2D; class CoordinatesInspector { Point2D.Double coordinates(Double degrees, Double radius) { return new Point2D.Double( Math.round(radius * Math.cos(Math.toRadians(degrees)) * 10e9) / 10e9, Math.round(radius * Math.sin(Math.toRadians(degrees)) * 10e9) / 10e9); } }Option 2:
Sort array by sorting its smallest sub-array in Java
The challenge
Given an array of integers, arr, find out 2 indices m, n(0<=m<=arr.length-1, 0<=n<=arr.length-1, m<=n), so that as long as all elements in the subarray(from index m to n, indices m and n inclusive) are sorted properly, with this sorted subarray relacing original subarray, the whole array is sorted (no matter ascendingly or descendingly).
The subarray should include the least number of elements, means (n-m) must be of the smallest value, and n should also be the smallest one.
Excessively Abundant Numbers in Java
The challenge
An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself.
The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).
Derive function
abundantNumber(num)/abundant_number(num)which returnstrue/True/.true.ifnumis abundant,false/False/.false.if not.The solution in Java code
Option 1 (using
IntStream):Unique Substring From Joined Strings in Java
The challenge
Write a function that takes two strings, A and B, and returns the length of the longest possible substring that can be formed from the concatenation of either A + B or B + A containing only characters that do not appear in both A and B.
Example:
Given the strings “piquancy” and “refocusing”:
A = “piquancy”
B = “refocusing”
A + B = “piquancyrefocusing”
B + A = “refocusingpiquancy”Converting from Base 10 to 16 (Decimal to Hex) in Java
The challenge
Convert an
integerwhich is base 10, to ahexadecimalbase 16string.Java provides various built-in options such as
Integer.toString(a, 16), orString.format("0x%X", a), orInteger.toHexString(a)The solution in Java code
Option 1:
public class Hexadecimal{ public static String convertToHex(int a){ return "0x"+Integer.toHexString(a).toUpperCase(); } }Option 2:
public class Hexadecimal{ private static final String hexDigits = "0123456789ABCDEF"; public static String convertToHex(int a) { String hexadecimal = ""; while (a > 0) { int digit = a % 16; hexadecimal = hexDigits.charAt(digit) + hexadecimal; a = a / 16; } return "0x" + hexadecimal; } }Option 3:
How to Format Numbers by Prepending 0 to single-digit numbers in Javascript
If you have a single-digit number, and you need to format it to always have at-least two digits, then you can use the below function to solve your problem:
function toAtleastTwoPlaces(n){ return n > 9 ? "" + n: "0" + n; }When testing the above method, you could do the following:
toAtleastTwoPlaces(9); //Returns "09" toAtleastTwoPlaces(10); //Returns "10" toAtleastTwoPlaces(999); //Returns "999"This is especially useful where you need to format dates:
String polynomial converter in Java
The challenge
Your task is to programe:
String convertToString(int[] pol) {....}The method returns given by a parameter, (integer array) which represents a polynomial, the representation of the polynomial in String format. NOTE:array{a, b, c, d, e,...., z} 0 1 2 3 4 .... nThe numbers indicate the grade of the polynomial, where n is a positive integer always. Some examples:
array{0,1,-2,0,5} -> convertToString(array) -> "5x^4-2x^2+x" array{1,1,-2,0,0} -> convertToString(array) -> "-2x^2+x+1" array{} -> convertToString(array) -> "" array{0,0,7,0,0} -> convertToString(array) -> "7x^2" array{1,0,0,0,0} -> convertToString(array) -> "1" array{0,1,-1,0,5,0,0,1} -> convertToString(array) -> "x^7+5x^4-x^2+x"The solution in Java code
Option 1:
How to Remove all Exclamation Marks from a String in Java
The challenge
Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
The solution in Java code
Option 1:
class Solution { static String removeExclamationMarks(String s) { return s.replaceAll("!", ""); } }Option 2:
class Solution { static String removeExclamationMarks(String s) { return s.replace("!", ""); } }Test cases to validate our solution in Java
import org.junit.Test; import java.util.Random; import java.util.stream.*; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void testSimpleString1() { assertEquals("Hello World", Solution.removeExclamationMarks("Hello World!")); } @Test public void testSimpleString2() { assertEquals("Hello World", Solution.removeExclamationMarks("Hello World!!!")); } @Test public void testSimpleString3() { assertEquals("Hi Hello", Solution.removeExclamationMarks("Hi! Hello!")); } @Test public void testRandomString() { String rs = String.format("%s!%s %s!%s", randomString(), randomString(), randomString(), randomString()); assertEquals(solution(rs), Solution.removeExclamationMarks(rs)); } private String randomString() { Random random = new Random(); String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZbcdefghijklmnopqrstuvwxyz"; return IntStream.range(0, 10) .mapToObj(__ -> (char) abc.charAt(random.nextInt(abc.length()))) .map(String::valueOf) .collect(Collectors.joining("")); } private String solution(String s) { return s.replaceAll("!", ""); } }How to Convert a Number to a String in Java
The challenge
We need a function that can transform a number into a string.
What ways of achieving this do you know?
Examples:
Solution.numberToString(123); // returns "123"; Solution.numberToString(999); // returns "999";The solution in Java code
The easiest way to do this is to use the
String.valueOfmethod to take an integer and return a string:class Solution { public static String numberToString(int num) { return String.valueOf(num); } }This can also be done the other way around, using the
Integer.toStringmethod:How to Remove Spaces in a String in Java
The challenge
Simple, remove the spaces from the string, then return the resultant string.
The solution in Java code
class Solution { static String noSpace(final String x) { return x.replace(" ", ""); } }An alternative:
class Solution { static String noSpace(final String x) { return x.replaceAll("\\s+",""); } }Test cases to validate our Java solution
import org.junit.Test; import java.util.Random; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void testSomething() { assertEquals("8j8mBliB8gimjB8B8jlB", Solution.noSpace("8 j 8 mBliB8g imjB8B8 jl B")); assertEquals("88Bifk8hB8BB8BBBB888chl8BhBfd", Solution.noSpace("8 8 Bi fk8h B 8 BB8B B B B888 c hl8 BhB fd")); assertEquals("8aaaaaddddr", Solution.noSpace("8aaaaa dddd r ")); assertEquals("jfBmgklf8hg88lbe8", Solution.noSpace("jfBm gk lf8hg 88lbe8 ")); assertEquals("8jaam", Solution.noSpace("8j aam")); } private static final String chars = "abc defg hij klm no pq rstuvw xyz"; @Test public void randomTests() { Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 20; i++) { int length = random.nextInt(15) + 1; for (int j = 0; j < length; j++) { int index = random.nextInt(chars.length()); sb.append(chars.charAt(index)); } String input = sb.toString(); sb.setLength(0); assertEquals(input.replaceAll(" ", ""), Solution.noSpace(input)); } } }How many stairs will Suzuki climb in 20 years? in Java
The challenge
Suzuki is a monk who climbs a large staircase to the monastery as part of a ritual. Some days he climbs more stairs than others depending on the number of students he must train in the morning. He is curious how many stairs might be climbed over the next 20 years and has spent a year marking down his daily progress.
The sum of all the stairs logged in a year will be used for estimating the number he might climb in 20.
Determine if N is divisible by X and Y in Java
The challenge
Create a function that checks if a number
nis divisible by two numbersxANDy. All inputs are positive, non-zero digits.Examples
1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3 2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6 3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3 4) n = 12, x = 7, y = 5 => false because 12 is neither divisible by 7 nor 5The solution in Java code
Option 1:
How to Sum a Mixed Array in Java
The challenge
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.
Return your answer as a number.
The solution in Java code
Option 1 (using
stream):import java.util.List; public class MixedSum { public int sum(List<?> mixed) { return mixed.stream().mapToInt(o -> Integer.parseInt(o.toString())).sum(); } }Option 2 (the harder way):
import java.util.List; public class MixedSum { public int sum(List<?> mixed) { int sum = 0; for (Object element : mixed) { if (element instanceof Integer) { sum += (Integer) element; } else if (element instanceof String) { sum += Integer.parseInt( (String) element ); } } return sum; } }Option 3 (using
Objects):Calculate the Volume of a Cuboid in Java
A Cuboid is a geometric object that is more or less cubic in shape. It is a solid which has six rectangular faces at right angles to each other.
The formula to calculate a cuboid is pretty simple, just multiple the length by the width by the height to get the total volume. We want to calculate volume of cuboid.
Additionally, the volume of cuboid test case below validates the Java code solution.
Find the first non-consecutive number in Java
The challenge
Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array
[1,2,3,4,6,7,8]then1then2then3then4are all consecutive but6is not, so that’s the first non-consecutive number.If the whole array is consecutive then return
null.Alternating String Casing in Java
The challenge
altERnaTIng cAsE <=> ALTerNAtiNG CaSe
Define
String.prototype.toAlternatingCase(or a similar function/method such asto_alternating_case/toAlternatingCase/ToAlternatingCasein your selected language; see the initial solution for details) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example:StringUtils.toAlternativeString("hello world") == "HELLO WORLD" StringUtils.toAlternativeString("HELLO WORLD") == "hello world" StringUtils.toAlternativeString("hello WORLD") == "HELLO world" StringUtils.toAlternativeString("HeLLo WoRLD") == "hEllO wOrld" StringUtils.toAlternativeString("12345") == "12345" // Non-alphabetical characters are unaffected StringUtils.toAlternativeString("1a2b3c4d5e") == "1A2B3C4D5E" StringUtils.toAlternativeString("StringUtils.toAlternatingCase") == "sTRINGuTILS.TOaLTERNATINGcASE"As usual, your function/method should be pure, i.e. it should not mutate the original string.
Solving the Pythagorean Triple in Java
The challenge
Given an array of 3 integers
a, b and c, determine if they form a pythagorean triple.A pythagorean triple is formed when:
c2 = a2 + b2
where
cis the largest value ofa, b, c.For example:
a = 3, b = 4, c = 5forms a pythagorean triple, because 52 = 32 + 42Return Values
1ifa,bandcform a pythagorean triple- `` if
a,bandcdo not form a pythagorean triple - For Python: return
TrueorFalse
The solution in Java code
Option 1:
How to Correct the Mistakes of the Character Recognition Software in Java
The challenge
Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer.
When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes.
Your task is correct the errors in the digitised text. You only have to handle the following mistakes:
Sis misinterpreted as5Ois misinterpreted as ``Iis misinterpreted as1
The test cases contain numbers only by mistake.
Solving “Duck Duck Goose” in Java
The challenge
The objective of Duck, duck, goose is to walk in a circle, tapping on each player’s head until one is chosen.
Task: Given an array of Player objects (an array of associative arrays in PHP) and an index (1-based), return the
nameof the chosen Player(nameis a property ofPlayerobjects, e.gPlayer.name)Example:
duck_duck_goose([a, b, c, d], 1) should return a.name duck_duck_goose([a, b, c, d], 5) should return a.name duck_duck_goose([a, b, c, d], 4) should return d.nameThe solution in Java code
Option 1 (
returning the modulo):Calculate averages from an int array in Java
The challenge
Write function avg which calculates average of numbers in given list.
The solution in Java code
Option 1 (working through the problem):
public class Solution { public static double find_average(int[] array){ double sum = 0; for(int i=0; i<array.length; i++) { sum+=array[i]; } return sum/array.length; } }Option 2 (using
streams):import java.util.Arrays; public class Solution { public static double find_average(int[] array){ return Arrays.stream(array).average().orElse(0); } }Option 3 (using an
IntStream):How to Rotate a String in Java
Rotating a
Stringin Java is a common interview question, and albeit it quite a simple one, it tests many fundamental concepts. Did I mention that it can also be done fairly quickly too!Rotating a String in Java
public class Rotater { public static void main(String...args) { Rotater r = new Rotater(); System.out.println(r.rotateLeft("test", 1)); System.out.println(r.rotateRight("test", 1)); } private String rotateLeft(String value, int n) { return value.substring(n) + value.substring(0, n); } private String rotateRight(String value, int n) { return rotateLeft(value, value.length() - n); } }With the above code, we can rotate a string both left and right, but we don’t take into account any edge cases, exception handling, input validation or out of bounds problems.
Calculate the Sum without highest and lowest number in Java
The challenge
Sum all the numbers of the array except the highest and the lowest element (the value, not the index!).
(The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!)Example:
{ 6, 2, 1, 8, 10 } => 16 { 1, 1, 11, 2, 3 } => 6If array is empty, null or None, or if only 1 Element exists, return 0.
How to Convert a String to an Array in Java
Java makes it easy to convert a string to an array by providing the built-in
.split()method on theStringobject.The challenge
Write a function to split a string and convert it into an array of words. For example:
"Robin Singh" ==> ["Robin", "Singh"] "I love arrays they are my favorite" ==> ["I", "love", "arrays", "they", "are", "my", "favorite"]The solution in Java code
This is a really simple one, you just
splitthestringwith thespacecharacter:How to Loop and Combine Three Strings in Java
The challenge
Create a function that will return a string that combines all of the letters of the three inputed strings in groups. Taking the first letter of all of the inputs and grouping them next to each other. Do this for every letter, see example below!
E.g. Input: “aa”, “bb” , “cc” => Output: “abcabc”
Note: You can expect all of the inputs to be the same length.
The solution in Java code
Option 1:
How to Localize The Barycenter of a Triangle in Java
The challenge
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides. The three medians of a triangle intersect at the same point, called the barycenter or the centroid. Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or centroid.
The function
bar_triang() or barTriang or bar-triang, receives the coordinates of the three verticesA, B and Cas three different arguments and outputs the coordinates of the barycenterOin an array[xO, yO]How to Calculate a Valid Square in Java
The challenge
Given the coordinates of four points in 2D space
p1,p2,p3andp4, returntrueif the four points construct a square.The coordinate of a point
p<sub>i</sub>is represented as[x<sub>i</sub>, y<sub>i</sub>]. The input is not given in any order.A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Example 1:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: true
Example 2:
How to Calculate Age Range Compatibility as an Equation in Java
The challenge
Everybody knows the classic “half your age plus seven” dating rule that a lot of people follow (including myself). It’s the ‘recommended’ age range in which to date someone.
minimum age <= your age <= maximum ageGiven an integer (1 <= n <= 100) representing a person’s age, return their minimum and maximum age range.
This equation doesn’t work when the age <= 14, so use this equation instead:
How to Find the Longest Mountain in Array in Java
The challenge
Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3- There exists some
0 < i < B.length - 1such thatB[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array
Aof integers, return the length of the longest mountain.How to tell what the CHMOD value of a file/directory is
chmodalters the permissions for a file or directory, you could allow full read/write access to a file or directory by running the following command:chmod 777 myfile.extYou could do the same on a directory recursively:
chmod -R 777 mydirectoryBut if we look at the directory listing of this path now, we can’t tell what integer value this affected:
$ ls -lash 0 -rwxrwxrwx 1 ao staff 0B 18 Nov 13:29 myfile.extHow to get the CHMOD value
If we want to get the actual integer value back, we could use the
statcommand and tell it what we want from it:How to Solve the “Decode a String” Challenge in Java
The challenge
Given an encoded string, return its decoded string.
The encoding rule is:
k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like
3aor2[4].How to cleanup a /var/log/journal in Linux
You may find your
/var/log/journaldirectory taking up a lot of disk-space.How do you go about removing, or deleting all these files under
var log journalwithout the system complaining and falling over?How to tell how much space is being taken?
You can ask the
journalctlcommand directly, using the--disk-usageargument:journalctl --disk-usageIt will report something like this:
Journals take up 3.9G on disk.Fix: Option 1 (not ideal):
Go and adjust its config under
/etc/systemd/journald.conf, making sure to pay attention to theSystemMaxUsekey; set this to something reasonable, like50Mperhaps.How to Find the Maximum Difference Between Node and Ancestor in Java
The challenge
Given the
rootof a binary tree, find the maximum valueVfor which there exist different nodesAandBwhereV = |A.val - B.val|andAis an ancestor ofB.A node
Ais an ancestor ofBif either: any child ofAis equal toB, or any child ofAis an ancestor ofB.Example 1:
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Example 2:
How to Find the Integral using Java
The challenge
Create a function that finds the integral of the expression passed.
In order to find the integral all you need to do is add one to the
exponent(the second argument), and divide thecoefficient(the first argument) by that new number.For example for
3x^2, the integral would be1x^3: we added 1 to the exponent, and divided the coefficient by that new number).Notes:
- The output should be a string.
- The coefficient and exponent is always a positive integer.
Examples
3, 2 --> "1x^3" 12, 5 --> "2x^6" 20, 1 --> "10x^2" 40, 3 --> "10x^4" 90, 2 --> "30x^3"The solution in Java code
public class Solution { public static String integrate(int coefficient, int exponent) { int first = ++exponent; coefficient /= first; return coefficient+"x^"+first; } }A single line solution:
How to Build Strings from a Size in Java
The challenge
Write a function
stringythat takes asizeand returns astringof alternating'1s'and'0s'.The string should start with a
1.A string with
size6 should return :'101010'.With
size4 should return :'1010'.With
size12 should return :'101010101010'.The size will always be positive and will only use whole numbers.
The solution in Java code
public class Solution { public static String stringy(int size) { int last = 1; StringBuilder sb = new StringBuilder(); for (int i=0; i<size; i++) { sb.append(last); last = last==0 ? 1 : 0; } return sb.toString(); } }We could make this a little simpler by doing the following:
Best Time to Buy and Sell Stock in Java
The challenge
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
How to Solve the “To square(root) or not to square(root)” Challenge in Java
The challenge
Write a method, that will get an integer array as parameter and will process every number from this array.
Return a new array with processing every number of the input-array like this:If the number has an integer square root, take this, otherwise square the number. [4,3,9,7,2,1] -> [2,9,3,49,4,1]The input array will always contain only positive numbers and will never be empty or null.
Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.util.Arrays; public class SolutionTest { @Test public void basicTests() { int[] input = new int[] { 4, 3, 9, 7, 2, 1 }; int[] expected = new int[] { 2, 9, 3, 49, 4, 1 }; assertEquals(Arrays.toString(expected), Arrays.toString(Squarer.squareOrSquareRoot(input))); input = new int[] { 100, 101, 5, 5, 1, 1 }; expected = new int[] { 10, 10201, 25, 25, 1, 1 }; assertEquals(Arrays.toString(expected), Arrays.toString(Squarer.squareOrSquareRoot(input))); input = new int[] { 1, 2, 3, 4, 5, 6 }; expected = new int[] { 1, 4, 9, 2, 25, 36 }; assertEquals(Arrays.toString(expected), Arrays.toString(Squarer.squareOrSquareRoot(input))); } }The solution in Java
Option 1 (using a
loop):Solving the Rule of Divisibility by 13 in Java
The challenge
"A divisibility rule is a shorthand way of determining whether a given integer is divisible by a fixed divisor without performing the division, usually by examining its digits."
wikipedia.com
When you divide the successive powers of
10by13you get the following remainders of the integer divisions:1, 10, 9, 12, 3, 4because:
(For “mod” you can see: https://en.wikipedia.org/wiki/Modulo_operation)
Then the whole pattern repeats. Hence the following method:
How to Calculate Buddy Strings in Java
The challenge
Given two strings
AandBof lowercase letters, returntrueif you can swap two letters inAso the result is equal toB, otherwise, returnfalse.Swapping letters is defined as taking two indices
iandj(0-indexed) such thati != jand swapping the characters atA[i]andA[j]. For example, swapping at indices `` and2in"abcd"results in"cbad".Example 1:
How to Flip a Binary Matrix in Java
The challenge
Given a binary matrix
A, we want to flip the image horizontally, then invert it, and return the resulting image.To flip an image horizontally means that each row of the image is reversed. For example, flipping
[1, 1, 0]horizontally results in[0, 1, 1].To invert an image means that each
is replaced by `1`, and each `1` is replaced by . For example, inverting[0, 1, 1]results in[1, 0, 0].How to Tilt a Binary Tree in Java
The challenge
Given the
rootof a binary tree, return the sum of every tree node’s tilt.The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as ``. The rule is similar if there the node does not have a right child.
How to solve the House Robber Challenge in Java
The challenge
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
How to Solve the Bag of Tokens Challenge in Java
The challenge
You have an initial power of
P, an initial score of ``, and a bag oftokenswheretokens[i]is the value of thei<sup>th</sup>token (0-indexed).Your goal is to maximize your total score by potentially playing each token in one of two ways:
- If your current power is at least
tokens[i], you may play thei<sup>th</sup>token face up, losingtokens[i]power and gaining1score. - If your current score is at least
1, you may play thei<sup>th</sup>token face down, gainingtokens[i]power and losing1score.
Each token may be played at most once and in any order. You do not have to play all the tokens.
How to Find the Smallest Divisor Given a Threshold in Java
The challenge
Given an array of integers
numsand an integerthreshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal tothreshold.Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
How to Sort and Star a String Array in Java
The challenge
You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value.
The returned value must be a string, and have
"***"between each of its letters.You should not remove or add elements from/to the array.
The solution in Java code
At first we could approach the problem by using the built-in
Arrays.sort()method and then looping through the first string, placing asterisks inbetween each letter:How to Count Consecutive Characters in Java
The challenge
Given a string
s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.Return the power of the string.
Example 1:
Input: s = "meetme" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only
Example 2:
Input: s = "abbcccddddeeeeedcba" Output: 5 Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Example 3:
How to Abbreviate a Two Word Name in Java
The challenge
Write a function to convert a name into initials. This challenge strictly takes two words with one space in between them.
The output should be two capital letters with a dot separating them.
It should look like this:
Sam Harris=>S.HPatrick Feeney=>P.FThe solution in Java
This is a really easy one, basically what we will do is the following:
- Convert our
nametoUpperCaseso that we can just pull out the characters we want. - Convert the
nameString into 2 separate values, stored in anamesarray. - Return the first character of each, using
charAt(0)with a dot inbetween.
public class AbbreviateTwoWords { public static String abbrevName(String name) { name = name.toUpperCase(); String[] names = name.split(" "); return names[0].charAt(0)+"."+names[1].charAt(0); } }Test cases to validate our solutionn
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testFixed() { assertEquals("S.H", AbbreviateTwoWords.abbrevName("Sam Harris")); assertEquals("P.F", AbbreviateTwoWords.abbrevName("Patrick Feenan")); assertEquals("E.C", AbbreviateTwoWords.abbrevName("Evan Cole")); assertEquals("P.F", AbbreviateTwoWords.abbrevName("P Favuzzi")); assertEquals("D.M", AbbreviateTwoWords.abbrevName("David Mendieta")); assertEquals("Z.K", AbbreviateTwoWords.abbrevName("Zenon Kapusta")); assertEquals("G.C", AbbreviateTwoWords.abbrevName("george clooney")); assertEquals("M.M", AbbreviateTwoWords.abbrevName("marky mark")); assertEquals("E.D", AbbreviateTwoWords.abbrevName("eliza doolittle")); assertEquals("R.W", AbbreviateTwoWords.abbrevName("reese witherspoon")); } @Test public void testRandom() { for(int i = 0; i < 200; i++){ String testString = makeString(); assertEquals(randomTest(testString), AbbreviateTwoWords.abbrevName(testString)); } } private String makeString() { return makeWord(1, 20) + " " + makeWord(1, 20); } private String makeWord(int min, int max) { String word = ""; String[] possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""); int length = (int) (Math.random() * max) + min; for(int i=0; i < length; i++) { int index = (int) (Math.random() * possible.length); word += possible[index]; } return word; } private String randomTest(String name){ String[] nameSplit = name.toUpperCase().split(" "); return nameSplit[0].substring(0, 1) + '.' + nameSplit[1].substring(0, 1); } }How to Sort a Linked List using Insertion Sort in Java
The challenge
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partially sorted list (black) initially contains only the first element in the list.
With each iteration, one element (red) is removed from the input data and inserted in-place into the sorted listAlgorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
Example 1:
How to Remove First and Last Character in a String in Java
The challenge
The goal is to create a function that removes the first and last characters of a string. You don’t have to worry with strings with less than two characters.
The solution in Java code
public class RemoveChars { public static String remove(String str) { return str.substring(1, str.length()-1); } }Test cases to validate our Java solution
import org.junit.Test; import static org.junit.Assert.assertEquals; public class RemoveCharsTest { @Test public void testRemoval() { assertEquals("loquen", RemoveChars.remove("eloquent")); assertEquals("ountr", RemoveChars.remove("country")); assertEquals("erso", RemoveChars.remove("person")); assertEquals("lac", RemoveChars.remove("place")); } }How to Distribute Halloween Candies by Rating Value in Java
The challenge
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
How to Distribute Halloween Candies in Java
The challenge
You have
ncandies, thei<sup>th</sup>candy is of typecandies[i].You want to distribute the candies equally between a sister and a brother so that each of them gets
n / 2candies (nis even). The sister loves to collect different types of candies, so you want to give her the maximum number of different types of candies.Return the maximum number of different types of candies you can give to the sister.
How to Solve the Maximize Distance to Closest Person Challenge in Java
The challenge
You are given an array representing a row of
seatswhereseats[i] = 1represents a person sitting in thei<sup>th</sup>seat, andseats[i] = 0represents that thei<sup>th</sup>seat is empty (0-indexed).There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
How to Get Character from ASCII Value in Java
The challenge
Write a function which takes a number and returns the corresponding ASCII char for that value.
Example:
Ascii.getChar(65) // => 'A'For ASCII table, you can refer to http://www.asciitable.com/
The solution in Java
public class Ascii { public static char getChar(int c) { return (char) c; } }Test cases to validate our solution
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testChar() { assertEquals('7', Ascii.getChar(55)); assertEquals('8', Ascii.getChar(56)); assertEquals('9', Ascii.getChar(57)); assertEquals(':', Ascii.getChar(58)); assertEquals(';', Ascii.getChar(59)); assertEquals('<', Ascii.getChar(60)); assertEquals('=', Ascii.getChar(61)); assertEquals('>', Ascii.getChar(62)); assertEquals('?', Ascii.getChar(63)); assertEquals('@', Ascii.getChar(64)); assertEquals('A', Ascii.getChar(65)); assertEquals("getChar should return a `char`", 0, Character.compare('!', Ascii.getChar(33))); } }Finding a Needle in a Haystack in Java
The challenge
Can you find the needle in the haystack?
Write a function
findNeedle()that takes anarrayfull of junk but containing one"needle"After your function finds the needle it should return a message (as a string) that says:
"found the needle at position "plus theindexit found the needle, so:findNeedle(new Object[] {"hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"})should return
"found the needle at position 5"How to Solve the Champagne Tower in Java
The challenge
We stack glasses in a pyramid, where the first row has
1glass, the second row has2glasses, and so on until the 100th row. Each glass holds one cup (250ml) of champagne.Then, some champagne is poured in the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
How to Solve the 132 Pattern in Java
The challenge
Given an array of
nintegersnums, a 132 pattern is a subsequence of three integersnums[i],nums[j]andnums[k]such thati < j < kandnums[i] < nums[k] < nums[j].Return
trueif there is a 132 pattern innums, otherwise, returnfalse.**Follow up: **The
O(n^2)is trivial, could you come up with theO(n logn)or theO(n)solution?Example 1:
Input: nums = [1,2,3,4] Output: false Explanation: There is no 132 pattern in the sequence.
Example 2:
How to Replace all Vowels in a String in Java
The challenge
Replace all vowel to exclamation mark in the sentence.
aeiouAEIOUis vowel.Examples
replace("Hi!") === "H!!" replace("!Hi! Hi!") === "!H!! H!!" replace("aeiou") === "!!!!!" replace("ABCDE") === "!BCD!"The solution in Java code
We could use a
StringBuilderand aswitchcaseas a first attempt:public class Solution { public static String replace(final String s) { StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { switch(Character.toLowerCase(s.charAt(i))) { case 'a': case 'e': case 'i': case 'o': case 'u': sb.append("!"); break; default: sb.append(s.charAt(i)); break; } } return sb.toString(); } }A more efficient method using
replaceAll:How to Get the N-th Power in Java
The challenge
You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don’t forget that the first element has the index 0.
Let’s look at a few examples:
- array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
- array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.
The solution in Java code
public class Solution { public static int nthPower(int[] array, int n) { return n >= array.length ? -1 : (int) Math.pow(array[n], n); } }An alternative mapping:
How to Count the Minimum Depth of a Binary Tree in Java
The challenge
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6] Output: 5
Constraints:
- The number of nodes in the tree is in the range
[0, 10<sup>5</sup>]. -1000 <= Node.val <= 1000
The definition for a binary tree node
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }The solution in Java code
First we need to make sure that we catch our 2 edge cases:
How to Solve the House Robber II Challenge in Java
The challenge
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
How to Clone a Graph in Java
The challenge
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph. Effectively a graph copy.
Each node in the graph contains a val (
int) and a list (List[Node]) of its neighbors.class Node { public int val; public List<Node> neighbors; }Test case format:
For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with
val = 1, the second node withval = 2, and so on. The graph is represented in the test case using an adjacency list.How to Return Random Values in Java
The challenge
Ghost objects are instantiated without any arguments.
Ghost objects are given a random color attribute of white" or “yellow” or “purple” or “red” when instantiated
Ghost ghost = new Ghost(); ghost.getColor(); //=> "white" or "yellow" or "purple" or "red"All this challenge is really asking us to do is to create a class method that can return random colour strings when called.
The solution in Java
We make use of the
java.util.Randomclass to generate a couple of random values for us to use within aswitchstatement.How to Compare Version Numbers in Java
The challenge
Compare two version numbers version1 and version2.
If<em>version1</em> > <em>version2</em>return1;if<em>version1</em> < <em>version2</em>return-1;otherwise return ``.You may assume that the version strings are non-empty and contain only digits and the
.character.The
.character does not represent a decimal point and is used to separate number sequences.For instance,
2.5is not “two and a half” or “half way to version three”, it is the fifth second-level revision of the second first-level revision.How to Return the First N Elements in Java
The challenge
Create a method take that accepts a list/array and a number n, and returns a list/array array of the first n elements from the list/array.
If you need help, here’s a reference:
https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOfRange(int[],%20int,%20int)
Test cases
import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; import java.util.*; public class SolutionTest { @Test public void basicTests() { assertArrayEquals("should return the first 3 items", new int[]{0, 1, 2}, ZywOo.take(new int[]{0, 1, 2, 3, 5, 8, 13}, 3)); assertArrayEquals("should return 0 items", new int[0], ZywOo.take(new int[]{0, 1, 2, 3, 5, 8, 13}, 0)); assertArrayEquals("empty array should return empty array", new int[0], ZywOo.take(new int[0], 3)); } @Test public void randomTests() { for (int i = 0; i < 100; i++) { int n = (int)Math.floor(100 * Math.random()); int[] randomArray = generateRandomArray(); assertArrayEquals("Testing with array " + Arrays.toString(randomArray) + " and n = " + n, solution(randomArray, n), ZywOo.take(randomArray, n)); } } private int[] solution(int[] arr, int n) { return arr.length > 0 && arr.length > n ? Arrays.copyOfRange(arr, 0, n) : arr; } private int[] generateRandomArray() { int length = (int)Math.floor(100 * Math.random()); int min = (int)Math.floor(-100 * Math.random()); int max = (int)Math.floor( 100 * Math.random()); return new Random().ints(length, min, max).toArray(); } }The solution in Java
Option 1:
How to Search a 2d Matrix/Array in Java
The challenge
Write an efficient algorithm that searches for a value in an
m x nmatrix. This matrix has the following properties:- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 3 Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 13 Output: false
Example 3:
Calculate the Surface Area and Volume of a Box with Java
The challenge
Write a function that returns the total surface area and volume of a box as an array:
[area, volume]The solution in Java
We know that the formula to calculate the area of a box is as follows:
2(h × W) + 2(h × L) + 2(W × L)We also know that the formula to calculate the volume of a box is as follows:
W x h x HFind Numbers which are Divisible by given Number in Java
The challenge
Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of
numbersand the second is thedivisor.Example
divisibleBy([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]The solution in Java
Option 1 (using
streams):import java.util.stream.*; import java.util.Arrays; public class EvenNumbers { public static int[] divisibleBy(int[] numbers, int divider) { return Arrays.stream(numbers) .filter(i -> (i % divider) == 0) .toArray(); } }Option 2 (writing the code ourselves):
How to Split a Subdirectory to a New Git Repository and Keep the History
There comes a time when you need to split out a subdirectory into it’s own git repo.
This is a very simple task if you don’t care about persisting the git history for any changes that were made in that subdirectory.
However, if you would like to keep all the history of the subdirectory only, and not of the overall entire repository itself, then you can perform the following bunch of steps:
Get the Maximum XOR of Two Numbers in an Array in Java
The challenge
Given a non-empty array of numbers, a, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28.
The solution in Java
We can very quickly resolve this challenge by performing a double loop and comparing our resultant:
How to Get the Opposite of a Number in Java
The challenge
Given a number, find its opposite.
Examples:
1: -1 14: -14 -34: 34The solution in Java
We return the number itself multiplied by a negative 1.
public class Solution { public static int opposite(int number) { return number *= -1; } }This can be simplified further as:
public class Solution { public static int opposite(int number) { return -number; } }There is also a built in method to help with this if you prefer, called
Math.negateExact():How to Find the Area or Perimeter of a 4-sided Polygon using Java
The challenge
You are given the
lengthandwidthof a 4-sided polygon. The polygon can either be a rectangle or a square.
If it is a square, return its area. If it is a rectangle, return its perimeter.area_or_perimeter(6, 10) --> 32 area_or_perimeter(4, 4) --> 16Note: for the purposes of this challenge you will assume that it is a square if its
lengthandwidthare equal, otherwise, it is a rectangle.How to Parse Int from Char in Java
The challenge
We take in a
Stringwhere the first place contains a number, write a function that takes in thisStringand returns anintcontaining it.For correct answer program should return int from 0 to 9.
Assume test input string always valid and may look like “1 year old” or “5 years old”, etc.. The first char is number only.
The solution in Java
We take in a
String, and get the first character, which is done by usingcharAt(0). As this is achartype, we can append a-'0'to it and cast it back to an int using(ing):How to Search a Binary Tree in Java
The challenge
Given a sorted (in ascending order) integer array
numsofnelements and atargetvalue, write a function to searchtargetinnums. Iftargetexists, then return its index, otherwise return-1.Example 1:
Input:
nums= [-1,0,3,5,9,12],target= 9 Output: 4 Explanation: 9 exists innumsand its index is 4Example 2:
Input:
nums= [-1,0,3,5,9,12],target= 2 Output: -1 Explanation: 2 does not exist innumsso return -1Note:
How to Rotate a Singly Linked List in Java
The challenge
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4 Output:
2->0->1->NULLExplanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right:0->1->2->NULLrotate 4 steps to the right:2->0->1->NULL ``` ## The solution in Java code The definition for our singly-linked lists ``` public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } ``` Our solution in Java code: ``` class Solution { public ListNode rotateRight(ListNode head, int k) { // catch edge cases and return the head otherwise if (head == null || head.next == null) return head; // set the initial length to 1 int length = 1; // set the tail to the head ListNode tail = head; // while a next item exists while (tail.next != null) { // set the tail to the next item tail = tail.next; // increment the length length ++; } // set the amount of places to a remainer k %= length; // if none, then return the head if (k == 0) return head; // set our new head and tail ListNode newHead = head; ListNode newTail = head; // loop while length is greater than k while (length > k) { // set tail to head newTail = newHead; // set head to next head newHead = newHead.next; // decrement the length length --; } // set the next item on tail to null newTail.next = null; // set the tail's next item to head tail.next = head; // return the new head return newHead; } } ```How to Insert into a Binary Search Tree using Java
The challenge
You are given the
rootnode of a binary search tree (BST) and avalueto insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Find the Complement of Base 10 Integer in Java
The challenge
Every non-negative integer
Nhas a binary representation. For example,5can be represented as"101"in binary,11as"1011"in binary, and so on. Note that except forN = 0, there are no leading zeroes in any binary representation.The complement of a binary representation is the number in binary you get when changing every
1to a and to a1. For example, the complement of"101"in binary is"010"in binary.Solve the Number of Recent Calls Challenge in Java
The challenge
You have a
RecentCounterclass which counts the number of recent requests within a certain time frame.Implement the
RecentCounterclass:RecentCounter()Initializes the counter with zero recent requests.int ping(int t)Adds a new request at timet, wheretrepresents some time in milliseconds, and returns the number of requests that has happened in the past3000milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range[t - 3000, t].
It is guaranteed that every call to
pinguses a strictly larger value oftthan the previous call.How to Calculate the Summation of a Number in Java
The challenge
Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.
For example:
summation(2) -> 3 1 + 2 summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8The solution in Java
public class Solution { public static int summation(int n) { int runningTotal = 0; for (int i=1; i<=n; i++) runningTotal += i; return runningTotal; } }A simpler alternative is to do the following:
How to Calculate all Unique Combinations of a Target using Backtracking in Java
The challenge
Given an array of distinct integers
candidatesand a target integertarget, return a list of all unique combinations ofcandidateswhere the chosen numbers sum totarget. You may return the combinations in any order.The same number may be chosen from
candidatesan unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.Example 1:
Who is going to pay for the wall? in Python
The challenge
Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go. Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build the wall. Unfortunately for Don Drumphet, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names. As he collects signatures, he insists that his neighbors keep truncating their names until two letters remain, and he can finally read them.
Calculate the Total Amount of Points using Java
The challenge
Our football team finished the championship. The result of each match look like “x:y”. Results of all matches are recorded in the collection.
For example:
["3:1", "2:2", "0:1", ...]Write a function that takes such collection and counts the points of our team in the championship. Rules for counting points for each match:
- if x>y – 3 points
- if x<y – 0 point
- if x=y – 1 point
Notes:
Calculate the biggest of 3 numbers using Java
The challenge
Task
- Given three integers
a,b,c, return the largest number obtained after inserting the following operators and brackets:+,*,() - In other words , try every combination of a,b,c with [*+()] , and return the Maximum Obtained
Consider an Example :
With the numbers are 1, 2 and 3 , here are some ways of placing signs and brackets:
1 * (2 + 3) = 51 * 2 * 3 = 61 + 2 * 3 = 7(1 + 2) * 3 = 9
So the maximum value that you can obtain is 9.
Find the missing element between two arrays in Python
The challenge
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element.
Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution.
find_missing([1, 2, 2, 3], [1, 2, 3]) => 2find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8The first array will always have at least one element.
How to Count an Array of Boolean Values in Java
The challenge
Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
For example,
[true, true, true, false, true, true, true, true , true, false, true, false, true, false, false, true , true, true, true, true , false, false, true, true]The correct answer would be 17.
Hint: Don’t forget to check for bad values like
null/undefinedHow to Solve the Car Pooling Challenge in Java
The challenge
You are driving a vehicle that has
capacityempty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)Given a list of
trips,trip[i] = [num_passengers, start_location, end_location]contains information about thei-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle’s initial location.How to Repeat a String in Java
The challenge
Write a function called
repeat_strwhich repeats the given stringsrcexactlycounttimes.repeatStr(6, "I") // "IIIIII" repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"The solution in Java
Java comes with a
built-inon theStringclass. Calledrepeat, which allows you to very easily repeat that stringnnumber of times."Hello".repeat(2); // "HelloHello"Using String::repeat()
Therefore, we could solve our above problem as follows:
class Solution { static String repeatStr(int repeat, String string) { return string.repeat(repeat); } }Obviously, we probably want to validate our input before we just do it, so maybe wrap it in a ternary:
How to Find the Smallest Integer in the Array in Java
The challenge
Given an array of integers your solution should find the smallest integer.
For example:
- Given
[34, 15, 88, 2]your solution will return2 - Given
[34, -345, -1, 100]your solution will return-345
You can assume, for the purpose of this challenge, that the supplied array will not be empty.
The solution in Java
Option 1 (using
Arrays.sort):import java.util.Arrays; public class SmallestIntegerFinder { public static int findSmallestInt(int[] args) { Arrays.sort(args); return args[0]; } }Option 2 (using
streams):How to Count Odd Numbers Below N using Java
The challenge
Given a number n, return the number of positive odd numbers below n, EASY!
oddCount(7) //=> 3, i.e [1, 3, 5] oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13]Expect large Inputs!
Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void fixedTests() { assertEquals(7, OddNumbers.oddCount(15)); assertEquals(7511, OddNumbers.oddCount(15023)); } }The solution in Java
At first we would approach this in a programming type of way:
How to get the Length of the Last Word in a String using Java
The challenge
Given a string s consists of upper/lower-case alphabets and empty space characters
' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
Example:
Input: "Hello World" Output: 5
The solution in Java
class Solution { public int lengthOfLastWord(String s) { // catch edge case of blank input if (s.length()<=0) return 0; // split into words String[] words = s.split("\\s+"); // if one or less words, then return the length of the trimmed string if (words.length<=1) return s.trim().length(); // get the alst word String lastWord = words[words.length-1]; // return the last word's length return lastWord.length(); } }How to Convert a Number to Reversed Array of Digits in Java
The challenge
Given a random non-negative number, you have to return the digits of this number within an array in reverse order.
Test cases
import org.junit.Test; import static org.junit.Assert.assertArrayEquals; public class DigitizeExampleTests { @Test public void tests() { assertArrayEquals(new int[] {1, 3, 2, 5, 3}, ConvertAndReverse.digitize(35231)); } }Solution in Java
Option 1 (using
StreamsandStringBuilder):import java.util.*; public class ConvertAndReverse { public static int[] digitize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)).reverse(); return Arrays.stream(sb.toString().split("")) .mapToInt(Integer::parseInt) .toArray(); } }Option 2 (using
StringBuilderandStreams):How to Solve Unique Paths III in Java
The challenge
On a 2-dimensional
grid, there are 4 types of squares:1represents the starting square. There is exactly one starting square.2represents the ending square. There is exactly one ending square.- `` represents empty squares we can walk over.
-1represents obstacles that we cannot walk over.
Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
How to Find the Mean/Average of a List of Numbers in Java
The challenge
Find the mean (average) of a list of numbers in an array.
To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.
For an example list of
1, 3, 5, 71. Add all of the numbers
1+3+5+7 = 162. Divide by the number of values in the list. In this example there are 4 numbers in the list.
How to Calculate BMI in Java
The challenge
BMIstands for Body Mass Index and is a value derived from the mass and height of a person. The BMI is defined asthe body mass divided by the square of the body height, and is universally expressed in units of kg/m², resulting from mass in kilograms and height in metres. WikipediaWrite function BMI that calculates body mass index (bmi = weight / height ^ 2).
How to Solve the Robot Bounded In Circle Challenge in Java
The challenge
On an infinite plane, a robot initially stands at
(0, 0)and faces north. The robot can receive one of three instructions:"G": go straight 1 unit;"L": turn 90 degrees to the left;"R": turn 90 degress to the right.
The robot performs the
instructionsgiven in order, and repeats them forever.Return
trueif and only if there exists a circle in the plane such that the robot never leaves the circle.How to Convert a String to a Number in Java
The challenge
We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don’t worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.
Examples
stringToNumber("1234") == 1234 stringToNumber("605" ) == 605 stringToNumber("1405") == 1405 stringToNumber("-7" ) == -7Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; public class StringToNumberTest { @Test public void test1(){ assertEquals("stringToNumber(1234)", 1234 , StringToNumber.stringToNumber("1234")); } @Test public void test2(){ assertEquals("stringToNumber(605)", 605 , StringToNumber.stringToNumber("605")); } @Test public void test3(){ assertEquals("stringToNumber(1405)", 1405 , StringToNumber.stringToNumber("1405")); } @Test public void test4(){ assertEquals("stringToNumber(-7)", -7 , StringToNumber.stringToNumber("-7")); } @Test public void test5(){ for(int i = 0; i < 100; ++i) { int t = (int)Math.round(Math.random() * 500000); assertEquals("stringToNumber(" + t + ")", t , StringToNumber.stringToNumber(Integer.toString(t))); } } }The solution in Java
Option 1 (using
parseInt):How to Convert an Integer to Binary using Java
The challenge
Given a non-negative integer
n, write a functiontoBinary/ToBinarywhich returns that number in a binary format.to_binary(1) /* should return 1 */ to_binary(5) /* should return 101 */ to_binary(11) /* should return 1011 */Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class ConvertTest { @Test public void testToBinary() { assertEquals(1, BinaryConvert.toBinary(1)); assertEquals(10, BinaryConvert.toBinary(2)); assertEquals(11, BinaryConvert.toBinary(3)); assertEquals(101, BinaryConvert.toBinary(5)); } }The solution in Java
public class BinaryConvert { public static int toBinary(int n) { // Use the `toBinaryString` method of the Integer class // convert it back to an `int` using the `parseInt` method of the Integer class // return the result return Integer.parseInt(Integer.toBinaryString(n)); } }Alternative 1:
How to create a Logical Operator in Java
Exclusive “or” (
xor) Logical OperatorIn some scripting languages like PHP, there exists a logical operator (e.g.
&&,||,and,or, etc.) called the “Exclusive Or”. The exclusive or evaluates two booleans. It then returns true if exactly one of the two expressions are true, false otherwise. For example:// since both are false false xor false == false // exactly one of the two expressions are true true xor false == true // exactly one of the two expressions are true false xor true == true // Both are true. "xor" only returns true if EXACTLY one of the two expressions evaluate to true. true xor true == falseHow to create a Logical Operator in Java
As Java does not ship out the box with this functionality, we can easily create it ourselves.
How to merge sorted integer arrays (without duplicates) in Java
The challenge
Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.
Test cases
import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.Function; import java.util.stream.IntStream; public class SolutionTest { @Test public void fixedTest() { assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 6 }, Merger.mergeArrays(new int[] { 1, 3, 5 }, new int[] { 2, 4, 6 })); assertArrayEquals(new int[] { 2, 4, 6, 8 }, Merger.mergeArrays(new int[] { 2, 4, 8 }, new int[] { 2, 4, 6 })); assertArrayEquals(new int[] { 1, 2, 3 }, Merger.mergeArrays(new int[] { 1, 2, 3 }, new int[] {})); assertArrayEquals(new int[0], Merger.mergeArrays(new int[0], new int[0])); assertArrayEquals(IntStream.rangeClosed(1, 15).toArray(), Merger.mergeArrays(IntStream.rangeClosed(1, 10).toArray(), IntStream.rangeClosed(5, 15).toArray())); assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15 }, Merger.mergeArrays(IntStream.rangeClosed(1, 5).toArray(), IntStream.rangeClosed(10, 15).toArray())); assertArrayEquals(IntStream.rangeClosed(-5, 20).toArray(), Merger.mergeArrays(IntStream.rangeClosed(-5, 10).toArray(), IntStream.rangeClosed(-2, 20).toArray())); } private static final Random rnd = new Random(); @Test public void randomTest() { for (int i = 0; i < 100; ++i) { int[] source = IntStream.generate(() -> { return rnd.nextInt(200) - 100; }).limit(200).distinct().sorted().toArray(); List<Integer> one = new ArrayList<>(); List<Integer> two = new ArrayList<>(); for (int num : source) { (rnd.nextBoolean() ? one : two).add(num); if (rnd.nextInt(10) < 2) (rnd.nextBoolean() ? one : two).add(num); } Function<List<Integer>, int[]> asPrimitive = array -> array.stream().mapToInt(n -> n.intValue()).toArray(); assertArrayEquals(source, Merger.mergeArrays(asPrimitive.apply(one), asPrimitive.apply(two))); } } }The solution in Java
Option 1 (using
streams):Find the Force of Gravity Between Two Objects with Java
The challenge
Your job is to find the gravitational force between two spherical objects (obj1 , obj2).
Two arrays are give :
arr_val(value array), consists of 3 elements- 1st element : mass of obj 1
- 2nd element : mass of obj 2
- 3rd element : distance between their centers
arr_unit(unit array), consists of 3 elements- 1st element : unit for mass of obj 1
- 2nd element : unit for mass of obj 2
- 3rd element : unit for distance between their centers
Mass units are :
- kilogram (kg)
- gram (g)
- milligram (mg)
- microgram (μg)
- pound (lb)
Distance units are :
- meter (m)
- centimeter (cm)
- millimeter (mm)
- micrometer (μm)
- feet (ft)
Additional notes
value of G = 6.67 x 10-11N.kg–2.m2
How to zoom text by mouse wheel in IntelliJ Idea
It’s a common requirement to be able to zoom in or out while working in the code editor in IntelliJ Idea.
This is achieved on Windows with
CTRL+Mouse Wheel, or on Mac withCMD+Mouse Wheel.This feature is not enabled by default, but luckily it’s very simple to enable this.
How to enable mouse wheel zoom in IntelliJ
Open the Settings, or Preferences window.
On Windows you can press
CTRL+ALT+S, and on Mac you can pressCMD+,Playing the Bulls and Cows Game in Java
The challenge
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.
Calculate the Sum of Root To Leaf Binary Numbers in Java
The challenge
Given a binary tree, each node has value `` or
1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is0 -> 1 -> 1 -> 0 -> 1, then this could represent01101in binary, which is13.For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Remove an Exclamation Mark from the End of String using Python
The challenge
Remove a exclamation mark from the end of string. You can assume that the input data is always a string, no need to verify it.
Examples
remove("Hi!") === "Hi" remove("Hi!!!") === "Hi!!" remove("!Hi") === "!Hi" remove("!Hi!") === "!Hi" remove("Hi! Hi!") === "Hi! Hi" remove("Hi") === "Hi"Test cases
test.describe("Basic Tests") tests = [ #[input, [expected]], ["Hi!", "Hi"], ["Hi!!!","Hi!!"], ["!Hi", "!Hi"], ["!Hi!", "!Hi"], ["Hi! Hi!", "Hi! Hi"], ["Hi", "Hi"], ] for inp, exp in tests: test.assert_equals(remove(inp), exp)The solution in Python
Option 1:
How to “Rock Paper Scissors” in Java
The challenge
Let’s play Rock Paper Scissors! You have to return which player won! In case of a draw return
Draw!.Examples:
rps('scissors','paper') // Player 1 won! rps('scissors','rock') // Player 2 won! rps('paper','paper') // Draw!The rules of the game Rock Paper Scissors
The rules of the game Rock Paper Scissors is quite simple.
Rock beats scissors, scissors beats paper, and paper beats rock.
Below is an illustration showing the cyclical routes.
Compare within Margin using Python
The challenge
Create a function
close_comparethat accepts 3 parameters:a,b, and an optionalmargin. The function should return whetherais lower than, close to, or higher thanb.ais “close to”bifmarginis higher than or equal to the difference betweenaandb.When
ais lower thanb, return-1.When
ais higher thanb, return1.When
ais close tob, return ``.Get the mean of an array in Java
The challenge
It’s the academic year’s end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script.
Return the average of the given array rounded down to its nearest integer.
The array will never be empty.
Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void simpleTest() { assertEquals(2,School.getAverage(new int[] {2,2,2,2})); assertEquals(3,School.getAverage(new int[] {1,2,3,4,5})); assertEquals(1,School.getAverage(new int[] {1,1,1,1,1,1,1,2})); } }The solution in Java
Option 1:
Remove the time challenge in Python
The challenge
You’re re-designing a blog and the blog’s posts have the following format for showing the date and time a post was made:
Weekday Month Day, time e.g., Friday May 2, 7pm
You’re running out of screen real estate, and on some pages you want to display a shorter format, Weekday Month Day that omits the time.
Write a function, shortenToDate, that takes the Website date/time in its original string format, and returns the shortened format.
How to Convert Hex to Decimal in Java
The challenge
Write a function that converts an input string contains a
hexvalue, and return adecimal.Test cases
import org.junit.Test; import static org.junit.Assert.*; public class ExampleTests { @Test public void examples() { // assertEquals("expected", "actual"); assertEquals(1, ConvertHexToDec.hexToDec("1")); assertEquals(10, ConvertHexToDec.hexToDec("a")); assertEquals(16, ConvertHexToDec.hexToDec("10")); assertEquals(255, ConvertHexToDec.hexToDec("FF")); assertEquals(-12, ConvertHexToDec.hexToDec("-C")); } }The solution in Java
In Java, it is really easy to convert Hex to Decimal.
You simply use the
Integerclass and call theparseIntmethod, making sure to also provide the base that you want to convert from.Character with Longest Consecutive Repetition in Java
The challenge
For a given string
sfind the characterc(orC) with longest consecutive repetition and return:Object[]{c, l};where
l(orL) is the length of the repetition. If there are two or more characters with the samelreturn the first in order of appearance.For empty string return:
Object[]{"", 0}Test cases
import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void exampleTests() { assertArrayEquals(new Object[]{"a", 4}, Solution.longestRepetition("aaaabb")); assertArrayEquals(new Object[]{"a", 4}, Solution.longestRepetition("bbbaaabaaaa")); assertArrayEquals(new Object[]{"u", 3}, Solution.longestRepetition("cbdeuuu900")); assertArrayEquals(new Object[]{"b", 5}, Solution.longestRepetition("abbbbb")); assertArrayEquals(new Object[]{"a", 2}, Solution.longestRepetition("aabb")); assertArrayEquals(new Object[]{"", 0}, Solution.longestRepetition("")); } }The solution in java
Option 1:
Check if List contains Item in Python
The challenge
Create a method that accepts a list and an item, and returns
trueif the item belongs to the list, otherwisefalse.Test cases
list = [0,1,2,3,5,8,13,2,2,2,11]; Test.assert_equals(include(list, 100), False, "list does not include 100") Test.assert_equals(include(list, 2), True, "list includes 2 multiple times") Test.assert_equals(include(list, 11), True, "list includes 11") Test.assert_equals(include(list, "2"), False, "list includes 2 (integer), not ''2'' (string)") Test.assert_equals(include([], 0), False, "empty list doesn't include anything") Test.assert_equals(include(list, 0), True, "list includes 0")The solution in Python
def include(arr,item): return item in arrHow To Create a User and Grant Permissions in MySQL
How to create a user
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';How to delete a user
DROP USER 'myuser'@'localhost';How to grant permissions
GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost';How to apply those permissions
FLUSH PRIVILEGES;Going a bit deeper
Different types of Grants
ALL PRIVILEGES: Full access to everything, globally unless restricted to a databaseCREATE: Create databases and tablesDROP: Delete databases and tablesDELETE: Delete rows from tablesHow to Remove Vowels with Python
The challenge
Create a function called
shortcutto remove all the lowercase vowels in a given string.Examples
shortcut("codewars") # --> cdwrs shortcut("goodbye") # --> gdbyDon’t worry about uppercase vowels.
Test cases
import random Test.describe("Easy") for t in [ ["hello","hll"], ["hellooooo","hll"], ["how are you today?","hw r y tdy?"], ["complain","cmpln"], ["never","nvr"] ]: ans,exp = shortcut(t[0]), t[1] Test.assert_equals(ans,exp) Test.describe("Not so easy") for t in [ ["a e i o u, borriquito como tu"," , brrqt cm t","Isolated vowels let spaces between them"], ["Explicit is better than implicit", "Explct s bttr thn mplct","Should remove only lowercase vowel"], ["Beautiful is better than Ugly", "Btfl s bttr thn Ugly","Should remove only lowercase vowel"] ]: ans,exp = shortcut(t[0]), t[1] Test.assert_equals(ans,exp) # for t in random.sample([ ["We are the Knights who say ni!","W r th Knghts wh sy n!"], ["Nobody expects the Spanish Inquisition!","Nbdy xpcts th Spnsh Inqstn!"], ["He's not the messiah. He's a very naughty boy!","H's nt th mssh. H's vry nghty by!"], ["It's just a flesh wound.","It's jst flsh wnd."], ["You don't frighten us, English pig dogs.","Y dn't frghtn s, Englsh pg dgs."], ["Mate, this parrot wouldn't VOOM if you put four million volts through it!","Mt, ths prrt wldn't VOOM f y pt fr mlln vlts thrgh t!"], ["Five is a sufficiently close approximation to infinity.","Fv s sffcntly cls pprxmtn t nfnty."] ],7): ans,exp = shortcut(t[0]), t[1] Test.assert_equals(ans,exp)The solution in Python
Option 1 (long way):
How to find all files in a directory with extension
I needed to find all files in a directory on Linux that ended with the file extension
.php.How to find all files in a directory with extension
You can do this as follows:
cd <your directory path> find . -type f -name "*.php"How to find other file extensions in a directory
Just swap out the
.phpvalue for another file extension that you would like to search for instead.How to Sort a List in Python
In this tutorial, you will learn how to sort a list in Python, by following the below three steps:
- Options to sort a list in Python
- What is the difference between “sort” and “sorted”
- An example of using “sort”
- An example of using “sorted”
- How to Sort a List in Reverse
- Sort a list in Reverse using “sort”
- Sort a list in Reverse using “sorted”
- Sort with a Custom Function using Key
1. Options to sort a list in Python
There exist two main options, those are
sort()andsorted(), let’s explore them below.Cryptanalysis Word Patterns in Java
The challenge
In cryptanalysis, words patterns can be a useful tool in cracking simple ciphers.
A word pattern is a description of the patterns of letters occurring in a word, where each letter is given an integer code in order of appearance. So the first letter is given the code 0, and second is then assigned 1 if it is different to the first letter or 0 otherwise, and so on.
How to divide a number in Python
The challenge
Your task is to create function
isDivideBy(oris_divide_by) to check if an integer number is divisible by each out of two arguments.A few cases:
(-12, 2, -6) -> true (-12, 2, -5) -> false (45, 1, 6) -> false (45, 5, 15) -> true (4, 1, 4) -> true (15, -5, 3) -> trueTest cases
Test.describe("Basic Tests") Test.it("should pass basic tests") Test.assert_equals(is_divide_by(-12, 2, -6), True) Test.assert_equals(is_divide_by(-12, 2, -5), False) Test.assert_equals(is_divide_by(45, 1, 6), False) Test.assert_equals(is_divide_by(45, 5, 15), True) Test.assert_equals(is_divide_by(4, 1, 4), True) Test.assert_equals(is_divide_by(15, -5, 3), True)Understanding how to solve this
To resolve this problem, we need to understand how to find if a number can be divided without a remainder in Python. This is similar to other mathematical operations you might perform in Python, like finding the intersection of two arrays or converting RGB to Hex.
How to Read Kubernetes Secrets
Kubernetes secrets is a great way to store secret values that only Kubernetes can access in your hosted applications.
There are times when you might need to view these secrets in plain-text. This is probably because you want to validate the value or use it manually elsewhere.
In this tutorial we will go through how to achieve this and read Kubernetes secrets using
kubectlfor the command-line.tl;dr
kubectl get secret <SECRET_NAME> -o jsonpath="{.data.<DATA>}" | base64 --decodeIn the above sample code, simply replace
<SECRET_NAME>and<DATA>with your own values.Backspaces in String Challenge using Java
The challenge
Assume
"#"is like a backspace in string. This means that string"a#bc#d"actually is"bd"Your task is to process a string with
"#"symbols.Examples
"abc#d##c" ==> "ac" "abc##d######" ==> "" "#######" ==> "" "" ==> ""Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testCleanString() { final BackspacesInString bis = new BackspacesInString(); assertEquals("ac", bis.cleanString("abc#d##c")); assertEquals("", bis.cleanString("abc####d##c#")); } }The solution in Java
Option 1:
How many times to Kaprekar’s constant using Python
Introduction
6174 is known as Kaprekar’s constant after the Indian mathematician D. R. Kaprekar. This number is notable for the following rule:
- Take any four-digit number, using at least two different digits (leading zeros are allowed).
- Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
- Subtract the smaller number from the bigger number.
- Go back to step 2 and repeat.
The above process, known as Kaprekar’s routine, will always reach its fixed point, 6174, in at most 7 iterations. Once 6174 is reached, the process will continue yielding 7641 – 1467 = 6174. For example, choose 3524:5432 – 2345 = 30878730 – 0378 = 83528532 – 2358 = 61747641 – 1467 = 6174
How to check if a String is a Number in Python
The challenge
Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.
Valid examples, should return true:
isDigit("3") isDigit(" 3 ") isDigit("-3.23")should return false:
isDigit("3-4") isDigit(" 3 5") isDigit("3 5") isDigit("zero")Test cases
test.assert_equals(isDigit("s2324"), False) test.assert_equals(isDigit("-234.4"), True)The solution in Python
Option 1(with
try/except):# create a function def isDigit(string): # use a `try/except` block try: # True if can convert to a float float(string) return True except: # otherwise return False return FalseOption 2(with
regex/Regular expression):How to Write a Custom Comparator in Python
Generally, you want to use the built-in
sorted()function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.How the custom comparator works
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
- return a negative value (
< 0) when the left item should be sorted before the right item - return a positive value (
> 0) when the left item should be sorted after the right item - return `` when both the left and the right item have the same weight and should be ordered “equally” without precedence
The challenge
Write a comparator for a list of phonetic words for the letters of the greek alphabet.
How to delete an AWS WAF – Web ACL
Usually, it’s quite easy to delete an AWS WAF, or Web ACL. But sometimes you may come across the following error when attempting to delete the actual WAF:
AWS WAF couldn’t perform the operation because your resource is being used by another resource or it’s associated with another resource.
What this means
When you get this error, it means that there is something attached to the WAF that is currently using it.
How to Sort an Integer in Python
Let’s say that you have an integer with value of
9271and you want to sort it either ascending(1279) or descending(9721).How would you do this in Python? How would you sort an integer in either ascending or descending order?
Sorting our integer
Let’s set our integer to
n:n = 9271Now let’s sort it:
sorted([i for i in str(n)]) # This will give us a list in ascending order # ['1', '2', '7', '9']We can as easily do it the other way:
How to Upgrade PIP
In this tutorial, you will learn how to upgrade PIP.
You will also learn how to check the current version of PIP, as well as downgrade to a previous version of PIP if you really need to.
TLDR; How to Upgrade PIP
The most obvious way, if
pythonis mapped to the version you want pip to be upgraded on:python -m pip install --upgrade pipor if you are running
python3from thepython3command itself:How to Copy a File in Python
In this tutorial, you will learn how to copy a file using Python from a directory to another directory, or if you’re on Windows, then from a Folder to another Folder.
shutil.copyfileis a tool that is often used to copy a file in Python, below is an example of it’s usage, you can read more about it on the Python docs:import shutil # the source file original = '/path/to/the/file.extension' # the destination file target = '/path/to/the/new/destination/newname.extension' # perform the copy shutil.copyfile(original, target)Now let’s break this down and understand what happens…
Conway’s Game of Life – Unlimited Edition – in Python
What is this?
Conways’s Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc..
geeksforgeeks.org
How the game works
Because the Game of Life is built on a grid of nine squares, every cell has eight neighboring cells,as shown in the given figure. A given cell (i, j) in the simulation is accessed on a grid [i][j], where i and j are the row and column indices, respectively. The value of a given cell at a given instant of time depends on the state of its neighbors at the previous time step. Conway’s Game of Life has four rules.
Most frequently used words in a text with Python
The challenge
Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences.
Assumptions:
- A word is a string of letters (A to Z) optionally containing one or more apostrophes (‘) in ASCII. (No need to handle fancy punctuation.)
- Matches should be case-insensitive, and the words in the result should be lowercased.
- Ties may be broken arbitrarily.
- If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words.
Examples:
top_3_words("In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income.") # => ["a", "of", "on"] top_3_words("e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e") # => ["e", "ddd", "aa"] top_3_words(" //wont won't won't") # => ["won't", "wont"]Bonus points:
- Avoid creating an array whose memory footprint is roughly as big as the input text.
- Avoid sorting the entire array of unique words.
Test cases
from random import choice, randint, sample, shuffle, choices import re from collections import Counter def check(s, this=None): # this: only for debugging purpose returned_result = top_3_words(s) if this is None else this fs = Counter(w for w in re.findall(r"[a-zA-Z']+", s.lower()) if w != "'" * len(w)) exp,expected_frequencies = map(list,zip(*fs.most_common(3))) if fs else ([],[]) msg = '' wrong_words = [w for w in returned_result if not fs[w]] actual_freq = [fs[w] for w in returned_result] if wrong_words: msg = 'Incorrect match: words not present in the string. Your output: {}. One possible valid answer: {}'.format(returned_result, exp) elif len(set(returned_result)) != len(returned_result): msg = 'The result should not contain copies of the same word. Your output: {}. One possible output: {}'.format(returned_result, exp) elif actual_freq!=expected_frequencies: msg = "Incorrect frequencies: {} should be {}. Your output: {}. One possible output: {}".format(actual_freq, expected_frequencies, returned_result, exp) Test.expect(not msg, msg) @test.describe("Fixed tests") def fixed_tests(): TESTS = ( "a a a b c c d d d d e e e e e", "e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e", " //wont won't won't ", " , e .. ", " ... ", " ' ", " ''' ", """In a village of La Mancha, the name of which I have no desire to cao mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income.""", "a a a b c c X", "a a c b b", ) for s in TESTS: check(s) @test.describe("Random tests") def random_tests(): def gen_word(): return "".join(choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'") for _ in range(randint(3, 10))) def gen_string(): words = [] nums = choices(range(1, 31), k=20) for _ in range(randint(0, 20)): words += [gen_word()] * nums.pop() shuffle(words) s = "" while words: s += words.pop() + "".join(choice("-,.?!_:;/ ") for _ in range(randint(1, 5))) return s @test.it("Tests") def it_1(): for _ in range(100): check(gen_string())The solution using Python
Option 1:
The SongDecoder Dubstep Challenge with Java
The challenge
Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let’s assume that a song consists of some number of words (that don’t contain WUB). To make the dubstep remix of this song, Polycarpus inserts a certain number of words “WUB” before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including “WUB”, in one string and plays the song at the club.
Break camelCase Challenge in Java
The challenge
Complete the solution so that the function will break up camel casing, using a space between words.
Example
solution("camelCasing") == "camel Casing"Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void tests() { assertEquals( "Incorrect", "camel Casing", Solution.camelCase("camelCasing")); assertEquals( "Incorrect", "camel Casing Test", Solution.camelCase("camelCasingTest")); assertEquals( "Incorrect", "camelcasingtest", Solution.camelCase("camelcasingtest")); } }The solution in Java
class Solution { public static String camelCase(String input) { String out = ""; for (int i=0; i<input.length(); i++) { String c = Character.toString(input.charAt(i)); if (c.equals(c.toUpperCase())) { out+=" "; } out+=c; } return out; } }Sort Binary Tree by Levels using Python
The challenge
You are given a binary tree:
class Node: def __init__(self, L, R, n): self.left = L self.right = R self.value = nYour task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.
Return empty list if root is
None.Example 1 – following tree:
How to Split a String with Python
Splitting a string in Python is really easy.
You simply take a
stringand apply thesplit()method."Your String".split()See some examples of the Python Split String method:
A Python Split String – Example
# Your string a_string = "This is our string" # Split into a list a_list = a_string.split() # Print the list print(a_list)Python Split String – Syntax
string.split(separator, maxsplit)Parameter Values
Parameter Description separator Optional – What to split the string on. The default is the whitespace character maxsplit Optional – How many splits to perform. The default is -1, meaning “no limit” Some examples for Python Split String
Use a comma (
,) as the separator:How to fix the Terraform stuck on “Refreshing state…” problem
Terraform is a fantastic tool to help automate your infrastructure as code.
Quite a few times however, I have noticed a few strange issues, one of them is when Terraform gets stuck while refreshing the state.
This can happen when running
terraform planor in-fact, when running a range of other commands that require the state-file to be refreshed and used.The problem
Terraform gets stuck on this message:
Refreshing Terraform state in-memory prior to plan…The “Split Strings” Challenge using Java
The challenge
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (‘_’).
Examples:
StringSplit.solution("abc") // should return {"ab", "c_"} StringSplit.solution("abcdef") // should return {"ab", "cd", "ef"}Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.util.Arrays; public class SampleTest { @Test public void testEvenString() { String s = "abcdef"; String s1 = "HelloWorld"; assertEquals("Should handle even string","[ab, cd, ef]", Arrays.toString(StringSplit.solution(s))); assertEquals("Should handle even string","[He, ll, oW, or, ld]", Arrays.toString(StringSplit.solution(s1))); } @Test public void testOddString() { String s = "abcde"; String s1 = "LovePizza"; assertEquals("Should handle odd string","[ab, cd, e_]", Arrays.toString(StringSplit.solution(s))); assertEquals("Should handle odd string","[Lo, ve, Pi, zz, a_]", Arrays.toString(StringSplit.solution(s1))); } @Test public void testEmptyString() { String s = ""; assertEquals("Should handle empty string","[]", Arrays.toString(StringSplit.solution(s))); } }The solution in Java
public class StringSplit { public static String[] solution(String s) { // if it's blank, then return if (s.length()==0) return new String[0]; // if not even, then add an underscore to the end if (s.length()%2!=0) { s+="_"; } // determine the space needed for the return array int spaceNeeded = s.length()/2; // create a new array to populate and return String[] out = new String[spaceNeeded]; // create an builder index int j = 0; // loop through the input string for (int i=0; i<s.length(); i++) { // create a new string to build StringBuilder sb = new StringBuilder(); // add the current item sb.append(s.charAt(i)); // add the next item sb.append(s.charAt(i+1)); // populate our output string as we go out[j] = sb.toString(); // increment both counters i++; j++; } // return the built string return out; } }A simple alternative using regular expressions:
Converting to PigLatin with Python
The challenge
Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched. This string manipulation challenge is similar to other Python exercises like counting smiley faces or finding the intersection of two arrays.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway !Test cases
Test.assert_equals(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay') Test.assert_equals(pig_it('This is my string'),'hisTay siay ymay tringsay')How to write the code in Python
def pig_it(text): words = text.split(" ") new_words = [] for word in words: if word.isalpha(): new_word = word[1:] + word[0] + "ay" new_words.append(new_word) else: new_words.append(word) return " ".join(new_words)Solving the “Double Cola” Challenge using Java
The challenge
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a “Double Cola” drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.
Convert Seconds to Human Readable Time (HH:MM:SS) using Java
The challenge
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (
HH:MM:SS)HH= hours, padded to 2 digits, range: 00 – 99MM= minutes, padded to 2 digits, range: 00 – 59SS= seconds, padded to 2 digits, range: 00 – 59
The maximum time never exceeds 359999 (
99:59:59)Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; public class ExampleTest { @Test public void Tests() { assertEquals("makeReadable(0)", "00:00:00", HumanReadableTime.makeReadable(0)); assertEquals("makeReadable(5)", "00:00:05", HumanReadableTime.makeReadable(5)); assertEquals("makeReadable(60)", "00:01:00", HumanReadableTime.makeReadable(60)); assertEquals("makeReadable(86399)", "23:59:59", HumanReadableTime.makeReadable(86399)); assertEquals("makeReadable(359999)", "99:59:59", HumanReadableTime.makeReadable(359999)); } }The solution in Java
public class HumanReadableTime { public static String makeReadable(int seconds) { return String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60)); } }Solving the “Mexican Wave” Challenge using Java
The challenge
Task
Your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up.
Rules
1. The input string will always be lowercase but may be empty.
2. If the character in the string is whitespace then pass over it as if it was an empty seat.Multiples of 3 and 5 with Python
The challenge
This multiples of 3 and multiples of 5 challenge is a variation of the common FizzBuzz question.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. This challenge requires similar modulo operations as seen in how to divide a number in Python.
Solving the “Catching Car Mileage Numbers” Challenge using Python
The challenge
"7777…8?!??!", exclaimed Bob, "I missed it again! Argh!" Every time there's an interesting number coming up, he notices and then promptly forgets. Who doesn't like catching those one-off interesting mileage numbers?
Let’s make it so Bob never misses another interesting number. We’ve hacked into his car’s computer, and we have a box hooked up that reads mileage numbers. We’ve got a box glued to his dash that lights up yellow or green depending on whether it receives a
1or a2(respectively).Counting smiley faces with Python
The challenge
Given an array (arr) as an argument complete the function
countSmileysthat should return the total number of smiling faces.Rules for a smiling face:
- Each smiley face must contain a valid pair of eyes. Eyes can be marked as
:or; - A smiley face can have a nose but it does not have to. Valid characters for a nose are
-or~ - Every smiling face must have a smiling mouth that should be marked with either
)orD
No additional characters are allowed except for those mentioned.
Convert String to Camel Case using Java
The challenge
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
Examples
toCamelCase("the-stealth-warrior"); // returns "theStealthWarrior" toCamelCase("The_Stealth_Warrior"); // returns "TheStealthWarrior"Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomeUnderscoreLowerStart() { String input = "the_Stealth_Warrior"; System.out.println("input: "+input); assertEquals("theStealthWarrior", Solution.toCamelCase(input)); } @Test public void testSomeDashLowerStart() { String input = "the-Stealth-Warrior"; System.out.println("input: "+input); assertEquals("theStealthWarrior", Solution.toCamelCase(input)); } }The solution in Java
import java.lang.StringBuilder; class Solution{ // Our method static String toCamelCase(String s){ // create a StringBuilder to create our output string StringBuilder sb = new StringBuilder(); // determine when the next capital letter will be Boolean nextCapital = false; // loop through the string for (int i=0; i<s.length(); i++) { // if the current character is a letter if (Character.isLetter(s.charAt(i))) { // get the current character char tmp = s.charAt(i); // make it a capital if required if (nextCapital) tmp = Character.toUpperCase(tmp); // add it to our output string sb.append(tmp); // make sure the next character isn't a capital nextCapital = false; } else { // otherwise the next letter should be a capital nextCapital = true; } } // return our output string return sb.toString(); } }How to Setup an SSH Server on AWS
Basic instructions on how to set up an SSH server on an Ubuntu 16.04/18.04 EC2 instance.
Step 1 – Create a New User
sudo adduser testuserStep 2 – Create a Directory for File Transfers
sudo mkdir -p /var/sftp/uploads sudo chown root:root /var/sftp sudo chmod 755 /var/sftp sudo chown testuser:testuser /var/sftp/uploadsStep 3 – Restrict Access to One Directory
Open the SSH server configuration file
sudo nano /etc/ssh/sshd_configAdd the following to the bottom of the file:
How to Convert Numeric Words into Numbers using Python
Challenge
Using Python, we want to convert words into numbers. In this challenge, we will explore how to convert a string into an integer.
The strings simply represent the numbers in words. Let’s convert these words into numbers.
Examples:
- “one” => 1
- “twenty” => 20
- “two hundred forty-six” => 246
- “seven hundred eighty-three thousand nine hundred and nineteen” => 783919
Additional Notes:
- The minimum number is “zero” (inclusively)
- The maximum number, which must be supported is 1 million (inclusively)
- The “and” in e.g. “one hundred and twenty-four” is optional, in some cases it’s present and in others, it’s not
- All tested numbers are valid, you don’t need to validate them
Test cases to convert words into numbers
Test.assert_equals(parse_int('one'), 1) Test.assert_equals(parse_int('twenty'), 20) Test.assert_equals(parse_int('two hundred forty-six'), 246)The solution in Python to convert words into numbers
def parse_int(textnum, numwords={}): # create our default word-lists if not numwords: # singles units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] # tens tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] # larger scales scales = ["hundred", "thousand", "million", "billion", "trillion"] # divisors numwords["and"] = (1, 0) # perform our loops and start the swap for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) # primary loop current = result = 0 # loop while splitting to break into individual words for word in textnum.replace("-"," ").split(): # if problem then fail-safe if word not in numwords: raise Exception("Illegal word: " + word) # use the index by the multiplier scale, increment = numwords[word] current = current * scale + increment # if larger than 100 then push for a round 2 if scale > 100: result += current current = 0 # return the result plus the current return result + currentSolve The Triangle of Odd Numbers using Python
The challenge
Given the triangle of consecutive odd numbers:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ...Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
row_sum_odd_numbers(1); # 1 row_sum_odd_numbers(2); # 3 + 5 = 8Test cases
Test.assert_equals(row_sum_odd_numbers(1), 1) Test.assert_equals(row_sum_odd_numbers(2), 8) Test.assert_equals(row_sum_odd_numbers(13), 2197) Test.assert_equals(row_sum_odd_numbers(19), 6859) Test.assert_equals(row_sum_odd_numbers(41), 68921)The solution in code
While there are many ways to achieve this, the absolute most simple is to realise that the solution is just a
n^3.“Who likes it” code Challenge in Python
The Challenge
You probably know the “like” system from Facebook and other pages. People can “like” blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement a function
likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:Python 4 New Features Planned
It took the Python community a long time to move from Python 2 to Python 3. Now as we approach the possible end of Python 3 version history, we are approaching a potential Python 4.
What to expect in Python 4
Other than Python version 4 being mentioned in the PEP documentation, there is currently no formal writeup of the Python 4 feature-set.
Therefore we have to either believe that it will be the next version after 3.9, and will simply become 3.10. Otherwise it will fall back to version 4.
Custom RGB To Hex Conversion with Python
The challenge
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 – 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
Sort a Java Integer in Descending Order
The challenge
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples:
Input:
42145Output:54421Input:
145263Output:654321Input:
123456789Output:987654321Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; public class DescendingOrderTest { @Test public void test_01() { assertEquals(0, DescendingOrder.sortDesc(0)); } @Test public void test_02() { assertEquals(51, DescendingOrder.sortDesc(15)); } @Test public void test_03() { assertEquals(987654321, DescendingOrder.sortDesc(123456789)); } }The solution in Java
public class DescendingOrder { public static int sortDesc(final int num) { // return if a negative number if (num<0) return num; // our number we will return int sortedNumber = 0; // loop with a maximum number int // perform loop in reverse for (int i = 9; i >= 0; i--) { // set a local number variable int tmpNumber = num; // while greater than 0 while (tmpNumber > 0) { // get the digit int digit = tmpNumber % 10; // check for the greatest digit in the given number if (digit == i) { // build the sortedNumber value sortedNumber *= 10; sortedNumber += digit; } // reduce the loop variable tmpNumber /= 10; } } // return our sorted number return sortedNumber; } }Get the Sum of Digits / Digital Root using Java
The challenge
Digital root is the recursive sum of all the digits in a number.
Given
n, take the sum of the digits ofn. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.Examples
16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2Tests cases
import org.junit.Test; import static org.junit.Assert.assertEquals; public class DRootExampleTest { @Test public void Tests() { assertEquals( "Nope!" , 7, DRoot.digital_root(16)); assertEquals( "Nope!" , 6, DRoot.digital_root(456)); } }The solution in Java
public class DRoot { public static int digital_root(int n) { // return the number if less than 10 // this is to break out of the recursion loop if (n<10) return n; // set an output variable int out = 0; // while we still have numbers, loop while(n>0) { // increment our output by the base out += n % 10; // reduce the base by the same amount n = n / 10; } // return a recursion of the output return digital_root(out); } }How to write a Chain Adding Function in Python
The challenge
We want to create a function that will add numbers together when called in succession.
add(1)(2); # returns 3We also want to be able to continue to add numbers to our chain.
add(1)(2)(3) # 6 add(1)(2)(3)(4) # 10 add(1)(2)(3)(4)(5) # 15and so on.
A single call should return the number passed in.
add(1); # 1We should be able to store the returned values and reuse them.
addTwo = add(2) addTwo # 2 addTwo + 5 # 7 addTwo(3) # 5 addTwo(3)(5) # 10We can assume any number being passed in will be valid whole number.
Get the next biggest number with the same digits using Python
The challenge
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21 513 ==> 531 2017 ==> 2071nextBigger(num: 12) # returns 21 nextBigger(num: 513) # returns 531 nextBigger(num: 2017) # returns 2071If the digits can’t be rearranged to form a bigger number, return
-1(ornilin Swift):9 ==> -1 111 ==> -1 531 ==> -1nextBigger(num: 9) # returns nil nextBigger(num: 111) # returns nil nextBigger(num: 531) # returns nilTest cases
Test.assert_equals(next_bigger(12),21) Test.assert_equals(next_bigger(513),531) Test.assert_equals(next_bigger(2017),2071) Test.assert_equals(next_bigger(414),441) Test.assert_equals(next_bigger(144),414)The solution in Python
This problem requires careful manipulation of digits and arrays, similar to other Python challenges like finding the intersection of two arrays or getting the last element of a list.
Solving Tribonacci Sequence with Python
The challenge
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next.
So, if we are to start our Tribonacci sequence with
[1, 1, 1]as a starting input (AKA signature), we have this sequence:[1, 1 ,1, 3, 5, 9, 17, 31, ...]But what if we started with
[0, 0, 1]as a signature? As starting with[0, 1]instead of[1, 1]basically shifts the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:The Casino Chips Problem Solved with Python
The challenge
You are given three piles of casino chips: white, green and black chips:
- the first pile contains only white chips
- the second pile contains only green chips
- the third pile contains only black chips
Each day you take exactly two chips of different colors and head to the casino. You can chose any color, but you are not allowed to take two chips of the same color in a day.
Check if Isogram using Python
The challenge
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
is_isogram("Dermatoglyphics" ) == true is_isogram("aba" ) == false is_isogram("moOse" ) == false # -- ignore letter caseTest cases
Test.assert_equals(is_isogram("Dermatoglyphics"), True ) Test.assert_equals(is_isogram("isogram"), True ) Test.assert_equals(is_isogram("aba"), False, "same chars may not be adjacent" ) Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) Test.assert_equals(is_isogram("isIsogram"), False ) Test.assert_equals(is_isogram(""), True, "an empty string is a valid isogram" )The solution in Python
First pass, using a dictionary (
dict):Find the Longest Common Prefix using Python
The challenge
Write a function to find the longest common prefix string amongst an array of strings. This string manipulation challenge requires careful handling of arrays, similar to getting the last element of a list in Python.
If there is no common prefix, return an empty string
"". For more Python string challenges, you might also be interested in converting to PigLatin.Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
Count and Say with Python
The challenge
he count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
The Plus One problem solved with Python
The challenge
Given a non-empty array of digits representing a non-negative integer, increment one to the integer. This challenge involves array manipulation similar to finding the intersection of two arrays.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. For more Python array challenges, you might also be interested in getting the last element of a list.
Solving the Single Number problem in Python
The challenge
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
The solution in Python
def singleNumber(nums): # create a dictionary/hashmap found = {} # loop through the nums for i in nums: # add to map if not found if i not in found: found[i] = i else: # otherwise remove it del found[i] # loop through the found map and return the first item for i in found: return iRotate a Matrix List in Python
The challenge
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ]
Example 2:
Check if Valid Sudoku Blocks in Java
The challenge of solving valid Sudoku blocks
Determine if a 9×9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9without repetition. - Each column must contain the digits
1-9without repetition. - Each of the 9
3x3sub-boxes of the grid must contain the digits1-9without repetition.
(A partially filled sudoku which is valid.)
Find the Intersection of Two Arrays in Python
The challenge
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
This is a common array manipulation problem that’s similar to other Python challenges like counting smiley faces or getting the next biggest number with the same digits.
Rotate an Array K Times in Python
The challenge
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
FizzBuzz in Java
The challenge
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]The solution in Java
class Solution { public List<String> fizzBuzz(int n) { List<String> l = new ArrayList<>(); for (int i=1; i<=n; i++) { if (i%3==0 && i%5==0) { l.add("FizzBuzz"); } else if (i%3==0) { l.add("Fizz"); } else if (i%5==0) { l.add("Buzz"); } else { l.add(""+i); } } return l; } }Python Splices reimplemented in Java
Python has a fantastic feature called
slices. It allows you to work with alist,setorstringby it’s index items.E.g.:
string_sample = "hello world" string_sample[:-1] >>> "hello worl" string_sample[-1] >>> "d" string_sample[3] >>> "l"You can also do things like:
string_sample[3:5] >>> 'lo'Or even in reverse!
string_sample[::-1] >>> 'dlrow olleh'A possible Java implementation
public String slice_start(String s, int startIndex) { if (startIndex < 0) startIndex = s.length() + startIndex; return s.substring(startIndex); } public String slice_end(String s, int endIndex) { if (endIndex < 0) endIndex = s.length() + endIndex; return s.substring(0, endIndex); } public String slice_range(String s, int startIndex, int endIndex) { if (startIndex < 0) startIndex = s.length() + startIndex; if (endIndex < 0) endIndex = s.length() + endIndex; return s.substring(startIndex, endIndex); }Solving Two Sum in Python
The challenge
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[] + nums[1] = 2 + 7 = 9, return [, 1].
The solution in Python
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # keep a hashmap of items found seen = {} # loop through the nums, with int and value for i, v in enumerate(nums): # set remaining to the target minus the value remaining = target - v # check if the new value is in the hashmap if remaining in seen: # return it and the index return [seen[remaining], i] # otherwise, put it on the map instead seen[v] = i # nothing found, return an empty list return []Get the Next Small Integer in Python
The challenge
Write a function:
def solution(A)that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given
A = [1, 3, 6, 4, 1, 2], the function should return 5.Given
A = [1, 2, 3], the function should return 4.Given
A = [−1, −3], the function should return 1.Write an efficient algorithm for the following assumptions:
Is a Valid Palindrome with Java
The challenge
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
Constraints:
sconsists only of printable ASCII characters.
The solution in Java
class Solution { // take in a String public boolean isPalindrome(String s) { // remove all non-alphanumeric characters and lowercase everything s = s.replaceAll("\\P{Alnum}", "").toLowerCase(); // loop through the String for (int i=0; i<s.length(); i++) { // if the beginning and last characters don't match, return false // also walk in both directions and do the same if (s.charAt(i)!=s.charAt(s.length()-i-1)) return false; } // return true if we get here return true; } }Is a Valid Anagram with Java
The challenge
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Note:
You may assume the string contains only lowercase alphabets.Follow up:
What if the inputs contain Unicode characters? How would you adapt your solution to such a case?How to ReImplement strStr() in Java
What we want to achieve
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
How to code this
class Solution { public int strStr(String haystack, String needle) { // If needle is an empty string if (needle.isEmpty()) return 0; // If the needle is not within the haystack if (!haystack.contains(needle)) return -1; // declare an index and the needle's length int index = 0; int len = needle.length(); // loop through the hackstack minus the needle's length for (int i = 0; i <= haystack.length() - len; i++) { // compare the needle with the hackstack new string // created from using substring, start->end if (haystack.substring(i, i + len).equals(needle)) { // set the index and exit index = i; break; } } return index; } }Third Maximum Number with Java
The challenge
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:
Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.
The solution
I have seen many possible resolutions to this problem, but my favourite has to be the following:
How to Quickly Hide all Icons on a Mac’s Desktop
Why the need to hide icons?
Perhaps you have a
screen-share sessioncoming up and you want a nice clean desktop to show everyone. Also, nobody will see all your funny files and folders as they wait for you.Just open the
Terminaland enter the following to hide all icons:If you’re not familiar with the
Terminal; it is a Mac application that allows you to enter commands like the ones below, to enable and disable advanced features, among other things.First Unique Character in a String using Java
The challenge
Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.
Examples:
s = "spacesuite" return 1. s = "simplespacesuite" return 2.
Note: You may assume the string contains only lowercase English letters.
The solution
class Solution { // take in a String and return an int containing the index public int firstUniqChar(String s) { // create a HashMap to hold our counts HashMap<Character, Integer> h = new HashMap<>(); // get the string's length int len = s.length(); // loop to populate the HashMap for(int i=0; i<len; i++) { // get the Character char c = s.charAt(i); // add or update HashMap entry h.put(c, h.getOrDefault(c, 0)+1); } // loop to look for non-duplicates for(int i=0; i<len; i++) { // get the Character char c = s.charAt(i); // if only have 1 item, then we found our match if (h.get(c)==1) return i; } // return -1 if all else fails return -1; } }How to fix the Release Version 5 Not Supported error in IntelliJ
What do you do when you create a new Maven Java project, and when you run it, you get the following error:
Error:java: error: release version 5 not supportedSometimes the error could also read as follows:
java: Source option 5 is no longer supported. Use 6 or later.Luckily for us, the solution is exactly the same!
Solution
Open the project’s
pom.xmlfile and add the following snippet:<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>Now open the Maven side-panel, and click the
Report All Maven Projectsbutton.Facebook’s custom IPv6 range
I noticed an interesting thing with a certain visitor after posting a blog post to Facebook.
The IP address that the Facebook crawler uses to visit the site on callback to get meta-data has a custom IPv6 sub-range.
IPv6: 2a03:2880:ff:1a::face:b00c Host: fwdproxy-prn-026.fbsv.netNotice
2a03:2880:ff:1a::<strong>face:b00c</strong>How this is done
The IPv4 addresses could only use regular integers (decimal); numbers between 0 and 9.
However, IPv6 can use any and all hexadecimal; 0-9 and a-f.
How to Reverse an Integer in Java
The challenge
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.The solution
class Solution { // take in int, return int public int reverse(int x) { // set a Long variable to return // we make it a long incase we catch the edge case // of a larger size than int long out = 0; // loop while processing while(x!=0) { // multiple by 10 and add decimal place division out = out * 10 + x % 10; // move the decimal place by 1 x /= 10; } // return 0 if edge case found if (Integer.MAX_VALUE<out || out<Integer.MIN_VALUE) return 0; // return the output and cast to an int return (int)out; } }Reverse a String in-place using Java
The challenge
Write a function that reverses a string. The input string is given as an array of characters
char[].Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
The solution
The goal here is to not create a new array, or string, but to rather make the change in-place using the single character array.
Check if a Java array Contains Duplicates
The challenge
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
The solution
class Solution { // return a boolean from the primitive int array input public boolean containsDuplicate(int[] nums) { // create a HashMap to hold our values HashMap<Integer, Integer> hm = new HashMap<>(); // loop through the input array for (int i=0; i<nums.length; i++) { // return true if we have seen a duplicate // otherwise add the int to the HashMap if (hm.get(nums[i])!=null) return true; else hm.put(nums[i], 1); } // return false if all else fails return false; } }Find All Numbers Disappeared in an Array using Python
The challenge
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
The solution
class Solution: # our method def findDisappearedNumbers(self, nums: List[int]) -> List[int]: # get the length / amount of items l=len(nums) # create a `set` to remove duplicates nums=set(nums) # create a new array to return d=[] # loop through the amount of items in the input array for i in range(1,l+1): # if the item is not in the input list if i not in nums: # add it to the return list d.append(i) # return the new array return dThe Array Height Checker Problem in Java
The challenge
Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.
Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.
Example 1:
Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: Current array : [1,1,4,2,1,3] Target array : [1,1,1,2,3,4] On index 2 (0-based) we have 4 vs 1 so we have to move this student. On index 4 (0-based) we have 1 vs 3 so we have to move this student. On index 5 (0-based) we have 3 vs 4 so we have to move this student.
Example 2:
Find the Squares of a Sorted Array in Java
The challenge
Given an array of integers
Asorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.Example 1:
Input: [-4,-1,0,3,10] Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11] Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000-10000 <= A[i] <= 10000Ais sorted in non-decreasing order.
The solution
class Solution { // return the sorted array squared public int[] sortedSquares(int[] A) { // create a new primitive int array int[] res = new int[A.length]; // loop through the input array for (int i=0; i<A.length; i++) { // square each value res[i] = A[i] * A[i]; } // finally sort the array Arrays.sort(res); // return the array return res; } }Sorting a Java Array by Parity
The challenge
Given an array
Aof non-negative integers, return an array consisting of all the even elements ofA, followed by all the odd elements ofA.You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 50000 <= A[i] <= 5000
The solution
class Solution { // return a sorted primitive int array public int[] sortArrayByParity(int[] A) { // keep track of place int lastIndex = 0; // loop through input array for (int i=0; i<A.length; i++) { // if we found an even number if (A[i]%2==0) { // keep track of the values int lastValue = A[lastIndex]; int thisValue = A[i]; // swap the values A[i] = lastValue; A[lastIndex] = thisValue; // increment our swap index lastIndex++; } } // return a sorted array return A; } }Remove Duplicates from Sorted Array in Java
Say you have an array of primitive integers and you want to remove all duplicates.
You can find out how many non-duplicate integers are in the array with this method:
class Solution { public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; } }Because we pass the
numsarray in as a reference, and modify the variable in-place with no additional space, you could just continue using it as is.Replace Elements with Greatest Element on Right Side using Java
The challenge
Given an array
arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with-1.After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^41 <= arr[i] <= 10^5
The solution
class Solution { public int[] replaceElements(int[] arr) { // loop through all array items for (int i=0; i<arr.length; i++) { // if the last item if (i==arr.length-1) { // set the last item arr[i] = -1; } else { // set a variable to check biggest value against int biggest = 0; // loop through the internal looperr for(int j=i+1; j<arr.length; j++) { // if the next value is bigger than our // current biggest, then update it if (arr[j]>biggest) biggest = arr[j]; } // replace the current value with the biggest found arr[i] = biggest; } } // return our array of ints return arr; } }The Valid Mountain Array Problem using Java
Introducing the problem
Given an array
Aof integers, returntrueif and only if it is a valid mountain array.Recall that A is a mountain array if and only if:
A.length >= 3- There exists some
iwith0 < i < A.length - 1such that:A[0] < A[1] < ... A[i-1] < A[i]A[i] > A[i+1] > ... > A[A.length - 1]
The constraints
Example 1:
HashMaps (aka: Dictionaries) in Python
Introduction
Java has a built-in called
HashMap. It allows you to store and very quickly retrieve key value pairs.In Python, this is called a
dictionaryand appears very similar to a JSON Object for those familiar with Javascript and similar languages.Dictionaries as HashMaps
An example of a dictionary in Python is as follows:
ages = {"Bob":25, "James":54, "Darren":44}The same can be created using the
dictkeyword:ages = dict({"Bob":25, "James":54, "Darren":44})A third way to create and populate this:
Find Numbers with Even Number of Digits using Java
The challenge
Given an array
numsof integers, return how many of them contain an even number of digits.Example 1:
Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits.
Example 2:
The Relational Database Model
Relational databases first made an appearance in the mid-1970s, between the years 1974 and 1977 with the creation of Ingres and System R which led to the creation of MS SQL Server, Sybase, Wang?s PACE and Britton-Lee to name a few (Quickbase, n.d.).
It was only until the 1980s that SQL (Structured Query Language) became the standard query language used by relational databases.
Basic features of the relational data model:
How to use a Java HashSet by example
What is a HashSet
A
HashSetis an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1)Learn with a Programming Question
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
Get The Shortest Path in Binary Matrix using Python
The challenge
In an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length
kif and only if it is composed of cellsC_1, C_2, ..., C_ksuch that:- Adjacent cells
C_iandC_{i+1}are connected 8-directionally (ie., they are different and share an edge or corner) C_1is at location(0, 0)(ie. has valuegrid[0][0])C_kis at location(N-1, N-1)(ie. has valuegrid[N-1][N-1])- If
C_iis located at(r, c), thengrid[r][c]is empty (ie.grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
Palindrome Partitioning in Python
The problem
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ]
The solution
def partition(self, s: str) -> List[List[str]]: ret = [] def isPal(s): return s == s[::-1] def fn(s, l): if not s: ret.append(l) return for i in range(1, len(s)+1): if isPal(s[:i]): fn(s[i:], l+[s[:i]]) fn(s, []) return retFaster alternative to MySQL Delete Table Contents / Truncate
From time to time you might have some rather big tables that you want to delete all the data quickly and start afresh.
You have a few options at this point. The first you?ll probably look at is:
DELETE FROM `table_name`The benefit of doing this is DELETE provides the ability to Rollback if all hell breaks loose, but it also means that it will take longer because it requires more memory to store all this additional data
Best Time to Buy and Sell Stock with Python
The problem
Say you have an array
pricesfor which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
IPv4 CIDR Chart
CIDR stands for
Classless Inter-Domain Routingand is a method for allocating IP addresses as well as for IP routing.It was introduced in 1993 by the Internet Engineering Task Force to replace the previous
classful network addressing architectureon the internet.When choosing a CIDR range for your network, the following chart will show you how many maximum IP’s you can have on that network.
For example,
/32will give you1 usable IP,/24will give you256 usable IPs, while/3will give you512 million usable IPs.Recursively Delete Files and Folders and all Contents using PHP
Below is a quick and easy way to recursively delete all files and folders in a given path using PHP.
function destroy_dir($dir) { if (!is_dir($dir) || is_link($dir)) return unlink($dir); foreach (scandir($dir) as $file) { if ($file == "." || $file == "..") continue; if (!destroy_dir($dir."/".$file)) { chmod($dir."/".$file, 0777); if (!destroy_dir($dir."/".$file)) return false; } } return rmdir($dir); } destroy_dir("/var/www/site/public_html/directory/");Product Update: ADD becomes Serengeti
As a product update; The “Autonomous Distributed Database”, otherwise known as simply
ADDhas been renamed toSerengeti.The Serengeti is a vast ecosystem in east-central Africa. It spans 12,000 square miles (30,000 square kilometers), according to NASA, giving rise to its name, which is derived from the Maasai language and means “endless plains.” This region of Africa is located in north Tanzania and extends to southwestern Kenya.
Much the same, the Serengeti database project is a truly autonomous distributed system that has no visible ending nor capacity. There is the potential to scale it infinitely, horizontally without downtime or data loss.
SQL to Append all Fields if Shorter than a set Length
This came in very handy for me at one point because I needed to have a certain field in each row 14 characters long, but half of them were only 12 characters long.
In MySQL:
update `table` set `field` = CONCAT(`field`, '1') where LEN(`field`) = 13;In MSSQL:
update `table` set `field` = CONCAT(`field`, '1') where LENGTH(`field`) = 13;Validate Email Address in Javascript
Below is a nice little Javascript RegularExpression to validate email addresses.
/^\w.+@[a-zA-Z_.]+?\.[a-zA-Z.]{2,3}$/..and to use it..
if (/^\w.+@[a-zA-Z_.]+?\.[a-zA-Z.]{2,3}$/.test(email)) alert("Success"); else alert("Fail");Remove hash from window.location in Javascript
E.g. URL:<br>http://example.com/?option=1&task=2&listing_id=36&layout=4&table=5#some_hash_value_hereSo how would you get the current URL using Javascript?
That is really easy, you can use window.location.href or just simply window.location.
But how do you replace the #hash at the end if it exists?
That too is quite easy, you can just do something like this:
window.location.href.split("#")[0]or
window.location.href.substr(0, window.location.href.indexOf("#"))So now that we have the value of the current URL how do we refresh the page with it?
The Benefits and Dangers of Artificial Intelligence
Artificial Intelligence (AI) is usually defined as the science of making computers do things that require intelligence when done by humans. (Jack Copeland, 2000)
Current Benefits of AI
- Replicate the decisions and actions of humans without human shortcomings.
- Computers don’t get fatigued and tired.
- Computers are not biased by emotions.
- Tasks are scalable and can be done very quickly and effectively.
Current Dangers of AI
- Some decisions require a level of
grey area. - Replacing jobs and roles done by humans leading to a higher level of unemployment and poverty.
- Viruses and bugs in code leading to catastrophic circumstances such as accidents with self-driving cars and in aviation systems.
There are many trends currently taking place in the field of AI.
The Decoded String at Index using Java
The Challenge
An encoded string
Sis given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:- If the character read is a letter, that letter is written onto the tape.
- If the character read is a digit (say
d), the entire current tape is repeatedly writtend-1more times in total.
Now for some encoded string
S, and an indexK, find and return theK-th letter (1 indexed) in the decoded string.Timing Issues in Real-time systems
What are Real-time Systems?
If you look up the term “real-time” in a dictionary, it will tell you that it is the actual time during which a process takes place or an event occurs (Dictionary.com, n.d.).
In computing, it is more often than not due to when an event is created and specific data service is able to respond with the newly updated event in its index.
What is a Timing issue?
Timing is quite potentially the most crucial aspect of achieving a truly real-time system. This is mainly due to the nature of what is trying to be achieved. With real-time systems, it is all about reacting to events as data points as soon as they have happened.
Find the Minimum Absolute Difference in BST using Java
The question
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).Note:
- There are at least two nodes in this BST.
The solution
We will start with a stub to build out:
Get the Second Highest Salary in MySQL
The problem
Write a SQL query to get the second highest salary from the
Employeetable.+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
For example, given the above Employee table, the query should return
200as the second highest salary. If there is no second highest salary, then the query should returnnull.+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
The solution
SELECT DISTINCT Salary AS SecondHighestSalary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1The output
{"headers": ["SecondHighestSalary"], "values": [[200]]}Find Maximum Subarrays using Java
The problem
Given an integer array
nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
The code
// This method takes an array of `ints` and returns an `int` public int maxSubArray(int[] nums) { // Set some `max` variables, // ..firstly the minimum `Integer` value // ..secondly `0` int max = Integer.MIN_VALUE; int iMax = 0; // Loop through all input `nums` for(int num : nums) { // increment the `iMax` each loop iMax = iMax + num; // check if `num` is bigger than `iMax` if(iMax < num) { // set `iMax` to the `num` iMax = num; } // set the `max` to the max of both our variables max = Math.max(max,iMax); } // return the `max` return max; }Finding Number Complements using Java
The problem
Given a positive integer
num, output its complement number. The complement strategy is to flip the bits of its binary representation.Example 1:
Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Constraints:
Forensic Analysis on Linux (Unix)
Operating Systems come in a few competing choices, of which the major players are Apple’s MacOS, Microsoft’s Windows and then the various flavours of Linux, of which most are open-sourced while the remainder are proprietary to their vendors.
Of the three, Windows is the most dissimilar, with MacOS and Linux sharing a similar BSD/Unix platform running behind the scenes. This gives MacOS and Linux similar traits when it comes to logging, analysing and tracing system event-logs.
Self Dividing Numbers using Python
Introduction
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because
128 % 1 == 0,128 % 2 == 0, and128 % 8 == 0.Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
RuntimeError: thread.__init__() not called (Python)
Today I got a really dumb error from Python.
RuntimeError: thread.init() not called
But luckily it’s really easy to fix!
Below is the code before (with the error):
class SomeThread(Thread): def __init__(self, myVar): self.sMyVar = str(myVar) def run(self): self.sMyVar = "bla.." + self.sMyVarAnd now for the code that resolved the problem:
class SomeThread(Thread): def __init__(self, myVar): Thread.__init__(self) self.sMyVar = str(myVar) def run(self): self.sMyVar = "bla.." + self.sMyVarIf you have really bad eye-sight and can’t spot the difference between the 2 code block above 😛
What we do is add the following code in the beginning of the construct – or __init__ in Python:All About Distributed Databases
A database “is a structured collection of data. Card indices, printed catalogues of archaeological artefacts and telephone directories are all examples of databases”.
We are going to examine databases that are prevalent in computer systems and go through the core differences between Local and Distributed Databases.
Local
A local database is an isolated database that is stored on a single computer and does not share its data outside of itself or its direct access network.
Network systems security risks
Networking has played a vital part in the transfer of information as well as the accessibility of information that was never available to previous generations with the rapid increase of internet-connected devices.
Along with the benefits of computing devices being connected to one another for information sharing, online shopping and many other helpful tasks, there is also a real threat present. This is termed under the overarching “Network Security” realm of topics.
Communications and The Software Development Process
Software Engineering or the Software Development Process is broken down into the following phases.
- Requirements
- Design
- Implementation
- Verification
- Maintenance
Communication can often breakdown in the system analysis phases. As a knock on effect, the requirements and design can end up not being correctly implemented during the mid to latter stages of software development.
Without correct communication, a software system can end up not meeting the requirements initially laid out by the end client – or whomever requested the system in the first place.
Get the total size of all the files in a directory
It’s amazing how many times I’ve need to find out the total size of all the files in a directory on one of our servers.
I have grown to love the simplicity of the `du` command.
du -shdu= Display disk Usage statisticsstells us to display an entry for each specified file, whilehis for “human-readable” output.This will use the unit suffixes of Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte.
Structured and Object-Oriented Programming
Software development has really come a long way over the past few decades.
Programming used to always be about doing things in a very procedural way, this means that each line of code is executed in the order that it is written (or placed) in a source code document – we refer to a file where programming code is stored as “source code”.
This is still very much a core basis when writing code, except as software applications have gotten infinitely more expansive and complex, there has been more of a need to reuse sections of code and make it more “modular”.
Moving a MySQL Database without downtime
At Statvoo Analytics we found ourselves in the position where we needed to move our master MySQL database without ANY downtime and for anyone who’s tried to do this, you will know how hard this can be if it is not done exactly right.
Below I will run through the steps to get the job done efficiently and with no downtime (unless you mess it up that is).
First, you need to configure the master’s
/etc/mysql/my.cnfand add the following lines in the[mysqld]section:How to use Google Analytics in AngularJS
It seems to be quite a popular question with not as many answers to hold the weight.
Google Analytics has always been more of a pageviews type tracking use case and up until a few years ago that was all anyone ever really did anyways. However, the web has gotten a lot more complicated with the introduction of javascript and heavy ajax based sites and web applications.
This has caused quite a change in how Analytics Tools are used and how they are expected to gather statistics.
Converting from Legacy to Client-Server or Distributed Systems
What is a legacy system?
A legacy system is a computing system that has been around for a very long period of time, tends to be difficult to maintain, is prone to issues such as lack of scalability and feature additions, usually centralised in operation and is still heavily utilised in a particular organisation.
What is a client-server / distributed system?
A distributed system is a decentralised networked cluster of computers (servers) that are able to scale according to peaks and troughs in usage (Manoj A. Thomas, 2009), is modular in the way components are reused and code is arranged as well as more maintainable by a team of developers that are trained in relevant new technologies.
Conceptual Architectural Views, with a focus on the Development View
What is Conceptual Architectural Views?
Architectural views are abstractions, or simplifications, of the entire design, in which important characteristics are made more visible by leaving details aside. (Eclipse, n.d.)
They are divided into four main sub-categories as illustrated below when using the 4+1 modelling system:
Each of the above segments paints a different perspective view on the architecture of a complex system, allowing for a simplified look into the inner workings and how everything works together.
Assessing Reusable Parts in a Software Architecture
During the Software Development Life Cycle (SDLC) the development team will come to realise that parts of any application have already been created before and there is the potential for those parts to be reused time and again going forward.
In the last few years, the culture of software development has moved towards Q&A sites such as StackOverflow to answer common daily problems that developers face. This has also led to many “Accepted Answers” being associated with these common issues and many developers have become quite indolent and simply copy/paste the code snippets directly from these types of websites straight into their application code they plan to ship. If and when it then resolves the problem they are facing, there is a high chance that the pasted code will eventually find it’s way into a production environment as is, or with very little change whatsoever.
An Introduction to 2-Tier and 3-Tier Client-Server Systems
All software systems can be grouped in either a 2-tier or a 3-tier formation.
The former is essentially where all clients contain application and business logic code to read from a datastore themselves (STC, n.d.) and the latter by comparison relies on a thin client that talks to an application layer server that contains business logic which in turn communicates with the datastore.
2-Tier Architecture
The two-tiered (
2 tier architecture) approach to application modelling is to run a fat client – one which contains all business logic code – and communicate directly with a database server itself.Remove the Outermost Parentheses using Python
The Question
A valid parentheses string is either empty
(""),"(" + A + ")", orA + B, whereAandBare valid parentheses strings, and+represents string concatenation. For example,"","()","(())()", and"(()(()))"are all valid parentheses strings.A valid parentheses string
Sis primitive if it is nonempty, and there does not exist a way to split it intoS = A+B, withAandBnonempty valid parentheses strings.The Pros and Cons of Agile in Software Development
What is Agile in Software Engineering?
Agile approaches help teams respond to unpredictability through incremental, iterative work cadences and empirical feedback. (AgileMethodology.org, 2008)
Advantages of Agile
- Flexibility
Potentially the main advantage to Agile is the ability to be more ?flexible? or ?agile? in terms of evolving a project as it develops as opposed to taking on a mammoth list of project requirements and only being able to show the customer the end result at project completion. (Kelly Waters, 2007) - Visibility
By undertaking a defined list of ?tasks? per ?sprint?, it allows all involved business units and customers to see the project unfolding at regular checkpoints before their eyes and provides the ability to make informed decisions about what additional backlog tasks should be added or removed for an overall better final project goal. - Ability to make iterative changes
Taking on smaller pieces of work allows developers to not be stuck with large refactoring of code when big sections of the project need to be re-worked at a later stage. (Alexander Mikula, 2015) - Development led project management
By giving project management tasks back to the development team, team members are aligned in what needs to be done and they have an knowledgeable invested interest in excelling at their individual tasks laid out by themselves. - Cost control
Undertaking sections of work at a time highlights how much of the project has been completed and what still needs to be done. This allows feature requests and backlog items to be aligned with remaining budgets allocated to the project.
Disadvantages of Agile
- Scope creep
Customers/analysts add features/tasks as the project evolves, making it difficult to complete the project without adding additional scope. (Stephen Haunts, 2014) - Does not scale well
Teams should be no more than approximately 10 members otherwise it gets harder to manage (Robert Galen, 2015). - Requires more re-work
Tasks undertaken separately without knowledge of the wider project roadmap, code often needs to be refactored to make room for additional specifications at a later stage. - Demanding on participants time
With developers involved in: planning, design, implementation, demos, retrospectives and more; it can be difficult to allocate a decent amount of time towards ?coding? per sprint. Often spending over 20% time on discussions per sprint. (Andrew Odendaal, 2016) - Testing costs can be higher
Need for QA to test each feature each sprint as opposed to only at the end of the project, this can add a lot more cost and resource. (Donald Patti, 2010)
Agile can be negative on a project when you have inexperienced developers that need hand-holding and are not able to take on tasks by themselves, there is a steep learning curve and more senior developers will need to spent a lot more time managing the processes.
Contemporary and beneficial uses of Big-Data Systems
Big data is a term applied to datasets whose size or type is beyond the ability of traditional relational databases to capture, manage, and process the data with low-latency. (IBM, 2018)
The V’s of Big Data
They share at least one or more of the common V’s; known as
Volume,VelocityandVariety.Additionally,
Veracity,Variability,VisualisationandValueare often seen to be added to the core list as drivers towards a more rounded architecture. (DeVan, 2016)Distributed Database Systems Observations
Traditional database systems were a centralised powerful database server that housed all operations pertaining to the database.
There are countless reasons that this is unsustainable when larger databases are employed, specifically for globally distributed companies and popular applications as already known today.
A single database server may suit many database’s requirements, but at some point, there may be a need to scale up to support higher demand or for global capacity requirements of sorts (Shalom, 2017).
Functions of an Operating System
I am in a bit of an unusual situation where “I use” a combination of three different laptops, which each run different platforms. Namely;
MacOSprimarily at work with a combination of Linux servers and thenWindowsas well asUbuntuon two separate home laptops that I switch between on my desk all the time between tasks.A bit on Windows
Windows is good as a general consumer OS and there are many applications that are created to run on it. The problems come in with the way applications are installed, the registry as well as the way the file system works.
ORDER BY RAND() – Faster Alternative
MySQL’s
ORDER BY RAND()function can be so useful for returning random items from a table, in fact, we have used it a million times over the years.The problem comes when your database tables start getting really big.
We found a very nice alternative to using it and thought it useful to post here for everyone else to use and/or provide feedback on.
Say you have a SQL query as follows: (slow on big tables)
Top-down vs Bottom-up Database Design
There are essentially two different approaches one can take when designing databases; these, from a high-level analytic point of view, narrow down to what is typically called “Top-down” and “Bottom-up” philosophies or methods.
While these methodologies can appear profoundly unique, they share the shared objective of joining a system by portraying the greater part of the association between the procedures.
Top-down
What is top-down approach to database design
Top-down design, is characterized by an extensive planning and research phase that leads into the development of the database (Maxey, 2012).
How to keep your web server or blog up when you get a traffic spike
So you’re about to be featured on some very high ranking website.
You’re worried that when all the visitors come rushing towards you, your web server?is going to crash and burn.?Well, you’re probably right!
Did you know that 95% of all websites on the internet are not able to handle more than 30 concurrent visitors the way they are setup?
Even worse still, most websites run off of either Shared hosting or un-tweaked VPS configurations that are not meant to handle many visitors in the first place.
How to get the UTC Timestamp in Python
All dates in your server applications should be stored in the UTC timezone.
This is because you always want to store time without the offset of the timezone you may be working in.
Clients of your application may be in many different timezones around the world. However, storing all data in the UTC or GMT (same thing) timezone, is ideal as it gives your application the ability to present times and dates back in the same methodology.
How to setup the AWS CLI for multiple profiles
The AWS CLI provides the ability to use the wide range of Amazon Web Services tools and services straight from the command-line. If you’re working with AWS, you might also be interested in how to push Docker images to AWS ECR or how to get the size of an AWS S3 bucket.
However, sometimes it’s useful to be able to login to multiple AWS accounts. Luckily, this is possible by adding an additional
profileto your local configuration and then specifying it when making calls to respective services. This is especially useful when making HTTP requests in AWS Lambda using Python.How to get the size of an AWS S3 bucket
If you need to get the size of an AWS S3 folder, or even an entire bucket, you can do so with the following command:
aws s3api --profile
list-objects --bucket --output json --query "[sum(Contents[].Size), length(Contents[])]" | awk 'NR!=2 {print $0;next} NR==2 {print $0/1024/1024/1024" GB"}' If you don’t use
aws cli profiles, then you can leave out theprofilepart like this:aws s3api list-objects --bucket --output json --query "[sum(Contents[].Size), length(Contents[])]" | awk 'NR!=2 {print $0;next} NR==2 {print $0/1024/1024/1024" GB"}'Remember to replace
<bucket_name>with your own bucket name.Comparing Java and Javascript
Perhaps the first thing that most people ask when they hear the names of these two programming languages are. “Why do they have the same name?” and “Are they the same thing?”.
There is a general misconception that because Java and Javascript share a similar name to one another, that they are indeed one and the same; but in reality, they are very different languages, which each address different types of problems and only share the smallest of traits.
An Introduction to Data Structures
When bringing up the topic of “Data Structures”, it is first important to understand what they are. TechTarget states that “a data structure is a specialized format for organizing and storing data”. This provides a high-level definition to get you started; so let’s explore it a little deeper.
Below are a few examples of common data structures:
Primitive types: Boolean, Integer, Double, Character, String
Composite/Non-primitive types: Array, Record, Union
Abstract types: List, Associate Array, Stack, Queue, Tree
Relational Database Proprietary Extensions
Standard Query Language – or SQL for short – is a language designed for relational databases that allows end users such as developers and database administrators (DBAs) to manipulate data.
Whether that be INSERT-ing, UPDATE-ing, DELETE-ing, SELECT-ing or otherwise ALTER-ing almost any amount of data; SQL provides an effective way of utilising the database system/engine by providing standardised language to do so.
The American National Standards Institute (ANSI) SQL became the standard in 1986 when the specification described the official features of the SQL language (Karmin, 2015).
Locks used in Database Management Systems
Database Management Systems (DBMS?) are designed to store any amount of data that can then be retrieved or manipulated at a later date.
In order to make sure that the data can be concurrently utilised in parallel by numerous processes or users, it is important to have some form of Locking enforced so that if a particular record is being modified or created, then another process is not allowed to simultaneously adjust the same record. If databases did not appoint locks, then the data could easily be overwritten and therefore become inconsistent and corrupt.
Tail and Grep: display all output but highlight search matches
I
taillogs quite a lot.An example would be to tail the Apache2 access logs.
This is simple to do:
tail -f /var/log/apache2/access.logThis will show a trail of all access log entries as they come in.
What if we only wanted to see when Googlebot accessed the site?
Highlight entries
We could filter only these results:
tail -f /var/log/apache2/access.log | grep -i googlebotThis will tail all logs, and
grepwill only shows results for case-insensitive instances ofgooglebotentries.Convert URL String into a Javascript Object
Sometimes you find yourself with a String, something like and you want to repeatably access elements of it correctly.
Let’s say that you want to only get the origin of a URL, or maybe the host, or even protocol, how would you do this?
The URL object
Javascript brings you the
URLobject, which allows you to instantiate it with a string, and optionally a base to work from.How to make an HTTP Request in AWS Lambda using Python
The
requestsmodule for Python is very useful in helping simplify HTTP/s requests from Python, but how would you use it in an AWS Lambda script?Option 1 – Use
requestsimportThe
requestslibrary is very popular among Python enthusiasts.You will need to create a custom lambda layer and include
requestsThis will allow you to use
import requestsin your code.Download the folder package
pip install requests -t .Run this command on your local machine, then zip your working directory and upload to AWS.
How to fix a Javascript Uncaught ReferenceError
Sometimes you may get an error that looks something like this:
Uncaught ReferenceError: <some_variable_or_function> is not definedAt first this can be quite the pain, but it usually just means that that variable, or function has either not been defined, or it isn’t ready for use yet.
It’s good practice to wrap this bit of code into a conditional check.
The original code
if (variable_or_function) { //console.log(variable_or_function); }The improved code
if (typeof variable_or_function !== 'undefined') { //console.log(variable_or_function); }Alternate methods
Does not execute if yourvar is
undefined:Resolving InsufficientPrivilege Errors in Redshift
If you are getting the mysterious error:
[ERROR] InsufficientPrivilege: permission denied for schema errorsThen you can easily resolve this by running the following SQL:
GRANT USAGE ON SCHEMA <schema_name> TO <redshift_user>;Another common error that often follows this, is:
[ERROR] InsufficientPrivilege: permission denied for relation <table>Luckily, this too can be resolved by running the following SQL:
GRANT USAGE ON SCHEMA <schema_name> TO <redshift_user>; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema_name> TO <redshift_user>;How to increase column size in Redshift database tables
It is only possible to alter
VARCHARcolumns, and only under the following circumstances:- You can not alter a column with compression encodings
BYTEDICT,RUNLENGTH,TEXT255, orTEXT32K. - You can not decrease the size less than the maximum size of existing data.
- You can not alter columns with default values.
- You can not alter columns with
UNIQUE,PRIMARY KEY, orFOREIGN KEY. - You can not alter columns inside a multi-statement block
(BEGIN...END).
SQL to increase the size of (Redshift Alter Table)
It’s very simple to perform a
Redshift Alter Tablecommand to alter the column length, or alter the column varchar length:[Solved] The provided execution role does not have permissions to call CreateNetworkInterface on EC2
If you are trying to get an AWS Lambda added attached to a VPC, but get the error message:
The provided execution role does not have permissions to call CreateNetworkInterface on EC2There are 3 ways to solve this problem
Below we will look at 3 different options when it comes to solving this problem:
- Fix the problem in Terraform
- Fix the problem in CloudFormation / SAM
- Fix the problem Manually in the AWS Console
How to fix the problem in Terraform
resource "aws_iam_role_policy_attachment" "AWSLambdaVPCAccessExecutionRole" { role = aws_iam_role.lambda.name policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" }How to fix the problem in CloudFormation
Type: "AWS::IAM::Role" Properties: RoleName: "lambda-with-vpc-access" ManagedPolicyArns: - "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Action: - sts:AssumeRole Principal: Service: - lambda.amazonaws.comHow to fix this problem Manually in the AWS Console
Then you can resolve this by adding a custom Inline Policy to the Lambda execution role under the Permissions tab.
Entity and Referential Integrity in Relational Databases
Data integrity is the overall completeness, accuracy and consistency of data (Techopedia, n.d.).
In order to achieve data integrity, it is important to analyse Entity and Referential integrity constraints.
Entity Integrity
Focuses on Primary keys.
Each table should have a primary key and each record must be unique and not null.
This makes sure that records in a table are not duplicated and remain intact during insert, update and retrieval.
Data Warehouses vs Data Marts
Although the terms “data warehouse” and “data mart” sound similar, they are quite different. It is important to first understand how they differ in order to define some characteristics and practical applications for each.
Serra (2012) has a great explanation of data warehouses as being “a single organizational repository of enterprise-wide data across many or all subject areas”; while Inmon classifies the data mart as “a logical view or a physical extract of a larger data warehouse, usually isolated for the need to have a special data model or schema” (n.d.).
Amazon’s custom Whois date entry
Whoisis an online service that let’s you know registration information about a website or IP address.For the most part, Whois aggregations are not that standard, however, per gTLD (
.com,.net,.yourkitchsink) they try their best to apply the same overall guidance and regulatory patterns.Most individuals, as well as businesses will go about registering their domain name through a service such as GoDaddy, Namecheap, or some other common domain registrar.
Graph Databases and their Properties
The concept of a graph in mathematics is simply a collection of elements which are typically called Nodes and are joined together by Edges. Each Node represents a piece of information in the graph and each Edge represents some relationship or connection between any of the two Nodes (Cox, 2017).
A graph database is simply a database that models itself on the connections that Nodes represent in a mathematical graph structure.
How to add SSH keys to GitHub
When working with GitHub, you will need to identify yourself. The default way is using your username and password. However, you can also create an SSH key-pair that can be used instead.
By using this technique, you can generate a password and not have to use it each and every time.
You can also reuse your machine’s generated key-pair for other SSH services.
A private and public key is created locally on your machine, and the private key always stays on your own machine. The public key can then be shared with services such as GitHub.
Get the Maximum Length of a Concatenated String with Unique Characters in Python
The problem
Given an array of strings
arr. Stringsis a concatenation of a sub-sequence ofarrwhich have unique characters.Return the maximum possible length of
s.Example test-cases
Example 1:
Input: arr = ["un","iq","ue"] Output: 4 Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique". Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"] Output: 6 Explanation: Possible solutions are "chaers" and "acters".
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"] Output: 26
Constraints
1 <= arr.length <= 161 <= arr[i].length <= 26arr[i]contains only lower case English letters.
How to write the code
def maxLength(arr: List[str]) -> int: result = [float('-inf')] unique_char("", arr, 0, result) if not result[0] == float('-inf'): return result[0] return 0 def unique_char(cur, arr, index, result): # End of the array if index == len(arr): return # Iterating from the current word to the end of the array for index in range(index,len(arr)): # If current word + next word have all unique characters if len(set(cur + arr[index])) == len(list(cur + arr[index])): # Compare the actual lenth with the previous max result[0] = max(result[0],len(cur + arr[index])) # Make a new call with concatenate words unique_char(cur + arr[index], arr, index + 1,result)Apache Kafka’s Role in Big Data Streaming Analytics
The world of Big Data started out as a way of storing and querying obscene amounts of information by comparison to what yesteryears were able to achieve. However, most value in said data is primarily found in the real time or streaming information that is presented as it first enters the system. As data gets old, it also gets stale and less useful to many business systems.
Streaming analytics platforms have come a long way with numerous open source projects offering advanced products such as Flink, Spark Streaming, Samza and Storm; which are all at the forefront of the arena in their respective strengths.
Mitigating Risks with Software Development Outsourcing
In the Oxford Dictionary, the term “outsourcing” is simply defined as obtaining goods or services by contract from an outside supplier (OxfordDictionaries.com, n.d.).
When it comes to software development, the same is true, with many companies opting to use economically cheaper labour to extend or swap out their workforce in order to enhance their endeavours and reduce costs across the board.
Countries such as India, Russia, China and Mexico have a lower Cost of Living (Numbeo.com, 2017) and are among the most common places to outsource to (Lisa DiCarlo, 2003).
The Primary Data Types in Java
In Java there are eight basic data types; which are:
byte,short,int,long,float,double,booleanandchar.It could realistically be said that a Java developer’s time is primarily spent using these particular variable types to store, retrieve and manipulate data to complete most programming tasks. However, there are many times that these primitive variables don’t quite suffice and additional data types need to be explored and used instead.
Comparing Objects in Java
TLDR;
When to use
==in JavaWhen comparing two operands. It is used to check whether two operands are equal or not.
It’s best to only use it when working with primitive data types, such asint,float,charor sometimes evenBooleansWhen to use
equals()in JavaThis method is best used when comparing
Stringtypes.When to use
compareTo()in JavaIt is good to use
compareTowhen you need to compare twoStringliterals.Overloading Operators in Java
As with many programming languages such as C, C++ and C# (known commonly as the C family), it is possible to “overload methods” (sometimes called functions if not used in classes, such as C) in order to take a different amount of parameters so that they can be used in multiple scenarios with similar internals.
As Java is derived from the C style of languages (C family), it too can perform Method Overloading.
uncaught typeerror: $ is not a function
The
dollar-sign($) in Javascript has for many years now been associated with jQuery.When you see this error:
“uncaught typeerror: $ is not a function”
It almost always means that a jQuery piece of code is being run before the jQuery library has been initialised and loaded.
Oftentimes, your code will wait for jQuery to load before continuing any processing, this is almost always done as follows:
$(document).ready(function(){ // jQuery code is in here });However, it’s not uncommon to get an “TypeError: $ is not a function” error in response.
How to get the last element of a list in Python
Let’s say that you have a Python list with the following 5 foods:
foods = ["pizza", "pasta", "steak", "chicken", "olives"]How do we go about getting the last item?
Option 1
It’s actually really easy, you can select the index item by it’s total length minus one.
last_item = foods[len(foods)-1] # "olives"Option 2
Python has some really fantastic functionality around making your life easier. One of those such things is the ability to use
slices.How to embed a web server in your Python3 app
This is not the first time that I created a Python3 application that spat out some output and required access to it via an HTTP server.
While there are numerous ways to achieve this, a really simple way is to embed an HTTP server directly in your Python3 application, and have it serve your output directly when called.
A sample web server in Python
from http.server import HTTPServer, BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() # Add additional output here self.wfile.write(b'Hello, world!') httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler) httpd.serve_forever()How to get the Range Sum of Binary Search Tree using Java
Given the
rootnode of a binary search tree, return the sum of values of all nodes with value betweenLandR(inclusive).The binary search tree is guaranteed to have unique values.
Examples
Example1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32Example2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23Our solution in Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int rangeSumBST(TreeNode root, int L, int R) { //output variable int output = 0; // Create a stack Stack<TreeNode> stack = new Stack(); // Add the root node stack.push(root); // loop through each element while (!stack.isEmpty()) { // remove last item from stack TreeNode node = stack.pop(); // if the node exists if (node != null) { // incrememnt output counts if (L <= node.val && node.val <= R) output += node.val; // push if left if (L < node.val) stack.push(node.left); // push if right if (node.val < R) stack.push(node.right); } } // return our count return output; } }How to duplicate zeros in place using Python
Given a fixed length array
arrof integers, duplicate each occurrence of zero, shifting the remaining elements to the right.Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
Examples
Example1:
Input: [1,0,2,3,0,4,5,0] Output: null Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]Example2:
Input: [1,2,3] Output: null Explanation: After calling your function, the input array is modified to: [1,2,3]Writing the code
# declare our function def duplicateZeros(arr): # create our incrementor i = 0 # loop through all dynamic elements while i < len(arr)-1: # if the character is a zero if arr[i]==0: # remove the last item from the array arr.pop() # insert a zero in front of current element arr.insert(i+1, 0) # move one place forward i += 1 # increment to the next character i += 1A Quick Introduction to Asyncio in Python3
Python has never been the best at doing multiple things at the same time.
While there are ways to mostly resolve this, such as using the Multiprocessing library, it always seems a bit make-shift to me.
So many other languages have fantastic ways of resolving these types of issues, and Python now has an
Asyncway too!Introducing Asyncio
Asyncio is a library to write concurrent code using the async/await syntax.
How to replace newlines with commas in CLI
If you need to replace all newline characters with a comma, or perhaps some other delimiter, then using the build-in
trutility will work very well for you.Possible use-cases for this is if you need to transport a configuration file with multiple lines into a single input field, or store the file’s contents within an environment variable.
My personal use-case was to store an
~/.aws/credentialsfile in an environment variable.How to make a disk cache using PHP
If you have a busy PHP driven website and don’t want to make constant queries to the database for each user that will see the same data, then you can easily resolve this problem by letting the first of these visitors generate a cache for the consecutive visitors. This technique is similar to other PHP performance optimizations like using a PHP mail class or sending data from JavaScript to PHP.
Letting this cache last for a few minutes allows your database to not get overloaded and allows for a much faster website experience as well as a much cheaper hosting bill for you at the end of the month.
How to remove files without a certain extension?
You have a directory with a lot of files, and you want to delete only the files that don’t match a specific extension.
This is a simple task when using the
findcommand-line utility.Delete a single extension
You can delete all files that do not have the following
*.txtextension:find . -type f ! -name "*.txt" -exec rm {} \;Delete multiple extensions
You can delete all files that do not have the following
*.txtor*.exeextensions.How to debug an Apache 404 error
So you are getting an error
404or perhaps even worse, a500!The error in your Apache2 logs looks something like this:
***.162.245.*** - - [03/Apr/2020:12:49:50 +0000] "GET /robots.txt HTTP/1.1" 404 89670 "-" "Mozilla/5.0 (compatible; SomeUserAgent/2.1; +https://example.com)"In a perfect world, you’d only have a single site/domain on this host, so will know that the
robots.txtfile would reside in the Apache root serving directory.However, I just happen to (as you?) have a ton of VirtualHosts on this machine, so am not sure which
robots.txtfile is missing..How to Reorder Data in Log Files using Python
Let’s say that you have an array or a list, or
logs.Each of these logs is a space-delimited string of words.
For example:
logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]The task is to reorder these logs and return them in the following acceptance criteria:
- The first entry (identifier) of each log is ignored but still returned
- The letter-logs are returned before the digit-logs
- The identifier is only used to sort these there is a tie
How to analyse the problem
At first glance, this appears to be something that could be easily solved by looping through each log entry and if the second part of the entry is a
stringtype, then adding it to atempAlist, otherwise adding it to atempBlist.Another WTF Javascript Moment
Javascript is a powerful language, but sometimes it doesn’t always do what you expect it to.
Take the following expression for example. It’s a simple
ifstatement that checks to see iftrueand then runs the code within the block.Running the code results in the block being executed, however, when we directly compare the statement’s comparison against a false value, we can see that it is in fact, not actually true.
How to Bring Back GROUP BY in MySQL
If you are suddenly not able to perform
GROUP BYstatements as you used to after a MySQL/MariaDB version update, then you will have noticed the change forced upon you.You can re-enable the previous
GROUP BYbehaviour by editing your/etc/mysql/my.cnfand adding in the following line below the[mysqld]section:[mysqld] sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"This will allow you to
GROUP BYwithout having to return all those specific columns as well.How to implement a Queue using Stacks in Python
A common programming interview question, and for a change, one that you will actually be able to use in the job, is that of implementing a Queue by means of using Stacks in Python.
The 5 common operations of a Queue
- Instantiation
- push(val)
- pop()
- peek()
- empty()
What each operation does
Instantiationis the Queue’s storage object that will be used.class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack = []push(val)is the way to add data to the Queue.Find positions of largest groups of characters in a String with Python
The question
Take a string
Sof lowercase letters.These letters form consecutive groupings of like characters.
Find groups with 3 or more like characters and return a list of lists of starting and ending index for each character group.
Elaboration and examples
If we show an example, we could say
S = "abbcccdeffffy".This string has 2 groups,
candfwho’s consecutive characters are of 3 or more.How to make Git “forget” about a file that was tracked but is now in .gitignore?
You can ignore certain files and folders from being committed to Git by means of including a
.gitignorefile.Unfortunately, you may have forgotten to include certain entries and now find that there are files and/or folders that git will want to commit.
To start with, you should make sure that the relative path to the file or folder is included in your
.gitignorefile.Then run one of the below commands.
How to Purge the BinLog for MySQL and MariaDB
If you see lots of disk space quickly disappearing on your MySQL or MariaDB server, then you may want to look into the
BinLogdirectory, it is located at/var/log/mysql/.In my case I saw this:
usr@server-1:/var/log/mysql# ll total 5571044 drwxr-s--- 2 x x 4096 Mar 25 18:18 ./ drwxrwxr-x 12 x x 4096 Mar 25 05:25 ../ -rw-rw---- 1 x x 104857748 Mar 23 09:29 mariadb-bin.000301 -rw-rw---- 1 x x 104859422 Mar 23 10:07 mariadb-bin.000302 -rw-rw---- 1 x x 104857708 Mar 23 11:10 mariadb-bin.000303 -rw-rw---- 1 x x 104860750 Mar 23 12:29 mariadb-bin.000304 ...truncated... -rw-rw---- 1 x x 104857809 Mar 25 16:46 mariadb-bin.000352 -rw-rw---- 1 x x 104858231 Mar 25 17:17 mariadb-bin.000353 -rw-rw---- 1 x x 104857709 Mar 25 18:18 mariadb-bin.000354 -rw-rw---- 1 x x 24833125 Mar 25 18:32 mariadb-bin.000355 -rw-rw---- 1 x x 1870 Mar 25 18:18 mariadb-bin.indexI looked to see how much space this was all taking:
How to Measure Execution Time in Google Colab
Google Colab is a fantastic environment to write Python code using Jupyter Notebooks, hosted for free by Google.
If you’ve ever used Jupyter Notebooks before, it is the same principle, you write Python code in a cell and you are able to execute each cell as you require.
Measure Execution Time
But how would you measure the time each cell takes to execute?
How to fake a User Agent in Python
A
User-Agentis a bunch of text that is sent with every HTTP and HTTPS request. The server processing this request is able to determine what type of device and browser has made the request.Often times servers use this parameter to restrict access to the resource.
However, it’s easy to fake a User-Agent when using Python to make HTTP and HTTPS requests.
Using Requests Library
import requests user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36' response = requests.get('https://andrewodendaal.com', headers={'User-Agent': user_agent}) html = response.content print(response.content)Using URLLib Library
import urllib.request user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36' request = urllib.request.Request('https://andrewodendaal.com', headers={'User-Agent': user_agent}) response = urllib.request.urlopen(request) html = response.read()How to Delete from a Table where rows match in Another Table – MySQL
So you have a table where you want to delete a bunch of rows, based on a particular column being matched in another table.
This is easily achievable with MySQL.
DELETE FROM TABLE1 WHERE domain IN ( SELECT domain FROM TABLE2 )The above SQL will delete all rows in
TABLE1that are found inTABLE2.But what if we need to limit which records are returned from
TABLE2?That’s simple too. All we need to do is add a traditional
WHEREclause to our select statement.REPLACE INTO instead of INSERT INTO – MySQL
There are many occasions where you need to
INSERTa record into a MySQL database table, but the record already exists.INSERT INTO queue_domains (domain) VALUES('statvoo.com')This will result in a
Duplicate entry 'statvoo.com' for key 'domain'errorA nice and simple way to resolve this is to use
REPLACE INTOinstead.This will look to see if the item already exists and will simply replace it.
This is faster than doing a
SELECTfollowed by anINSERT.Read the bottom n lines of a file in Python
Using Operating System Commands in Python
Use the Linux/Mac
tailcommand to provide the data:line = subprocess.check_output(['tail', '-1', somefile.txt])Creating a Python Only Script
Read the whole file into memory and only print out the last line/s:
with open('somefile.txt', 'r') as f: lines = f.read().splitlines() last_line = lines[-1] print(last_line)How to Format a Number as a Currency in Javascript
There are quite a few ways to format a number as a currency value in Javascript. This is a common task when building web applications, similar to other string manipulations like removing hash from window location or checking if a string contains a substring.
Doing it yourself
The easiest of which is that of using the built-in
toFixed()method.Often times you will either have a string, integer or floating-point number (/double) and will need to output a value that looks like a currency.
How to Change the Timezone on Ubuntu Server
If you’ve ever typed
dateinto your Ubuntu Server and seen a different time or timezone appear than you expected, then it probably means that this tutorial is for you.Check current timezone
Start by checking what data is returned using the following command:
timedatectlIn my case, I wanted to make sure my server’s time was in UTC, London. However, it was reported as being in Berlin.
$ timedatectl Local time: Fri 2020-03-20 11:08:41 CET Universal time: Fri 2020-03-20 10:08:41 UTC RTC time: Fri 2020-03-20 10:08:42 Time zone: Europe/Berlin (CET, +0100) System clock synchronized: yes systemd-timesyncd.service active: yes RTC in local TZ: noUbuntu uses symbolic files to link configurations for timezones.
How to make a Python script Pip-installable
As Python developers, we’ve all used
pipto install applications, but speaking to other Python developers, it’s not always clear how to make your own application/scriptpip-installable.If you want to automatically publish your Python to PyPi, check out
makepipautomation tip
Steps involved
- Create a python script, or application
- Add and configure a setup file
- Build your new Pip Package Locally
- Upload them both to the Python Package Index (PyPi)
So let’s run through these 4 steps to get you going.
How to Host an AngularJS site on AWS S3
AngularJS is a Javascript Framework that allows you to create dynamic front-end web applications easily.
I have traditionally packaged these applications through NodeJS, and Grunt (or Gulp) in particular.
Once it needs to be hosted for the whole world to see, I always used to push the static folder up to an Apache2 or Nginx Linux web server.
There’s really not a massive need for this though, as it’s easily possible to AngularJS applications completely serverless using a combination of AWS S3 and Cloudflare.
How to send emails using Python and AWS SES SMTP
Sending emails using Python and AWS’ SES service is really easy. They provide an SMTP server that you can authenticate against and send email programmatically from your python scripts.
There is a wonderfully simple Python package called
emailsI like to use for this purpose.If you’re not running a Python Virtual Environment, then start by getting started here.
Otherwise, continue reading!
Getting AWS SES SMTP Setup
In order to start sending emails using AWS SES, and the SMTP server in particular, you will need to:
Generate a random number between two numbers in JavaScript
If you need to generate a random number between two numbers in JavaScript, then you are in the right place! Here you will learn javascript random number generation.
We can easily do this by using a combination of built-in
Mathfunctions.Javascript Random Number from Math.random()
Let’s start by using
Math.random()to generate a random number. Now we will take that and multiply it bymax - min + 1.Why Password Managers are Not the Solution
Why a Password Manager?
Password managers exist for two main reasons.
Firstly, to generate strong passwords and secondly so that you don’t end up using the same password on all your websites or apps that you frequent.
On the surface, that sounds like a pretty good idea.
Imagine you use the same password for a number of websites, then one of those websites gets hacked. The hackers will now try the same credentials on a range of sites. Oftentimes they will be able to successfully login because people don’t protect their stuff more than this.
Read the top n lines of a file in Python
Sometimes you may need to read the top
nlines of a file using Python.We start by opening the file for reading and then using a list comprehension we iterate through the range of lines we want to return:
N = 10 filename = "file.txt" with open(filename) as myfile: head = [next(myfile) for x in range(N)] print(head)Another way you can do this is by looping through each line individually:
How Fast is your Website?
I operate a bunch of different sites and have done for many years now.
Some of them get quite a lot of traffic and require a high level of uptime.
To monitor the uptime of these sites, I use various tools to alert me when a site is unreachable, when a specific resource is returning an unexpected status code, or if one of the database heavy pages starts taking a while to respond to requests.
How to Git Reset a Single File
It’s very easy to reset files that have not yet been committed to git.
Reset a single file
git reset <filename>You can also specify the filename as the path to the file, like so:
git reset ./the/actual/relatvive/path/with/filename.extThis will checkout the file from HEAD.
It is important to note that should you have a file that is the same name as a branch, you will need to rather run the following command:
Introducing Variables in Golang
Golang comes with a decent offering around variables that you can use to store, retrieve and manipulate information.
A variable is defined with the
varkeyword followed by the name of the variable, the type and then the assignment itself.How to name a variable in Golang
Variable names must:
- Start with a letter
- May contain letters, numbers or the underscore
_character.
Variable names that start with numbers or special characters are not allowed.
Golang cannot convert (type string) to type int
Every language has it’s ways of converting data types. One of the most common data types to convert between is that of strings (
string) and integers (int).If you’ve ever tried to do this in Golang, you would know that’s it isn’t all that simple at first.
The easiest way to convert between String and Integers in Golang is as follows:
String to Integer
My go-to option to resolve this problem would be with the
strconvmodule.Learn Golang as a Python Developer
Learning Go or Golang as a Python developer, programmer or software engineer is easier than you think.
While there are quite a lot of things to learn and get familiar with, there are many benefits and many common characteristics.
Why learn Go as a Python developer
I find Python to be a very powerful and useful programming language, having used it on a wide range of projects for an even wider range of tasks. From Platform Engineering automation to Machine Learning and Artificial Intelligence, to building User Interfaces and creating APIs as well as building entire websites and web applications. Python has served me well and will continue to do so.
Remove Special Characters in a String using Bash
Programming languages provide the ability to remove special characters from a string quite easily.
Sometimes you need to also do this from your command-line using Bash.
Let’s say we have a bash variable called
USER_EMAILand we want to remove any periods, underscores, dashes and the@symbol, how would we go about this?We could pipe our variable to a useful command called
tr(which is thetranslate or delete characterstool) and strip these specifics before pushing the output back to a new bash variable.Get the Amount of Days Between Two Dates in Python
Let’s say that you have two dates:
"2019-01-29" "2019-06-30"How would you create a function that would return the number of days between these two dates?
Introducing the Datetime Package
Python comes with a built-in library called
datetime.We start by importing the
datemodule.from datetime import dateWith this date module, we have access to an object format of the
datetype.Writing our Function
Next, we should write our function that takes in two dates and returns the number of days between them.
How to Always run Python 3 from Bash
Given a directory that contains:
| |- app.py |- requirements.txt |- ... |- <- other-files -> |- ...We can create a
runme.shfile to always make sure we are runningpython 3.Create a shell script
Create a file called
runme.shand put the following code in:python -c 'import sys; exit(1) if sys.version_info.major < 3 else exit(0)' if [[ $? == 0 ]]; then [ ! -d "venv" ] && virtualenv -p python venv . venv/bin/activate pip install -r requirements.txt else [ ! -d "venv" ] && virtualenv -p python3 venv . venv/bin/activate pip3 install -r requirements.txt fi python app.pyNow instead of running
python app.pyorpython3 app.py, you can simply runsh runme.sh.How to Run the Kubernetes Dashboard Locally
Kubernetes comes with a pretty nice dashboard to view
clusters,worker groups,nodesandpods. As well as a ton of other useful things.This tutorial presumes that you already have a Kubernetes cluster setup and running and have access to it through
kubectlin your command-line.Steps to run Kubernetes Dashboard
Start by downloading the
metrics-serverand applying it to yourkubectlconfig.DOWNLOAD_URL=$(curl -Ls "https://api.github.com/repos/kubernetes-sigs/metrics-server/releases/latest" | jq -r .tarball_url) DOWNLOAD_VERSION=$(grep -o '[^/v]*$' <<< $DOWNLOAD_URL) curl -Ls $DOWNLOAD_URL -o metrics-server-$DOWNLOAD_VERSION.tar.gz mkdir metrics-server-$DOWNLOAD_VERSION tar -xzf metrics-server-$DOWNLOAD_VERSION.tar.gz --directory metrics-server-$DOWNLOAD_VERSION --strip-components 1 kubectl apply -f metrics-server-$DOWNLOAD_VERSION/deploy/1.8+/Next, we will start setting up the
metrics-server, ready for action!How to tell if a year is a Leap Year in Python
Given that we are in a leap year this year (2020), it would be nice to know how to programmatically calculate this.
Luckily, this is a repeatable pattern that we can write some code for.
So what is a leap year?
A
leap yearis a year that has 29 days in the month of February.Astronomical years have a quarter of a day more than our calendar years that we follow, so to make sure this matches up continually, our calendar introduces an additional day every 4 years.
How to Reverse a Linked List in Python
It’s important to know about data types and one that comes up fairly regularly is that of Linked Lists.
Let’s write the following base code to create a Linked List.
# Defintion of a single Node class Node: # takes input data and next node def __init__(self, data = None, next=None): self.data = data self.next = next # Definition of a Linked List class LinkedList: def __init__(self): self.head = None # Insert a node into our Linked List def insert(self, data): newNode = Node(data) if(self.head): current = self.head while(current.next): current = current.next current.next = newNode else: self.head = newNode # Print our Linked List so we can see how it looks def render(self): current = self.head while(current): print(current.data) current = current.nextNow that we have a base class, let’s insert a couple of nodes and print it out to see what we are working with:
The Docker Quickstart Guide for Developers
This Docker Quickstart Guide for Developers aims to get developers familiar with Docker as quickly as possible.
Providing you with the knowledge to be able to use Docker in your personal and professional projects.
What is Docker?
Docker is a tool written in Golang that provides the ability to run applications within things called containers.
It removes the age-old “works on my machine” problems that plagued many software developers and testers lives.
How to Follow Redirects with cURL for CLI or PHP
Let’s take a really common example. Say we want to follow redirects with cURL for
google.com. It is common to curl follow redirect a URL.Follow Redirects with cURL in the CommandLine
If you navigate directly to google in the command-line using
curl, you will be taken to a301 redirectURL.curl google.com#<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> #<TITLE>301 Moved</TITLE></HEAD><BODY> #<H1>301 Moved</H1> #The document has moved #<A HREF="http://www.google.com/">here</A>. #</BODY></HTML>This makes sure that you follow the proper canonical URL as set by the particular website in question.
How to tell if a String contains a Substring in Javascript
Javascript comes with some pretty good support for determining if a string contains a substring.
There is the newer
includesfunction which was introduced in ES2015 which allows you to tell if a string contains a substring. This function returns a boolean value oftrueorfalse.'our example string'.includes('example') // returns trueAlternatively, if you need to either:
- Have support for older versions of Javascript
- Need to not only know if a string contains a substring, but also it’s position within the string..
Then
indexOfis a better match for you.How to package a Python app (pip) for PyPi
In this tutorial, we will create a Python application that can be installed directly from
pipthat will show the 10 latest blog posts from this website (the one you are reading this on!).If you just want to avoid all of this hard work and publish a python script directly, you can always make use of my
makepippackage right from the command line.Getting started
Make sure you have registered at Pypy and have an account, we will need this to upload our package once we’re done.
How to find the longest Palindrome in a String using Python
This occasionally comes up during coding interviews and is actually quite a decent way to test someone’s aptitude of moving back and forth on a string to determine if and where palindromes exist.
If we simply said: “return a boolean if a string is a palindrome”, then threw a couple tests cases at the function, we would expect the developer to loop through the first half of a string while comparing the second half, if it matched all the way to the central pivot, then “yes, the string is a palindrome”.
How to write Anonymous Functions in Javascript
There is a lot of power in Javascript syntax. One of those powerful things is that of Javascript Anonymous Functions.
But what is an Anonymous Function in Javascript?
It is a function that does not have a name or one that has been hidden out of scope around its creation.
A common use of a Javascript Anonymous Function is to guarantee that the same variable names or function names are not already used within the same document.
How to use Docker to test any Linux distribution locally
I often need to test a specific Linux binary or make sure something works as expected from
yum installorapt install.To do this, it’s common to have a virtual machine lying around, or even a VPS that you can just quickly log into.
Things are a bit easier and quicker if you use Docker.
Let’s run two tests, the first one to get going with Ubuntu, and the second to get going with Centos.
How to get the Maximum Depth of a Binary Tree in Python
Let’s say that you have a binary tree and we needed to know it’s maximum depth.
Binary tree input data
[3,9,20,null,null,15,7]could be visualised as follows:3 / \ 9 20 / \ 15 7In the above example, the depth would be 3. As there are 3 levels.
How would we write some Python code to work this out?
As usual, a TreeNode is defined as follows:
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = NoneAs we need to loop through the same data types, this would be a perfect time to practice some recursion!
What is Fizz Buzz?
Fizz buzz is a common programming interview question.
The problem statement usually reads something like this:
Write a short program that prints each number from 1 to 100 on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
How to Deploy a Helm “Hello World” app onto Kubernetes
We will create a simple Hello World static HTTP Service using Helm, package it and release it to an AWS EKS Cluster.
This tutorial expects you to have
kubectlas well ashelminstalled on your computer.Build our Docker image
Create a file called
Dockerfileand place the below into it:FROM busybox ADD index.html /www/index.html EXPOSE 8008 CMD httpd -p 8008 -h /www; tail -f /dev/nullNow we need to create our
index.htmlfile.How to write a Quicksort Algorithm in Python
While there are libraries available for all programming languages that offer abilities to sort list, arrays and collections, it is important to know how this is achieved.
Learning how to write a quicksort algorithm yourself gives the ability to better understand the programming language of your choice and how to optimise code where possible.
Today we will explore writing a quicksort algorithm in the Python programming language.
Let’s start by defining a list of integers that are clearly not in order:
How to Reverse a String or List using Python
Python comes with the power of
slicing.Let’s try it with a
String:>>> example1 = 'hello world' >>> example1[::-1] 'dlrow olleh'Now let’s try the same with a
List:>>> example2 = ['h','e','l','l','o',' ','w','o','r','l','d'] >>> example2[::-1] ['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']As we can see by passing in the third argument to our slice of
-1, we are able to reverse the return value.How to get the IP address in Python
Python exposes a
socketlibrary that allows us to perform networking tasks such as getting the IP Address as well as getting the Hostname of our system.import socket try: host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print(f"Hostname: {host_name}") print(f"IP : {host_ip}") except: print("Could not get the IP Address or Hostname")The above code imports the socket library and then runs a safe block of code.
We need to first get the hostname and then use that to get the IP Address.
How to Reverse a Binary Tree in Python
Reversing a Binary Treeis a common programming interview question.By learning how to Reverse a Binary Tree in Python, you are working towards fundamental data structure algorithms commonly found in Computer Science degrees and across the industry.
If we take a look at the following Data Tree Image, we will notice a few common points.
Firstly, a
binary treesimply means a tree that contains between 1 and 2 child nodes.[Solved] Unable to Detach AWS Network Interface
You do not have permission to access the specified resource.If you are seeing this error appears up when trying to delete or detach a Network Interface within AWS, then you need to read what the description column says, find that item and then delete that first.
We can see in this instance, we need to first delete an ELB starting with ID
a4e6efd6.Head over to the Load Balancers tab and search for that ELB:
How to delete a file in Python
A quick solution in Python
import os os.remove("filename.txt")The above code will delete a file in Python, it will not however delete a directory, or a directory containing files. For this we will need to explore a bit more..
Check file exists before deleting
First check if the file exists before deleting it:
import os if os.path.exists("filename.txt"): os.remove("filename.txt") else: print("The file doesn't exist")Delete a directory/folder
Sometimes you may want to delete an entire folder as well:
How to safely parse JSON in Javascript
JSONstands for Javascript Object Notation and has become wildly popular to transport and store data between application, databases and more.However, it is not always obvious that a piece of data your application is trying to use may be of type JSON, or be correctly sanitised.
Let’s take a simple Javascript function as follows:
function getNameFromJSONString(jsonString) { // Dangerous! json = JSON.parse(jsonString); // Dangerous again! return json.name; }What the above function does is take in a string which it believes is a stringified/serialised JSON (perhaps stored in a database), parse it back to a Javascript Object and then return an attribute called
name.Check if an HTML Checkbox is checked using Javascript
While processing forms in web development, it’s a common requirement to be able to tell if a checkbox has been checked or not.
It’s not immediately obvious though. Let’s dispell this and provide some ways to
check if a checkbox is checkedusing Javascript.First, we need an HTML checkbox to play around with.
<input type="checkbox" class="myCheckbox" />Using Javascript
Using regular Javascript, we can tell if it is checked by using the following Javascript:
How to Push Docker Images to AWS ECR
Docker images are usually stored on Docker Hub, but AWS’s Elastic Container Registry can also be used. It’s a great solution and this post teaches you how to push Docker images to AWS’ Elastic Container Registry (ECR).
Create a Repository
Let’s start by using the
aws-clito create a repository.aws ecr create-repository --repository-name mynameThis command successfully creates a repository and outputs the following JSON:
How to monitor Network Traffic on Linux
There is a fantastic tool to see and monitor Bandwidth and Network Traffic on Linux.
It’s called
bmonand it works out of the box.How to Setup and Use
On Ubuntu
apt-get install bmon, or in newer versions, you can also just sayapt install bmon.On Centos
yum install bmon.Once you have it installed, you can start the monitor by running
bmonfrom the command-line.You will be presented with multiple network interfaces (NICs).
How to Merge Javascript Objects
A Javascript Object – now just called
JSON– is a collection of values and properties stored as a map.How would you merge two or more Javascript objects together thought?
In ECMAScript 2018, the Object
Spreadoperator will do the trick for you in no time, let’s try it out.var jso1 = { "name": "John", "colour": "green", }; var jso2 = { "name": "Andrew", "symbol": "arrow", }; var merged = {...jso1, ...jso2};The result of this would be to combine all the elements and override any newer ones where applicable.
When to use Pip3 instead of Pip in Python
If you have multiple versions of Python installed on a system, such as both Python 2.7 and Python 3.6+. Then
pipwill often refer to the Python2 bin, whilepip3will point to the Python3 bin.You can easily tell what your own setup is by running the following commands in a terminal window / command-line.
$ which pip$ which pip3 /usr/local/bin/pip3It is also useful to know what version of Python you have on your system and where it is, as Pip is always coupled with it.
How to use Screen on Linux
Screenon Linux is a popular command-line program that lets you multiplex between interactive shells.What that means is, you can use
screento save and restore running of commands.Screenin actionThe best way to test this out is to SSH into a server.
sh [email protected] user@server:~#At this stage, you can execute
man screento learn all the commands available to you.You can issue a
screen -listto show all screen sessions that may already be open.Transfer a domain from Namecheap
Namecheap is a pretty good registrar. As its name says, yes, it is usually pretty cheap. I would also like to point out that I personally have nothing bad to say about Namecheap and that their service is overall pretty positive. But as with most things, there occasionally comes time to make a change. This change happens to be to transfer a domain hosted at Namecheap.
Recently I have been moving most of my domains to Cloudflare, who don’t currently offer registrations but do offer to take the domains once registered.
How to Package a Python App using Nuitka
Learn how to package a Python app in this tutorial.
For the most part, once you’ve written your Python code, you simply deploy it to a server, install the environment, grab the dependencies and you’re done.
However, there are times when you may want to provide your app to someone else and don’t want the hassle of getting them setup with all the training around making sure they have Python on their machine and can run your app.
Introduction to NPM
What is NPM?
NPMstands for Node Package Manager, and is the default way to extend your Node applications.There are an absolute ton of packages available to install and use immediately, making NPM wildly popular for software developers.
What is Node?
Node.js, or often simply justNode, is a Javascript runtime environment that allows Javascript code to be executed outside of the web browser.It first came about in 2009 when the creator (Ryan Dahl) took Google’s V8 Javascript Engine which powers its Chrome browser, and repurposed it. Adding in additional logic allowing it to be used independently to execute Javascript on the server.
How to create a Symbolic Link on Linux / Mac
A symbolic link – or often just
sym-link– is a pointer or shortcut to where the actual file lives on a filesystem. What does it take to create a symbolic link?The
lncommand actually describes it pretty well:"Make links between files"
The manual
Why would I need a Symbolic Link?
When should you create a symbolic linkis a question I am often asked.While creating a symbolic link can be really useful, it’s not often understood when or why we even do this.
Non-interactive git clone (ssh fingerprint prompt)
If you have ever been in the annoying situation where you had to run
git clonefrom a server that you did not have interactive access to, such as a continuous integration/deployment box or other. Then you may have run into the dreadedAre you sure you want to continue connecting (yes/no)?dialogue.Usually, at this stage, you would be stuck, as you need a way to tell it
yes, but there’s no input!When your Python code is much faster with PyPy
Python is a very powerful language, there are so many libraries available for it.
However, many developers will complain about its speed by comparison to certain other languages, for example, C or C++. If you’re new to Python, you might want to first check out how to learn Python programming quickly.
This is because Python is an interpreted language by design, as opposed to being compiled. Meaning that each time it executes, the instructions need to be converted right there on the spot, making for slower overall execution times. When working with Python, it’s also important to know how to setup and use the Python virtual environment for better dependency management.
What it takes to be a Platform Engineer in 2020
Platform Engineering is something that grew out of a mix of what software developers and sysadmins had been doing for years.
The only real difference is that most software these days either lives somewhere in some cloud or various services that support it do. Meaning that someone needs to design it, scale it and support it. This is not traditionally within the scope of a software engineer’s day job and requires a range of specialisms oftentimes not found with a developer’s direct focus.
Introduction to PIP – Python Package Manager
Python comes with a fully equipped package manager called
PIP– which stands for thePython Package Manager.PIP gives your python applications access to thousands of popular libraries, packages or modules for free.
What does PIP mean?
PIP is actually a recursive acronym which stands for:
- PIP Installs Python
- PIP Installs Packages
Before Continuing
As usual, it is recommended to do everything in a Python Virtual Environment. Making sure that you are running Python3 is also important, as Python2 has reached End of Life, and this is a welcome thing!
How to build a website quickly using PHP
PHP is a powerful scripting language created for the web.
It has come a long way since it’s initial inception in 1994.
It was originally created to build websites quickly and easily and has become a lot more than that.
While many developers and companies use PHP along with extensive and oftentimes heavy frameworks, there is no reason that you have to do that; you can build websites quickly and very easily by making use of many standard PHP functions.
How to replace all occurrences of a string in Javascript
I have pretty much resigned myself to the fact that in Javascript, there are really only two ways to do a proper search and replace.
Firstly, we need a base string to start manipulating, so let’s create our test subject:
var ourString = "This is a great string and we love it";So now the options are as follows,
replace,regular expression replaceandsplit/join.Javascript Replace
ourString.replace(" ", "-") "This-is a great string and we love it"As we can see with this method, it only replaces single occurrences in the string, which may be what you are trying to achieve, but it certainly wasn’t for this case!
How to exit Vim
If only I had a dollar for every time I saw someone sitting at their computer, trying for the life of them to exit vim
To save and exit; press
:followed byxand then hitEnterto save and exit the file in vim.TLDR;
Vimor sometimes justviis a command-line (cli) application that lets you edit documents. It’s massively popular and my personal go-to editor when I’m on a Linux box. Particularly if I’m editing remote files on a webserver or other.How to Setup and Use the Python Virtual Environment
Python is a fantastic language that continues to help so many businesses and individuals. It offers readable syntax to get started, yet extensive amounts of control and flexibility to move into the more advanced areas of software engineering. Python the number one choice for many because it is packed with the power of unparalleled libraries, it recommended to run them through a python virtual environment.
Conventionally, running a python script from the terminal is as simple as calling it and passing in the script needed to be executed.
Introducing the Hetzner Cloud
I could honestly not tell you how many hosting providers I’ve tried over the past 15 years. Probably more than 30, 40… Easily!
Today I would like to introduce you to the Hetzner Cloud. No, I do not work for Hetzner, or have any affiliation to them whatsoever, this is purely a sharing exercise as I have noticed that when I speak of them in my professional capacity, most colleagues don’t know about them. Not sure why, as most people know about Digital Ocean and a few others, but with the same token, these people don’t tend to know about Linode, Vultr, OVH, and some others. Most people within my profession only know and care about the big players, such as AWS, GCP and Azure.
Multiprocessing in Python3
import multiprocessing def runner(k): print(k) processes = [] for i in range(10): p = multiprocessing.Process(target=runner, args=(i,)) processes.append(p) p.start() for j in range(len(processes)): processes[j].join()Now that you have the code; let’s explain:
Import the
multiprocessinglibraryimport multiprocessingDefine the function that will run each time a process is executed
def runner(k): print(k)Keep track of all the processes
processes = []How many processes do you want to run?
for i in range(10):Send some arguments to the running function
How to Install MongoDB on Mac
You can use Homebrew to install MongoDB on a Mac.
For ages you were able to simply do:
brew install mongodb, but more recently, that has stopped working as it was removed from homebrew-core. Now, you need to do it as follows:brew services stop mongodb brew uninstall mongodb brew tap mongodb/brew brew install mongodb-community brew services start mongodb-communityYou can read more about it here if you’d like.
The Best Note Taking Apps
We’re all using a Note Taking App these days, they’re incredibly useful and come jam packed with loads of features. But which ones shine out from the rest and which should you use in 2019?
Among the many tens to hundreds of possible candidates, I have chosen the seemingly obvious top 5 to explore in this post. These were initially chosen from my own experience having used many over the past few years to find the ultimate single Note Taking app to conquer all others.
How to Delete large amount of files in directory
So you have clearly got a very large amount of files!
If you issue the conventional
rm -rf *within the directory, you will get an error-bash: /bin/rm: Argument list too long.You can still easily remove these files, just make sure to use the
findcommand instead!Solution:
find . -type f -deleteHow to Merge multiple files, removing duplicate values
If you have multiple files and you want to remove duplicate values from, while creating a single file.
File1 (one.txt):
123 123 234 345File2 (two.txt):
123 678 567 890As you can see, the two files contain some duplicates. You can easily remove these using the following command:
sort -u one.txt two.txtThis will output:
123 234 345 567 678 890You can as easily pipe this into a third file as follows:
Unable to delete an AWS Internet Gateway
So you need to delete an AWS Internet Gateway, sounds good.
You navigate to the VPC (Virtual Private Cloud) dashboard and go to Internet Gateways.
At this stage you select “Actions” and choose the “Detach VPC” option.
In a perfect world, this would return a “success” and the IG would be deleted.
But sometimes this isn’t the case and you have to do a little more.
How Distributed Applications Work
Distributed Applications come in a wide range of sizes, usages and resource availabilities.
What is a Distributed Application?
A perfect example of a Distributed Application is a multiple node database application such as Cassandra, HBase or Serengeti. These applications make use of multiple instances of themselves to be able to address vast amounts of data are stored across many networked computer systems.
This provides the ability for fault-tolerant issues to be resolved immediately as well as for massive amounts of data to be stored without reaching individual machine resource constraints.
Why Artificial Intelligence (AI) won’t necessarily take your job
Artificial Intelligence, or simply AI these days, is when computers are able to perform tasks that humans would otherwise do.
While this is incredibly exciting for many, it can be absolutely terrifying for others. Specifically those in roles that AI tends to current target.
After all, losing your bread and butter to a computer just seems wrong, but the reality of it is that some roles are already being swapped out for the lesser emotional, more rapidly replicable being of the twenty first century.
The difference between ‘git fetch’ and ‘git pull’
Git Pull vs Fetch
Many of us take a look at
git fetchandgit pulland believe them to do the exact same thing! This is just not true.So what exactly is the difference and when should you use one over the other?
The Difference Between Pull and Fetch
Git Fetch<p class="schema-faq-answer"> The <code>fetch</code> command goes to the remote repository and gets the latest information about the branch, commits, references (tags) and all the file objects. This is then returned to the local git instance so that it knows what to do when you want to issue a <code>merge</code>. </p>Git Pull<p class="schema-faq-answer"> The <code>pull</code> command essentially does a <code>git fetch</code> and a <code>git merge</code> on the respective branch. </p>Roundup
So when would you ever use
git fetchthen? Well, it’s for when you want to get all the information about changes without merging those changes into your local branch and overwriting your local working copy. It is also very useful for when you want to get the meta about a tag without pulling that tag’s reference data back over your local branch.7 Ways to Make Money Online from Home
1. Create a website / blog
There are numerous ways to make money when you create a website or blog. It’s really cheap and easy to do these days as well, with so many available options, some are even free. But how do you monetise your new online presence once you have created something?
There are a few obvious ways, which include:
- Sell things on your website
- Advertising on your website
These are probably the most common ways to make money online from home for almost free.
Investigation of insider attacks with computer forensics
Cyber-attacks do not always originate from outside of the target organisation. Veritably around twenty-five percent of all data breaches occur from the inside, from employees or trusted individuals within the organisation (TechBeacon, 2018).
Employees that have access to internal records, intellectual property or intramural trade secrets need to be watched as closely as any external party or connection should be.
Why employees are a risk
Employees can trigger internal cyber-attacks, steal intellectual property or even publicly release internal affairs and private information for a number of reasons, which could include:
Squid Proxy behind a Load Balancer on AWS
Squid is a proxy software that allows a computer without internet access to proxy through another computer that does have internet access.
Squid is very easy to get setup and the computer that needs internet just needs to specify environment variables called
HTTP_PROXYandHTTPS_PROXYwhich have the value ofhttp://squid.ip.address:3128/The complication comes in where you need a Squid instance (sitting on an EC2) to sit behind an AWS load balancer. This is usually done for a number of reasons, such as service redundancy, uptime guarantees or even mitigating against maintenance schedules.
How to install a Ruby Gem without Root on a Mac
Gems are little packaged Ruby applications that allow you to extend the ecosystem and reuse countless online sources.
If you don’t have Root on your Mac (work at a large company?) but you still want to use a Gem or two, then you will usually get the following error when attempting to install:
ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.This is incredible annoying, but something you can’t avoid. So better find a workaround and move on!
The dark truth behind Advertising on the internet
The story
Steve has a website which sells carpets in London.
Steve’s carpet business has been doing really well and Peter has recently noticed just how well. Peter decides to get into the same business and decides to build a website too.
Peter’s website is soon complete and he has a little stock to get started.. but nobody visits his website. So he decides to take out some online ads.
International hosting governments and forensic email cases
Cyber forensics is hard, but it is even harder when servers are hosted in different geographical locations and an investigation needs all localities to cooperate and hand over every part of the data consistently.
This is primarily due to privacy laws that each region may apply or carry out in differing ways.
Multiple regions
Even if a compilation can source multiple regions data; dealing with international governments could mean prolonged wait times, unfamiliar processes to follow or even citizens of those regions withholding data due to privacy rights within that region.
When to give up on your startup/product
One of the hardest things you can do after trying to get a startup or product off the ground is to simply give up and call it a day.
After all, you’ve put an awful lot of blood, sweat and tears into it, and you have probably done this for months, if not even years!
As a life-long software developer, I’ve always had side projects going, some from small ideas to others that I have truly invested a lot of time and money into. We all seem to fall down this same path and who doesn’t want their own company, doing exactly what they want to do?
Just SSH to my Jump Box!
I am a professional software engineer and do an absolute ton of devops work as well.
I’ve actually never been hired into devops roles as I always go in as a programmer, but I also always end up doing devops as well for various reasons.
What tasks?
These usually include things like:
- I like to get my code running on infrastructure as soon as possible for Proof of Concepts (POCs) and the like.
- I’m often one of the first people in the team, or am part of starting the project.
- I have a good grasp on the system admin side of things and like to get my hands dirty.
- I made the first prototypes of the software so like to get all the other parts up so that new joiners have a good understanding of how things work together.
One of the things I have found about getting this all going each time is that I end up with usually quite a lot of rapidly changing Compute machines (EC2s) and other services. It is perfectly fine for me to login and get the latest IPs to SSH to, or keep a local config, but as soon as I have a team that needs to start using them, connecting to things or getting onto boxes to made changes then this doesn’t really work all that well.
Counting in Python using a list
So before we begin, let me just tell you that this is a pretty useless thing to do.. But I was playing around with it while waiting for a C++ project to finish compiling, so why not!
The code (click here for the Gist):
magic = 0x616f-0x414f numbers = [ (magic/0x186A0), (magic/0x3E8/8), (magic/0x3E8/4), (magic/0o1534-7), (magic/0x3E8/2), (magic/0o2534-1), (magic/0o2544), (magic/0o075/19), (magic/0o064/19), (magic/0o1654) ] i = c = numbers[0] while True: print('%d%d' % (c, round(numbers[int(i)]))) i += 1 if i>len(numbers)-1: i = 0 c += 1If you ran it, it would look like this!
Show the desktop’s image name on a Mac
Sometimes you just need to know where that image shown on your desktop is stored!
For this, there is a simple but effective line of text you can pop into your terminal.
defaults write com.apple.dock desktop-picture-show-debug-text -bool TRUE;killall DockThis will render the image’s location pathname and image name over the desktop background image.
When you’re complete and you want to disable that over render of the image name, then simply type:
Network Forensics Concerns around GDPR
In Cyber Forensic there are a vast array of tools that are used throughout most investigations, however, not all jurisdictions allow or even agree to the usage of some of them. This is mainly due to each specific geographical region’s view on their citizens right to privacy.
Some of the tools and tactics to collecting evidence are therefore questionable and raise specific concerns in this matter.
During the evidence collection process there are many things to consider when it comes to data being transferred over a network.
A look into Future Developments in Operating Systems from a Cyber Forensics Investigator
Operating systems (OS) really have come a long way since the very first one was created by General Motors in 1956 (WIHT, 2017) to run on an IBM mainframe.
Since then, there have been countless attempts at popularising OS?s and a few companies have truly stood the test of time.
Among these the Windows OS, MacOS and Linux OS are the most notable with the highest market share and global penetration.
Comparing Interface Types in Cyber Forensics
In digital and cyber forensics, there are three main types of categories when it comes to forensic tooling. They can be considered as:
- Graphical User Interfaces (GUI?s)
- Interactive Text-based Consoles
- Command-line interfaces (CLI?s)
Of these, the main competitors are really just GUIs and CLIs as they certainly differentiate most from one another.
They both have their strengths and reasons to be used, of which neither should be discounted.
Many people like to use the GUI version of an application, as it allows them to focus on the task at hand that may extend between a range of activities and doesn?t require them to remember command line arguments and other such distractions. Essentially, getting straight to the point and focusing on retrieving the necessary evidence to place into a report in order to complete the investigation at hand.
Cyber Forensic Investigative Reports
Investigations are not proven in a jurisdiction until a detailed forensic report is created and presented to a judge or jury who can take it to the next level. Presenting digital evidence should be laid out that it is not overly technical in order for all parties to fully understand and interpret in its arrangement, yet still goes into absolute detail to express all the intricacies of an investigation and its extrication.
Altering Computer Evidence
Ever since it has been possible for humans to operate computers, some have used it to perform criminal activities.
Part of a cybercriminal’s gameplay is to cover up or otherwise alter digital evidence in one form or another.
There are many reasons why cybercriminals may try to alter computer evidence; these could be any of the following:
- Cover their traces
The most obvious reason is to simply cover up that the fact that an attacker was around and where the attack came from. - Shift the blame
Covering evidence or planting alternative evidence could shift the blame and make it appear as though another attacker, group or country was to blame for the attack. - Cover up a wider plan
Sometimes an attack is simply part of a larger, more coordinated attack. Covering up evidence at this point would be crucial in order to complete the greater plan.
Every time a computer is used, logged into, or attacked locally or remotely, traces of evidence (often called “logs”) are stored which can lead back to identify the operative; potentially showing where they connected from and what group of exact activities they performed (Kassner, 2015).
Connection broken by ‘SSLError(SSLError(1, ‘[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)’
This happens when your machine does not have the correct certificate bundle to access the Pypi repository, or you are behind a corporate proxy that just loves to block everything!
An easy way to get around this is to edit (or create) a local pip.conf file under your home directory:
~/.pip/pip.confPut the following in:
[global] index-url = http://mirrors.aliyun.com/pypi/simple/ trusted-host = mirrors.aliyun.comAs you can see, we have changed the download location to a mirror that doesn’t use HTTPS, so there will be no certificate issues.
Can’t pull a Git branch because of merge conflicts?
Sometimes you need to pull a remote branch and want to accept all their commits (and history) and override your own repository.
It’s quite simple if you do a pull, don’t care about unrelated histories and accept all their code when there’s a conflict.
git pull upstream master --allow-unrelated-histories -s recursive -X theirsThen simply push to your own remote and you’re done!
Software development processes
Introduction to Software Development Processes
Gabry defines the Software Development Methodology to be a set of related activities that lead to the production of the software (2017).
While this is the simplest concept of the processes, there are many formalised industry best practises in operation today; some of these include Rational Unified Process (RUP), OPEN, eXtreme Programming, Scrum, RWSP, DSDM and more.
A****?software development scenario****
Though I have worked under a range of these processes, I have found the Scrum methodology to be the best performing in most workplaces.
Approaches to software reuse
Introduction to Software Reuse
Software reuse is the process of creating software from antecedent and extant components.
There are a range of approaches that can be taken when following a reuse pattern, these can usually be grouped into one of the following abstractions:
- Class Libraries
- Reusable Components
- Application Frameworks
- Patterns / Service Oriented Architecture (SOA)
There are many benefits in taking up software reuse (SelectBS, n.d.). These include increased software productivity, shorter development times, improved interoperability, recuded costs and usually higher output quality to name a few.
Get the output of an application logged in the terminal
Just a quick note:
You are probably looking for a Linux command called `dtrace`.
If you’re on a mac then you are probably looking for `dtruss`.
Agile as a Software Development Process
Waterfall and Agile are by far the most commonly used software development processes, however, within them, there are many different styles of software development used in the management of software development projects.
While each has their own advantages and disadvantages, we will focus on Agile as it has rapidly grown in popularity over the past few years and is widely accepted throughout the software development discipline and across a wide range of industries of all sizes.
Big Data Security and Privacy Issues
Big Data shares what is commonly termed the V properties or characteristics such as Velocity, Volume and Variety which are amongst the most typical or frequently repeated.
Taking into account security issues and privacy implications with such large datasets is a challenging ordeal that needs a repeatable framework to cover all areas.
Volume is with little to no doubt the most highly targeted characteristic as the expression Big Data fundamentally factors a voluminous amount of information or data that needs to be processed (McCafferty, 2013).
How to delete/revert a Git commit
You’ve just pushed something to a Git repository and you immediately regret it!
Run
git logto see what the commit id was:git logTake the first 7 characters of the commit SHA id and do the following:
git revert <commit_id> git push --forceBut if you’re like me and your problem was because of a merge conflict that you tried to resolve and clearly failed at, but still had the balls to push to the repo before wishing you hadn’t; you can still recover this terrible moment in your life by undoing the merge request itself.
[Solved] Pip: There was a problem confirming the ssl certificate
If you ever get the following error when trying to install a Pip module under Python:
Could not fetch URL https://pypi.python.org/simple/****/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skippingThen an easy way to get around it is by adding the trusted-host flag to your commandline argument as follows:
--trusted-host pypi.python.orgSo your final command may look something like this:
pip install some_module --trusted-host pypi.python.orgHow to Learn Python Programming Quickly
So you want to learn to program in Python and you don’t have a lot of time?
That’s okay! Once you grasp some of the key concepts and ways of thinking, it will all come to you.
So let’s get going now, shall we?
What is Python?
Python is a high-level, interpreted, object-oriented programming language with dynamic semantics used for general-purpose programming. It was created by Guido van Rossum and first released in 1991.
NoSQL Pandas Dataframes
Pandas Dataframes are simply a table with some rows (McKinney, 2015) and many additional features built right in to make data scientists lives much easier.
What are NoSQL Pandas dataframes?
Pandas is an open source Python library that provides high performance yet easy to use data structures and data analysis tools (Pandas, 2018).
Dataframes are two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes. They can be thought of as dictionary type containers for Series objects (PandasDocs, 2018); they are also the primary data structure used in Pandas.
Relational (SQL) vs NoSQL Database Models
The Relational (SQL) database has been a central piece to businesses since the 1970s when they first had their claim to fame.
Experts say that the world?s data is doubling every two years (Gajani, 2017) and this is simply something that traditional relational databases cannot manage with their architectural inner workings and scalability concerns.
Carlo Strozzi first used the term NoSQL in 1998 to name his then lightweight database to show distinctions between it?s SQL cousins, however, it was still relational and quite different to what NoSQL databases circa 2009 ended up being.
Netflix Hadoop Big Data Marketing Use Case
Netflix is a video streaming service that has a wealth of information about their user base likes, dislikes, general consumer habits, retention lengths and much more.
Netflix uses their big data to commission original programming content that it knows will succeed and be accepted in relevant published markets (O?Neill, 2016).
They perform various A/B tests to determine which variant of similar things perform higher, for example, when showing cover images for series or movies, they will at random show alternative images to determine which proves more reactive from their user base.
Using Hadoop to manage Dark Data
Dark Data is the biggest piece of the pie (Datumize , n.d.) when it comes to Big Data and what lies beneath huge datasets of collected information.
IBM has stated in a report that over 80 percent of all data is dark and unstructured, meaning that it is simply too much data to process, analyse or unlock valuable information from.
This data is termed Dark Data and is mostly unstructured and oftentimes missing or incomplete, which leaves a lot of potential for solutions to be built around high volume analytics and processing.
An Introduction to Client-Server Systems
A client-server architecture/system is one where the server maintains all models of the backend datasets and business logic around taking and providing information to fulfill a service request from a client which in turn shows the representation thereof.
The client/server model has quickly grown in popularity throughout the 1990s and today serves as a favoured choice for most organisations? (Subramanian, Lacity, 1997) operations.
There is a statement which asserts that ?there are no unusual managerial issues related to the introduction of client/server systems?, however, this evaluation is not a valid one because of the change in style from the previous centralised mainframe approach that was extremely popular in yesteryears by comparison to today?s model which focuses on a more distributed and multi-machine configuration.
When to use FLUSH PRIVILEGES in MySQL
So if you’ve ever created users and given them specific permissions from with SQL or the commandline, you will be familiar with a statement called FLUSH PRIVILEGES.
It is said that if you create a new user, or alter than user, you should run FLUSH PRIVILEGES in order for the MySQL Engine’s Session to take the change into immediate effect.
But what about if you GRANTed or REVOKEd a permission? Do you still need to use it?
MySQL Community Server MSI Installer Hangs on Windows 10
I was trying to install MySQL Community Server for Windows 10 using the standard .MSI installer provded from the MySQL website and the installer just hung, saying that there was 3 seconds remaining.
About half an hour later, it still said “3 seconds remaining”.
It turned out that you have to run cmd (commandline) as Administrator:
Press Windows Key (Super), type “cmd”, right click on “Command Prompt” and select “Run as administrator”.
Android device supports x86, but APK only supports Arm
I get this error quite a lot when trying to deploy an Android APK to an emulator.
“Device supports x86_64, x86, but APK only support , all, armeabi-v7a”
The good thing is that it is actually a very easy thing to fix.
While doing development you can simply change the Build Variant target.
How do you do that?
Click “View” -> “Tool Window” -> “Build Variants”
Notice that ARM is currently selected and most of the time you will want x86 to be the build target if you are deploying to a emulator.
Weird Dialog Boxes
Adobe Setup setup?
Got this one while using Chrome, it complains about Safari?
What a load of bullshit!
Really?
Very handy tips screen!
ERROR: NO ERROR!
A bit on SQL Standards
SQL (Structured Query Language) for relational databases was maintained and standardised by the American National Standards Institute (ANSI) and the International Organisation for Standardisation (ISO) which is affiliated with the International Electrotechnical Commission (IEC).
When a new SQL standard is published by these organisations it is outlined on the ISO website and available for everyone to both reference and use as required.
The current version used in most production instances is commonly ISO/IEC 9075-11:2011; however, in December of 2016 a new version was published and is described under ISO/IEC 9075-11:2016 which can be found here: https://www.iso.org/standard/63565.html
A Brief Talk on Databases
Databases have been around since ancient times, when elaborate database systems were deployed by governments, hospitals and organisations to keep track of vast amounts of information; but only until around the 1960s did computerised databases start to take shape and become cost effective for private organisations to start using (Quickbase, n.d.).
I have used countless databases over my career to reliably store and retrieve many sizes of information, from a small collection of less than ten items of data to terabytes worth of hundred of billions of data points spread across clusters of machines around the world.
Cloud Computing – The Refute
Cloud is great, but when you know what you are doing, think about alternatives (Blippex, 2013).
What is Cloud?
“The cloud” is a term given to pay as you go – or pay monthly – off premises computing services that provide either hosting or storage to it?s user base. These services are created, maintained and wholly operated by a cloud computing provider.
Instead of purchasing and managing your own infrastructure, many opt for a cloud based model where you simply pay for the amount of resources you require at a given time.
Auditing Organisational Information Systems – Security
Auditing an organisation?s information systems is a vital part of operating a business at any decent scale. Particularly from a security standpoint (Mohamed ElBorno, n.d.).
Information systems have many different facets and each organisation operates slightly differently, so while auditing can be handled the same on general shared traits, more bespoke business units and organisational structures should be taken into account when designing a well thought out auditing system that fully guarantees the security of an organisation?s systems.
Biometric Technology
What is Biometric Technology?
Biometric verification is any means by which a person can be uniquely identified by evaluating one or more distinguishing biological traits (Margaret Rouse, n.d.)
Such recognition usually falls into one of the main categories such as:
- Facial recognition
- Hand geometry
- Earlobe geometry
- Signature comparison
- Voice waveform recognition
- Iris-pattern and Retina-pattern recognition
- Fingerprint recognition
The above are the verification patterns which various technologies are built around in order to create working application use cases for larger security concerns.
Copyright Compensation in the Internet Age
The original conception of copyright in 1710 (Craig Joyce, n.d.) was that it usually covers only the expression of a particular idea and not the idea itself, but this was a very long time ago, before the challenges of a digital society.
Since then, copyright has had to encompass a wide variety of extended property far removed from it?s original case studies that were available at the time.
Controlling employee digital access
Organisations of all sizes have taken to controlling what their employees can access in order to conserve computing resources, keep their employees focused 100 percent on the work they were hired to do and to make sure employees performance is high and as productive as possible (Cyberoam, n.d.).
However, keeping employees motivated and productive is not as simple as simply restricting specific access to internet resources and computer controls.
Electronic monitoring in the workplace
Electronic monitoring is not a new thing, nor one that only affects the workplace. From closed circuit television (CCTV) in stores and down many streets, to similar surveillance in offices everywhere, we are constantly being monitored in all aspects of our lives.
Why and how employers are monitoring employees
Many employers and organisations tend to perform similar tactics when it comes to monitoring (Emma Anderson, 2014), but I would like to focus on my current and previous employer in order to draw a common ground and paint a picture as to where and how we as employees are being electronically monitored.
The Therac-25 Case Study – What Actually Happened?
The Therac-25 was a computerised medical technology radiation therapy machine produced by Atomic Energy of Canada Limited (AECL) in 1982.
Between 1985 and 1987, it was involved in at least six patients deaths due to incorrect radiation doses because of computer software related failure.
When the error was first seen, it was thought to be a hardware problem with the microswitches.
After further inspection and deeper technical analysis; the problem was due to a software bug where a Race-Condition – which is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time but the operations must be done in the proper sequence to be done correctly. (TechTarget, n.d.) – occurred (Nancy Leveson and Clark Turner, 1993), causing the collimator jaw to not shut at the required moment. The result of this was that high current electron beams were fired directly at the patient with nothing to absorb the fatal radiation beam.<
Your Responsibilities as an IT Professional
As an IT professional it is extremely important to make sure that you do not take advantage of your position on being able to introduce certain skewed characteristics into a computing system in order to gain unfair advantage to your company or client?s business.
This is seen as unethical and in many cases can also be illegal.
Your professional responsibilities are:
- Role
The person assigned a task is considered the responsible one (Illinois Ideals, n.d.).- Legal
The individual or organisation can be both legally responsible and/or liable to fines or damaged, if not more.- Moral
Moral responsibilities hit at the heart of our core and spell the difference in who we aim to be as humans.As an IT professional, you have these responsibilities to yourself, your end users, your brand you are representing as well as your country that you upkeep the law in.
New capabilities with technology
Computing technology has undoubtedly had some very prominent impact on society at large.
Of the almost countless capabilities that it has brought us, the following five core capabilities are without a doubt at the top of any compiled list on the subject:
- Ever increasing speed
- Unlimited storage potential
- Lack of human error
- Global connectivity
- Auditability
Being able to store an unlimited amount of data is one of the main capabilities that we will expand upon and explore in a bit more detail as it provides innumerable offsprings into technological advancements and data insights generally for a wide range of applications and technologies in almost all sub-industries.
The Printing Press – Technology’s impact on society
It’s important to first define what the term “technology” means.
Technology is “the application of scientific knowledge for practical purposes, especially in industry.” (Oxford Dictionary, n.d.)
The term is not reserved for computing systems, but for any field of engineering or applied sciences.
The printing press has been one of the most important inventions in history and would definitely classify as being within the top few technological enhancements of all time.
Google Abuses Search Dominance in the European Union
The EU Commission found that Google has been favouring their very own shopping service while demoting those of their rivals as well as the placement of how they are seen in search results online.
This is favoritism or preferential treatment which makes it unethical, regardless of sustainability thereof.
This is a negative thing as a world-wide monopoly of this magnitude should not be allowed to occur at all.
Understanding the Risks of Commercial off-the-shelf software (COTS)
Commercial off-the-shelf (COTS) software can be an attractive buy in for many companies when it comes to:
- Purchasing an already made final software solution.
- Purchasing a solution that is tried, tested and trusted in the industry already.
- Not wanting to get a development team in to build a bespoke solution.
- Not wanting to manage a greenfields software development project.
It can seem very attractive at first to jump into a COTS solution, but there are many things to take into account that can make it a less than ideal option. This is where analysing potential software reuse risks is highly recommended and will make the difference between an overall cost saving as initially expected, compared to a failed attempt where the result ends up costing significantly more and the project runs over all checkpoints as well as completion dates.
Identifying Risks in Software Engineering
In Software Engineering it is absolutely paramount to identify all risks that may arise in a given project or grouping of tasks. Without doing the aforementioned, a project can quickly unravel and become disjointed and inherently fall apart.
It is very important to be able to identify risks and act on them appropriately and in a timely manner (Pressman,1997).
Among the many risks that are most common and obvious in Software Engineering, I have decided to showcase three in particular that I have found to be imperative in noticing and foreseeing the looming signs of project degradation and failure.
Software engineering challenges in the 21st century
Software Engineering covers not only the technical aspects of building software systems, but also management issues, such as directing programming teams, scheduling, and budgeting. (Webopedia, n.d.)
The world of software has exploded since it’s humble beginnings in the mid 1940’s.
Over the next 30 years the industry focused primarily on cost effective hardware manufacturing and software was undertaken as a second measure, but there were no real methodologies to creating robust, reusable software components. (Computer Hope, 2017)
Computer Memory – The Breakdown
Storage devices have come a long way in an extremely short amount of time; given how much they have changed from just my personal knowledge alone. I still remember using an IBM PC XT 286 with 640KB of RAM and a 64KB ROM to using services provided by companies over the past few years such as Backblaze who are building out 60 Drive 480TB Storage Servers accessible from anywhere.
There are two primary types of storage topologies. Volatile Memory and Non-Volatile Memory.
Current Trends in Computing
The American multinational technology company Yahoo, which has been around since the mid nineties has once again been hacked. This time it is more serious than ever before and a total of around one billion accounts have been identified in the biggest known breach in history as gleaned by The Guardian, Aljazeera, CNBC and numerous other sources.
This particular event has contributed towards the overall security risks evident in storing your information on another corporation's network. Customers take for granted that their personal and private information is safe and secure online.
Academic integrity in a cultural context
In academia it is vitally important to backup your own thoughts and ideas by using previously written authoritative papers and articles in reference.
This helps provide you more credibility as well as proof of what you’re saying actually makes sense and falls in line with previous extensive research that has been done on the subject. It also helps to build upon others so as to not have to “reinvent the wheel” each and every time. “Standing on the shoulders of giants” could potentially be the greatest lesson learned in progressing an industry and the concept of intellectual property is often not widely known and dealt with correctly.
How to get more traffic to your blog
If there’s only one thing that keeps website owners up at night, it’s thinking about the next wave of traffic that they aren’t yet getting.
Without decent amounts of traffic your website isn’t really doing all that much – regardless of what fantastic theme or design you may think you have.
and gain a more popular website bustling with loads of daily visitors**
**Social Networks
The obvious method to get more visitors is to go to where everyone else on the internet is most of the time. That would probably be one of the many social networks, such as Facebook, Twitter, Pinterest etc.
How big is Amazon S3 really?
Amazon’s Simple Storage Service, or simply S3 for short, is a product designed for storing objects (or files are most people know them) in their proprietary cloud hosting (AWS).
Since S3 was first released on March 14th of 2006, it has gained amazing amounts of popularity online, particularly from web and software developers.
It’s quite interesting to know what S3 really is under the hood and how large it has become.
3 Things you should be tracking with your analytics software
What should we be tracking?
This is a question we get asked quite a often – mainly by new customers as well as people who aren’t certain if what they’re looking at adds any value to their daily business time usage.
If you’ve ever used an analytics tool, you will identify with how addictive it can be to watch the traffic coming in, see where everyone visitor is from and what they are looking at as it happens in realtime.
11 of the Best Google Analytics Alternatives
So most webmasters know about Google Analytics and have probably used it to some degree, but did you know that there are some pretty good alternatives out there, some even better than the all-famous Google Analytics.
We have decided to do a roundup and show off some of our favourites – obviously, we favour Statvoo as we created it, so it’s clearly better ;).
Clicky
Clicky focuses on keeping things simple and lets you see the stats that matter as they come in.
Setup is simple and involves a snippet of custom code that you add to your website.503 Service Unavailable: Back-end server is at capacity
The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. Some servers in this state may also simply refuse the socket connection, in which case a different error may be generated because the socket creation timed out.
Fixing 503 errors
User Testing and Feedback?
So now you have a website, you use it and love it, but does everybody else?
There are many tools out there that allow you to do User Acceptance Testing and provide Feedback from real users, but what are the options?
Here are some options we have found that may be of interest.
-
UserTesting.com UserTesting.com provides on-demand usability testing.
-
Uxeria.com Your solution for rapid user testing. Users recording in 48 hours.
Date ranges are the key to a better index
Since AO Analytics originally went live in February 2013, we have been doing focused around individual time based reporting, it worked well and we were able to sort through indexes without doing full table scans.
After much feedback from our users as well as data usage patterns we made the decision to move to date ranges.
This replaced our entire retrieval algorithm and therefore copious amounts of work had to go into regression of backward compatibility while introducing the new way of moving forward with the overall system.
Track your Alexa Rank History
The Alexa Rank is a way of determining a website’s popularity. ?Alexa.com are in the game of Internet popularity ranking and for quite a long time now have been doing a very good job of it.
They have a system where the most visited website on the planet is rated as #1 and the second is #2 and so on.
If your site is within the top 100,000 alexa rank it is watched more closely and general usage statistics are calculated about it.
SSL Encryption – Update
We have just rolled out SSL encrytion on Statvoo which means:
- Event data is saved over a secure channel
- Authentication is done automatically
- All our user’s login information can not be cached over proxies
- Https sites can now use the service as well
Why Website Analytics Is So Important These Days
The web has come a long way since Tim Berners-Lee, a British scientist at CERN, “invented” the World Wide Web (WWW) in 1989.
Above is the very first Web Server with the classic label on the front “This machine is a server, DO NOT POWER DOWN!!”. Which has become an object of many nerds interests as with it being the very first web server, it is quite an interesting machine to study – not that it is available to play around with, but just because of the nerd value it adds.
Since these days the web has become a lot more intricate and we have found ourselves using the internet for many things and on many types of devices.Create daterange array of missing dates
<?php //fromDate 2014 - 01 - 22 //toDate 2014 - 02 - 20 //$arr Array( [0] = & gt; Array( [ISO_DATE] = & gt; 2014 - 02 - 18[DAY_SUM_AMOUNT] = & gt; 3000[DAY_SUM_VOLUME] = & gt; 2[CONVERSION_PCT] = & gt; 100 ) [1] = & gt; Array( [ISO_DATE] = & gt; 2014 - 02 - 19[DAY_SUM_AMOUNT] = & gt; 4000[DAY_SUM_VOLUME] = & gt; 1[CONVERSION_PCT] = & gt; 100 ) ) //codetime function createDateRangeArray($strDateFrom, $strDateTo) { $aryRange = array(); $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2) , substr($strDateFrom, 8, 2) , substr($strDateFrom, 0, 4)); $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2) , substr($strDateTo, 8, 2) , substr($strDateTo, 0, 4)); if ($iDateTo & gt; = $iDateFrom) { array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry while ($iDateFrom & lt; $iDateTo) { $iDateFrom += 86400; // add 24 hours array_push($aryRange,date('Y-m-d',$iDateFrom)); } } return $aryRange; } function recursive_array_search($needle,$haystack) { foreach($haystack as $key=>$value) { $current_key = $key; if ($needle === $value or (is_array($value) & amp; & amp; recursive_array_search($needle, $value) !== false)) { return $current_key; } } return false; } $dates = createDateRangeArray($fromDate, $toDate); $arr2 = array(); foreach ($dates as $date) { $inArr = recursive_array_search($date, $arr); if ($inArr !== false) { array_push($arr2, $arr[$inArr]); } else { array_push($arr2, array( "ISO_DATE" = & gt; $date, "DAY_SUM_AMOUNT" = & gt; 0, "DAY_SUM_VOLUME" = & gt; 0, "CONVERSION_PCT" = & gt; 0 )); } } $arr = $arr2;Speedtest on Ubuntu Server (commandline)
Using the
speedtest-cliis easy and very useful. You run it as follows:wget -O speedtest-cli https://raw.github.com/sivel/speedtest-cli/master/speedtest_cli.py chmod +x speedtest-cli ./speedtest-cliURL GET vars to PHP Array
Sometimes you will need to retrieve the GET variables passed into the current page URI or you will have a URL string to work from which contains certain GET variables, the below method helps a lot to convert them into an array which you can easily manipulate later.
$url = $_SERVER["REQUEST_URI"]; parse_str(parse_url($url, PHP_URL_QUERY), $array);$arrayis now an array of all the GET variables in the URL.Alternatively you can pass a URI string in place of the $_SERVER[“REQUEST_URI”] by replacing the
$urlvariable with something else.python "AttributeError: ZipFile instance has no attribute ‘__exit__"
This is actually a very easy error to fix, eventhough off the bat it seems a lot more involved.
You probably have syntax something like this:
with zipfile.ZipFile(wr_zip) as zipfd: extract(zipfd, wr_csv, wr_csv)So instead we will change it to this:
zipfd = zipfile.ZipFile(wr_zip) extract(zipfd, wr_csv, wr_csv)The reason this fixes it is because at the moment (Python 2.6/2.7 I believe) the zipfile.ZipFile class has no __exit__ attribute, so it does not work with a `with statement` as other file objects do.
Remove specific HTML tags using PHP
There are times when you want to remove a specific HTML tag from an HTML block of text.
This could be an anchor(
<a/>) or an image(<img/>) perhaps.You can use preg_replace to do this quite quickly and efficiently.
Remove an anchor:
$content = "Sample text <a href="#">Our anchor</a>. Etc etc"; $content = preg_replace('/<\/?a[^>]*>/','',$content); //$content is now -> "Sample text. Etc etc";Remove an image:
$content = "Sample text <img src="our_image.jpg">. Etc etc"; $content = preg_replace('/<\/?a[^>]*>/','',$content); //$content is now -> "Sample text. Etc etc";Keep Google Map v3 centered when browser is resized
Using Google Maps V3 Javascript API you can keep the map centered to the browser’s window by using the following trick when resizing the window.
var mapOptions = { zoom: 2, center: new google.maps.LatLng(0,0), mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); // this is our gem google.maps.event.addDomListener(window, "resize", function() { var center = map.getCenter(); google.maps.event.trigger(map, "resize"); map.setCenter(center); });Buy a Google Nexus 10 in the UK!
If you are looking to get a Google Nexus 10 inch tablet and are based in the UK you are in for a shocker!
The only place to buy it is at the Google Play store and since about the middle of November 2012 they have been sold out.
Some people say it’s due to delayed deliveries and orders and some say it’s just bad management on Google’s behalf. I think the latter is probably the thing that actually happened as no other tablet providers seem to ever have this problem.Let Joomla and MySQL interact!
I often need a quick and easy few lines to retrieve some data from MySQL using Joomla without all the MVC nonsense that usually goes about this topic.
So here is how I do it!
$dbSEL = JFactory::getDbo(); $dbSEL->setQuery("SELECT MAX(`start_price`) FROM #__some_table"); $dbSEL->query(); echo $dbSEL->fetchRow();As you can see above, we get the current database object and then run a query on it.
You may notice the hash (#) in the SQL statement of this example, Joomla replaces that (as well as the underscores (__) with the database prefix which is configured, so on shared nodes you don’t have to type all that extra stuff that will need to be changed later.Perform a Mysql Query using Joomla!
This is really actually meant for future reference for myself as lately I’ve been doing quite a lot of Joomla! mysql coding and have used the following code just short of 3million times.
$db = JFactory::getDbo(); $querySelectId = "SELECT `id` FROM #__some_table WHERE `user_id`='$user_id'"; $db->setQuery($querySelectId); $db->query(); $data = $db->loadAssoc();What we do in the above code snippet is select a user_id from some_table (#__) is short for whatever your database table’s prefix is (Joomla! replaces this itself) and then we perform the query and return the row’s `id` into the $data variable.
Refresh User Data in Joomla
I was busy with a custom component in Joomla, and it stored it’s own user_details based off of the main users table, but if the details were changed then I needed the system to update the session to reflect the changes.
This is what I did:
$user = JFactory::getUser(); $session = JFactory::getSession(); $session->set("user", new JUser($user->id)); $user = JFactory::getUser();Extract email addresses from a string – PHP
Sometimes you need to extract multiple email addresses from a string and the following function will make all your dreams come true.
function extract_emails_from($string){ preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches); return $matches[0]; }..and this is how you use it:
$text = "this is some text and here is an email address [email protected], here's another [email protected], etc.."; $emails = extract_emails_from($text);Now let’s use the data:
// as string print(implode("\n", $emails)); // loop as array foreach($emails as $email) { echo $email .","; }How to drive traffic to your website!
This is a very hot topic indeed.
Definitely one that everyone with a website should know all about.
To begin our journey we will look directly at the Traffic Generator Sites out there who – to be honest – are complete scams because all they really do is one of two things…
1.) Load your site into those annoying pop-under ad windows that users close immediately as they appear(not having opened them themselves)
jQuery limit fields to alphanumeric characters only
I was trying to restrict a form’s field from only allowing the user to enter alphanumeric characters into it. I looked all around and couldn’t find a nice way to do it without a plugin, so I wrote my own bind function that you can attach straight to an element.
$("#yourFieldsElementId").bind("keypress", function (event) { if (event.charCode!=0) { var regex = new RegExp("^[a-zA-Z0-9]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } } });If you would like to restrict the input to only be numeric then do this:
Make a dynamic year dropdown using PHP
Ever wanted to have a dropdown that automatically showed the current year and the few years before it?
This is a quick and easy way to do exactly that!
<select name="year"> <?php for($i=date("Y")-5;$i<=date("Y");$i++) { $sel = ($i == date('Y')) ? 'selected' : ''; echo "<option value=".$i." ".$sel."-->".date("Y", mktime(0,0,0,0,1,$i)).""; } ?> </select>Pad a string with zeros using PHP
Recently I had to create a code/username maker to fit into a certain type of pattern so that all “broker codes” (as they were called) followed the same path.
An example one looked like so:HJTH0001The number needed to increment and I wanted to use the auto-increment feature in the mysql database table that was driving this data to make it.
This was easy but I ended up with a code that looked like this:
ImportError: No module named MySQLdb (Python)
Trying to use MySQL with Python and getting an ImportError?
Traceback (most recent call last): File "some_file.py", line 4, in import MySQLdb as mdb ImportError: No module named MySQLdb
This is likely because you have not installed it to the system. You can do this on Ubuntu Linux by running the following code:
sudo apt-get install python-mysqldb
Also, remember that there is no MySQLdb for python3.x and above. There is however, a fork of it on GitHub at: https://github.com/PyMySQL/mysqlclient-python
Search for “arabic” is url request and change codepage – ASP
If you are using Classic ASP (yuck) to create an arabic section of a website you can search for the arabic string in your Request URI and then change the session’s codepage as follows:
if instr(1, request.ServerVariables("PATH_INFO"), "arabic") then session.codepage = 1252 end ifWindows 7 is better than Ubuntu 12.04 on desktop!
Today we have finalised for ourselves that Windows 7 is definitely a “better” operating system than Ubuntu 12.04 when it comes to desktop environments.
Now, I say “better” in quotes because the word is quite hard to use as is and “convince” everybody while doing so.
We started our journey on Windows 7 and after desperately needing a reinstall we decided to go for the latest version (at the time) of Ubuntu, which happened to be the brand spanking new Ubuntu 12.04.
Function split() is deprecated in PHP
You heard it right! split() is officially a deprecated function. That means that you can still use it if you are really brave and it will work correctly, but don’t expect to see it in later versions of PHP when they come out. Somewhere along the line it WILL not work at all.
It has been marked as “deprecated” due to the fact that the explode() function has the exact same output!
Disable Cache in jQuery
I usually run into this problem when dealing with good ol’ Internet Explorer (..any version of IE actually).
The problem is that IE tries to be smart and not tell you the new output of a file it fetches more than one time with the same filename, instead it shows you what it saw the first time it loaded that file.
You can imagine this would be insanely dumb if you were using a realtime application data source where a script output a different resultset each time, e.g. most database ajax requests.
Where is Technology heading, perhaps we should focus more on Software?
I often wonder to myself where the technology industry is heading as I see new things come out almost daily.
You look around and something you just bought is all of a sudden outdated. This can be quite irritating for the techno-geeks out there that always want the latest release of every gadget, as it makes it somewhat impossible to keep up with what’s in stores.
The really nice thing about software over hardware is that one can just perform a localised update instead of having to purchase new hardware everytime something changes or is improved. This all lead me to believe that perhaps things would be better if we could somehow come up with a device that is so well thought out with such good hardware that one could just perform regular software updates every once in a while and you would essentially have the “latest gadget around”.
How to break out of an iframe
So someone’s trying to make their site better by opening a page on your site inside of their site using an iframe?
They’re doing something like this:
<iframe src="http://www.example.com/your_page.html" width="100%" height="100%"></iframe>Well how about you stop that from happening by pasting the following line in your website’s header!
<script type="text/javascript"> if (top.location != self.location) { top.location = self.location.href; } </script>The above code basically does a check to see if the site is the same as what is said in the address bar, if not then it sets the parent’s frame (the other site) to change to your site’s location!
Edit hosts file on Windows 7
The hosts file is used to manually alter the hostname or IP address in place of it being served by a Nameserver, also known as via DNS.
The hosts file is located here:
C:\windows\system32\drivers\etc\Or an easiler way to get to it incase of whatever is like this:
%systemroot%\system32\drivers\etc\This file cannot be editted by “normal users” and requires all changes to be done via an Administrator.
This is really easy if you do it in the following way:
(EAI 2)Name or service not known: Could not resolve host name *.80 — ignoring!
You are no doubt trying to add a vhost and you get the following error when attempting to affect changes by restarting the http daemon (httpd):
(EAI 2)Name or service not known: Could not resolve host name *.80 — ignoring!
Not to worry!
Add the following text to httpd.conf at the bottom (That’s at /etc/httpd/conf/httpd.conf):
NameVirtualHost 12.34.56.78:80 ServerAdmin [email protected] DocumentRoot /var/www/html/the_path/ ServerName the_path.example.com ErrorLog /logs/the_path.example.com-error_log CustomLog /logs/the_path.example.com-access_log commonNow just restart the http daemon:
Virgin Media blocks torrent sites!
Virgin Media have done it again! They have gone and started a “downloaders war”, I’m sure of it.
Basically what happened is that Virgin Media are claiming that they have had an order from the Courts to prevent access to a whole bunch of sites which lead to illegal downloading or copyright infringement downloading.
Not only is it Virgin Media but all 5 major ISP’s in the UK that have received this Court order, that’s Sky, Everything Everywhere, TalkTalk, O2 and Virgin Media. The initial case was against the Swedish file-sharing website The Piratebay. The Court order sets in as of the 1st of May 2012 and originated in July 2011 when The British Phonographic Industry asked The Piratebay to remove selected torrents and The Piratebay refused, so they took them to court in December. In February Justice Arnold ruled that the The Piratebay incite their users to commit copyright infringement.
How to Comment out a line in a Crontab on Linux
Firstly let’s just note that crontabs are read in the following way:
* * * * * command to be executed - - - - - | | | | | | | | | +----- day of week (0 - 6) (Sunday=0) | | | +------- month (1 - 12) | | +--------- day of month (1 - 31) | +----------- hour (0 - 23) +------------- min (0 - 59)Your current crontabs can be viewed on your linux setup by typing in the following command:
DateTime conversion function using PHP
It’s really very simple to convert times in different timezones using the following function.
function dateTimeConversion($datetime, $timezone="Europe/London") { $date = new DateTime($datetime, new DateTimeZone("UTC")); $date->setTimezone($timezone); return $date->format("Y-m-d H:i:s"); }As you can see, it takes 2 arguments, $datetime which is a time string and a $timezone which is a timezone to convert to.
A usage example would be:
echo dateTimeConversion("2012-05-01 17:09:58");Convert seconds to days, hours, minutes, seconds in PHP
With the following function you can easily convert an integer containing seconds to a nice days, hours, minutes, seconds string or array.
function secondsToTime($seconds, $return_type="string") { // extract days $days = floor($seconds / 3600 / 24); // extract hours $hours = floor($seconds / 3600) - $days*24; // extract minutes $divisor_for_minutes = $seconds % 3600; $minutes = floor($divisor_for_minutes / 60); // extract the remaining seconds $divisor_for_seconds = $divisor_for_minutes % 60; $seconds = ceil($divisor_for_seconds); // return the final array $obj = array( "d" => (int) $days, "h" => (int) $hours, "m" => (int) $minutes, "s" => (int) $seconds ); $str = ""; if ($obj["d"]!=0) $str .= $obj["d"]."d "; $str .= $obj["h"]."h "; $str .= $obj["m"]."m "; if ($return_type=="string") return $obj["d"]." days, ".$obj["m"]." minutes, ".$obj["h"]." hours, ".$obj["s"]." seconds"; else return $obj; }To use the above function you can either use the default return type and call it like so:
Remove dotted outline around anchors
This has become quite a common question asked by many website owners.
“How do I remove that dotted outline around an anchor?”
Lucky for you all, it’s a really easy one to resolve as well. You just have to take a look at CSS for a second and add one line as follows:
a { outline:0; }This will disable the outlines around clicked links all around your site.
Now that you know how to do it you may want to read about why you shouldn’t do this!
Click here to read the petition to not do this.Get amount of hours between 2 hours
If you would like to get the amount of hours between 10:00 and 12:00 then use this!
function timeDiff($firstTime,$lastTime) { $firstTime=strtotime($firstTime); $lastTime=strtotime($lastTime); $timeDiff=$lastTime-$firstTime; return $timeDiff; } echo (timeDiff("10:00","12:00")/60)/60;How to embed HTML5 video with fallback
A common question with the rise of HTML5 becoming more and more common and the whole iGeneration (iPhones/iPads/iEtc) is “how can I embed a video on my site without using a flash player?”. If you’re working with HTML, you might also be interested in how to correctly form HTML and how to place HTML div on top of Flash.
An option that really does work quite well is to use the JWPlayer and set it up to use HTML5.
How to backup all mysql databases
In order to backup all mysql databases, you can run the following command in your linux command line:
The example below is configured with username “theuser” and password “thepass”.
mysqldump -utheuser -pthepass ?all-databases > all_dbs.sqlInvalid command 'RewriteEngine'
If you receive the following error message if means that mod_rewrite is not enabled in Apache:
Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration.
a2enmod rewriteBear in mind this is done like this on Linux Ubuntu, not entirely sure if this works for other flavours too.
How to get the Hours Difference (in HH:MM format) in PHP
It’s very simple to get the difference in hours using PHP
function timeDiff($firstTime,$lastTime) { $firstTime=strtotime($firstTime); $lastTime=strtotime($lastTime); $timeDiff=$lastTime-$firstTime; return $timeDiff; } echo (timeDiff("10:00","12:00")/60)/60;Warning: Invalid argument supplied for foreach()
A common error which occurs with foreach loops is the standard “Invalid argument supplied for foreach()” whch gets thrown up as a warning.
This can easily be overcome by wrapping the foreach loop in a conditional if statement which checks to see if the argument supplied to the loop is an array or not.
Below is an example of how to correct the problem:
if (in_array($arrItem)) { foreach($arrItem as $arrItemi) { // use $arrItemi; } }Unable to connect to any of the specified MySQL hosts.
If you get the following error while trying to connect to a MySQL database using a third party client such as TOAD or SQL Workbench, then you need to edit your mysql server’s my.cnf file.
Error Message: Unable to connect to any of the specified MySQL hosts.
So open the my.cnf file by running a similar command to the following one dependent on your server’s setup:
PHP nl2br on one line
I usually store data from a textarea directly to the database as is, then once I retrieve it back into HTML I use that lovely PHP function nl2br() to convert it to HTML
tags.This works well for most cases until you are passing this data back into javascript where everything has to be on one line!
nl2br()outputs as follows:Line one
Line twoAnd I want it to be as follows:
LEN in MySQL
In MySQL 5.1 LEN is called LENGTH, you use it exactly the same and pass in the link, so: LENGTH(link).
Remove all linebreaks in PHP
If you are having problems with a string that keeps adding a line break when output from PHP to HTML then the following code will work wonders for you!
$string_with_line_break = "blabla\nbla\r"; $string_without_line_break = trim(preg_replace( "/\s+/","",$string_with_line_break));IE9 adding empty table cells in large table
Well as usual, we are once again fighting the woes of the beloved Internet Explorer, and it appears that Microsoft’s latest greatest new and improved browser rival to the market IE9 still has a whole bunch of irritations and retardation to worry about (saw that one coming).
Today I was busy loading a massive amount of data into the body of a table using ajax and in Firefox and even Internet Explorer 8 it worked quite well, but Internet Explorer 9 decided that it would like to add some empty table cells randomly around my “massive table”, now of course I began by kicking something and cried a few times….. but then I thought about whitespacing and the usual problems I had found with it before while using “the best browser ever known to human-kind”(…not) and I thought of removing the whitespaces between the
’s and ’s. SELECT Duplicate Items Using SQL
If you have a table which has duplicate items in then you can use the below statement to select them.
SELECT * FROM tableName GROUP BY columnName HAVING ( COUNT( columnName) >1 )MySQL Error: Can’t get hostname for your address
This error is thrown by MySQL because it tries to do a DNS lookup on the address connecting to the server and it fails due to the IP not being able to be resolved back to a name or some-other deeper DNS bust problem.
The easiest way to fix this is to edit your my.ini or my.cnf (/etc/my.cnf) and in the
[mysqld] section add the “skip-name-resolve” option.Near the top of the file this will look similar to the below:
Adobe drops flash for mobiles!
..and it’s official – so says Adobe’s blog (read it here). Adobe will be dropping support for Flash on future devices due to performance and a few other things, pushing the future more towards the HTML5 route, which isn’t neccessarily a bad thing, I just find it quite ironic and somewhat comical that they waited for Steve Jobs (Apple) to die before giving up their long time fight with Apple about Flash being or not being supported on mobile devices, namely the iPhone.
jQuery Colorbox not showing but background shows
I was using Colorbox for some lightbox type effects to show larger images when clicking on thumbnails, but for some reason the background was showing up but the pretty little box in the middle where the larger image is supposed to show never showed up, so this is how I made it finally appear after many failed attempts!
$("document").ready(function(){ $(".theCssClass a[rel='forGroupingRelCodeGoesHere']").colorbox({ onLoad: function () { $("#colorbox").show(); } }); });So the “real” code that fixed it was the:
Get Value of Checkbox using jQuery
This one is quite an easy one, but a good one to mention non-the-less as it does definitely come in really handy.
If you would like to get a checkbox’s value to send to the backend using jQuery you can always do the following:
Firstly let’s draw some HTML to illustrate our example.
<input id="chkOurCheckbox" type="checkbox" />Now we need some jQuery to do the real work.
var ourCheckboxValue = ($("#chkOurCheckbox:checked").val()=="undefined") ? 0 : 1In our above example we draw an HTML checkbox to the screen and then use jQuery to return the value of it.
Everybody’s a web host
To cut straight to the point, “we’re living in the age where everybody’s a web host”. Whether it be small and quite pathetic or just another reseller of a larger service trying to get their cut of things, everybody truly is spamming the world with more and more web hosting packages.
Just a few short years ago this problem didn’t exist and getting web hosting was quite expensive, unless you went with free services such as the good ol’ “geocities” and co, but then larger companies started up their shared hosting and reseller hosting packages which immediately led to everybody thinking all it took to become a web host was to get themselves a reseller account and start trading. For the most part that isn’t so far off, as 95% of the websites out there sit mostly idle while almost nobody visits them and therefore it’s perfectly fine to share a single machine between multiple clients and call it “excellent web hosting”, but these small guys also try and compete with the larger players in the industry and end up creating quite a mess of things, all while flooding search engines and web development and hosting forums with “hosting deals and specials”.
CSS Background Default
If you would like to override an already attached class containing a background then you can use the following:
background:transparent none 0 repeat !important;Restrict PHPMyAdmin to IP Address
Would you like to restrict PHPMyAdmin from being accessible to the whole world?
Firstly you need to SSH into your box if you are not on the local machine where PHPMyAdmin is installed along with Apache.
cd /etc/phpmyadmin/ vi apache.confYou will need to look for the following text “<Directory /usr/share/phpmyadmin>” and add in the below code:
Remember that you need to press “i” in order to start editting text if using VI.
2014 – Commands out of sync; you can’t run this command now
#2014 – Commands out of sync; you can’t run this command now
Now that can be a really annoying error!
It happens when querying stored procedures in phpMyAdmin as mysqli seems to return 2 sets of results opposed to the usual 1 that mysql returns.
You cannot call anything else until you have “flushed” or “cleared” the second result.
You can try using COMMIT to resolve this.
Image corrupt or truncated: “unknown”
What is “Image corrupt or truncated:
” and what does it mean? This can often be seen while using Firebug in Firefox, but it actually has nothing to do with either and is just the error being reprinted in in firebug in most cases.
It comes from an image that has had it’s extension changed from say .gif to .png or .png to .ico. Eventhough .png and .ico file types are very similar, they are not the same, so an error occurs.
WordPress wp-admin use different language for user
I needed to do some work on a WordPress site a little while ago and all the admins were French – and I cannot speak French other than the popular swear words – so had no idea what was going on in the /wp-admin/ so needed some way of enabling my newly created user account to be in english while letting everybody else use french as they had been up til that point.
Replace all spaces in HTML with except in HTML tags using PHP
If you would like to replace all the spaces in an HTML string with so that you can render it out to the browser but you also want to retain current spaces in HTML tags you can use the below method:
$inputString = '<span class="color:red">1</span> 2 3'; $outputString = preg_replace_callback("#>[^<]+<#","relSpaces",$inputString); function relSpaces($match){return str_replace(" ","'",$match[0]);}This will replace:
<span>1</span> 2 3..to look like this:
<span>1</span> 2''''''' 3Using PHP to validate an IP address
You can use the PHP code below to check if an IP address is valid or not.
$ip = ""; //enter a valid or invalid ip address here if(filter_var($ip, FILTER_VALIDATE_IP)) { // The IP Address is valid } else { // The IP Address is not valid }Wasn’t that easy!?!
What is the difference between is_home() and is_front_page()
Call me ignorant, or call me an ignorant geek, but I used to think is_home() and is_front_page() was the same thing, until I experimented with them the other day and noticed they did quite different things. Let me break them down:
is_home()
This actually is the page where all your recent posts are shown. Which means if your “home” page is set to “static” then it will be false, otherwise it will be true.
..near 'option o ON (po.option_id = o.option_id) LEFT JOIN option_description od ON (o.o' at line 1
So you’ve just installed Opencart 1.5.0 and when attempting to edit a product or category or etc you get the following error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘option o ON (po.option_id = o.option_id) LEFT JOIN option_description od ON (o.o’ at line 1
Error No: 1064
SELECT * FROM product_option po LEFT JOIN option o ON (po.option_id = o.option_id) LEFT JOIN option_description od ON (o.option_id = od.option_id) WHERE po.product_id = ‘42’ AND od.language_id = ‘1’What is 1e100.net?
So you are probably reading this because you are not sure what 1e100.net is or why you are being redirected via it when performing Google searches or using products such as youtube etc.
Perform a SiteWhois lookup
1e100.net is owned by Google and has been in use since October 2009, if you perform a whois on the domain you can see it’s registration details linked back to Google.
Perform an SiteInfo lookup
Hide all error messages PHP
PHP Error messages showing up in your web applications are a dangerous thing. Not only does it look unprofessional, but it is also a serious security concern!
Once you have completed debugging your website or web application you can place the following one liner at the beginning of your code, this will turn off error reporting and therefore make sure that no application details are spilled to your users.
error_reporting(0);If a single line of code is causing the problems it is safer to use the at symbol (@) to suppress any errors it may cause.
You can also use “or die()” to stop the execution of your code after the suppressed error in case the remainder of your code relies on that function to return a value.
In the example below we will use the “@” and “or die” to handle everything:What is xmlrpc.php?
It is a script which allows clients to make procedural calls over the net.
As it says in the name, the encoding is XML and because it is used on websites we can make the fair assessment that it uses the HTTP protocol.If we break the name down we get: XML transmition via Remote Procedure Calls.
So you are still not sure what this is all about? Read on..
Windows Genuine Advantage Notifications in a VM
Windows Genuine Advantage Notifications
I am running a Windows XP SP3 VM used for testing multiple versions of InternetExplorer through Virtualbox.
Running this wizard should be avoided if Windows is in a VirtualMachine.
Force HTTP using htaccess
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]Stop That Referrer in PHP!
Today I will show you a method to stop the traffic that a referrer site is sending your way, you may wonder why you would want to ignore traffic, after all, isn’t inbound traffic to your site fantastic no matter what?
The simple answer is “NO!”
Let me explain it in a real life situation so that you can better understand where to use this.
Understanding where to use it
Viva la 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0!
You may see this around and not have a clue what the heck it is, weirdly enough, I did..
Why “weirdly” you ask, well, because, who would be looking for something like “09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0”.
Let me elaborate..The Urban Dictionary says it like this:
“An alphanumeric string denoting a hack and insecurites in the HD-DVD coding.”Ternary Operation
If you do not know what the Ternary operator is, or do not use it while you are coding, let me be the first to tell you how much you are missing out!
The Ternary operator looks like this: “?”, that’s right, it’s a question mark!
My favourite way of using it is to shorten Conditional If Statements, so let me show you what I’m on about.
The long way:
<br /> if ($someVariable==true) {<br /> $someOtherVariable=1;<br /> } else {<br /> $someOtherVariable=2;<br /> }<br />Oops the system encountered a problem (#104)
If you get the following error while using Google’s Gmail Service (gmail.com):
Oops? the system encountered a problem (#104)
..then you should try deleting your browser’s cache and everything will be resolved.
This appears to be a local problem and not on the Google servers as data is pushed via cookies to the local machine using the web service.
In order to delete your browser’s cache in Firefox click Tools->Clear Recent History then select “Everything” in the dropdown menu and then deselect everything except for “Cache” in the below list box.
Click “Clear Now” to complete this task.How to Write Unmaintainable Code
I have come across the following article before and again came across it today, after a revised browse through, I thought I may as well add another link to it on the web for whoever ends up clicking on it!
It really is a worthwhile (in a humor sort of way) read:
http://www.freevbcode.com/ShowCode.Asp?ID=2547
Captcha Fail!
Hey, thought I’d just post this one incase anybody else sees it and thinks it’s funny.
This is not really a very helpful post like most of the others on this site, but HEY! TOUGH!
So feel free to smile if you like..
What do you know, a snippet of helpful-ness is about to appear-> This issue is usually caused by an invalid referrer! HA!
Test IE versions on any machine!
Do you do web development and are unable to test your software in old shitty versions of Internet Explorer?
If so then you may want to read on a little bit.Microsoft has got a whole bunch of virtual images you can download for FREE(not a usual Microsoft word) over here:
http://www.microsoft.com/downloads/en/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en
They contain an operating system and an install of your favourite IE version! Hooray!
Error 500 php_value .htaccess
I noticed on some server setups I could not do the following inside a .htacess file:
<br> php_value upload_max_filesize 250M<br> php_value post_max_size 250M<br>I was getting an error 500 Internal Server Error with the above code in the .htaccess file.
What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead:
<br> upload_max_filesize = "250M"<br> post_max_size = "250M"<br>Windows Directory Tree Never Finishes Loading?
I am running Windows 7 64-bit and since yesterday whenever I open “My Computer”/“Windows Explorer” (-Windows+E) the initial “showing drives” screen is frozen, so I have to use the address bar to navigate to the path I need to go.
As you can see in the picture to the left even after you have gotten to and are viewing the folder you want, the directory tree in the sidebar continues to “check” for “who knows what”!
CSS background image data: base64?
What the heck is all that Gobbledygook in the CSS?
So you have noticed that bit of css that says something like this in the CSS source-code and you have no idea what it could be?
url(“data:image/gif;base64,R0lGODlfMAMEAIABAKysrObm5iH5BAEAAAEALAAAAAAwAwQAAAJOhI+py30Bo5y02ouz3rz7D4biSJbmiabqyrbuC8fyTKPOjedHzff+DwwKh8Si8YhMKku6pvOxjEqn1Kr1is1qt7ynV8cNi8fksvmMTiMLAD4=”) no-repeat scroll 50% 0 transparentIt is a technique called Data URLs and using PHP – or your favourite server-side script – you can generate these nifty little things.
WordPress remove Subscribe to my RSS feed after posts
If you are running WordPress and have noticed a line under all your posts that says:
If you enjoyed this post, make sure you subscribe to my RSS feed!
..and if this irritates you as much as it did me, you can remove it by deactivating a plugin called Subscribe Remind.
Done!
P.S. Sorry Trevor, not trying to piss you off 😛
And then there was Google Instant!
If you have visited the Google.co.uk homepage (Yes, that’s Google UK) recently – since about the 8th of September 2010 then you would have noticed a new search feature Google is pushing called Google Instant.
Now what is so nice about Google Instant?
It is an ajax type search application that now searches using keyword ghosting and searches and returns results as you type to populate the normal search results page that has been used up until now.
[Solved] PHP’s typeof – gettype()
Quite often you may need the ability to check what type of data type a variable is.
In most programming languages this is possible to do and is usually called something like typeof().
So what is typeof in php, or typeof php you ask? In PHP there is a simple function called gettype() and it’s so easy to use.
All you have to do is pass the variable in question to gettype() as the first argument and the type will be returned.
When to use SSL?
There has always been quite a lot of heated discussion around the question of when to use SSL and when to avoid it while building websites.
I have been asked this question a few times myself and finally thought that it would be good for everybody if I just wrote an article on it explaining what the big huff was all about.
Obviously if anyone has anything to add or if you disagree with me for whatever reason, then feel free to do so below at the end of this article.IE6 PngFix in Javascript
As a web developer you will know just how much we all love hate Internet Explorer 6 – one of the most dreaded browsers and browser versions that still exists in the deep dark corners of the interwebs – and you will probably have figured out that it doesn’t play well with PNG images.
So here is how you can resolve this problem. It’s not as nice as an actual browser that can render PNG images natively, but it does work.
MSSQL Select Not Null
I mainly use MySQL these days, so get screwed over for a few minutes when I have to do something in MSSQL that is slightly different when it comes to it’s custom syntax.
If you want to show all entries in a specific column and where it is not Null then you can do the following:
SELECT [columnNameHere] FROM [databaseNameHere].[dbo].[databaseTableNameHere] WHERE [columnNameHere] IS NOT NULLWhat is __utma, __utmb, __utmc, __utmz ?
__utma, __utmb, __utmc and __utmz are 4 cookies created by Google Analytics, for a detailed and very informative read, go here and here.
How to Close Bandmix Account
If you want to close a Bandmix account, then:
- Login to bandmix.co.uk
- Go to Options – http://www.bandmix.co.uk/account/options/
- Click Decline Service
- Then click the button called Decline Service at the bottom.
- Click “OK” to the verification popup.
Account closed!
Google Redirect Virus Fix!
Now this is an annoying one.
You go to any of google’s sites including any site that has google-analytics.com javascript included in it’s body and BOOM! ..either you get redirected to a bullshit search page you didn’t ask to go to or the browser shows a blank white screen while apparently analytics loads..It turns out this is actually a virus that infects routers!
There are “short-lived-ways” to solve this problem and the one I adopted was to add the following into a windows batch file and run it every bloody time just before doing a google search.
Chromium Operating System
As many of you may know, Chromium is an opensource project that is basically an Operating System built on Linux and is just like working in Google’s Chrome web browser.
I decided to take a look at it today and went and downloaded the developer sneak release.
It came all boxed up in a 764,994KB (764MB) VMDK Virtual Machine Harddisk file.
When it finished downloading I was sadly quite excited as I love trying out new Operating Systems and goodies – being a geeky kind of guy like most guys out there – and after hardly any setup at all it started up.Super Easy Email Validation AS2
I needed a quick and easy way to check for the basics of an email address.
Does it contain “@” and “.” symbols.
This is by no meals a foolproof method, so don’t use it for anything big, but if you want to just do a quick test then here you go:
var email:String = "[email protected]"; if (email.indexOf("@")!=-1 && email.indexOf(".")!=-1) trace("false"); else trace ("true");VLC Cache Rant
The first time this ran it took for freakin’ ages!
This should take less than a few minutes
What the hell is that supposed to mean? Less than a few? 73 minutes perhaps?
Rant over..
ODBC SQL Server Memory General Network Error
Microsoft OLE DB Provider for ODBC Drivers error ‘80004005’
[Microsoft][ODBC SQL Server Driver][Shared Memory]General network error. Check your network documentation.
/site/path/to/script/aspfile.asp, line #..and that’s what it throws you!
At about this point you may want to scream, or just be a tad annoyed by that damn machine running your site.
Basically your server is either one of two things, and those are:- Overloaded
- Server is “Just Plain Shit”
The error is caused because the script is struggeling to connect to the database server – may it even be in the same damn box with same IP and all – and sometimes fails, so shows you it’s overloaded groan.
XML cannot be the whole program
What the hell does that mean?
You can get this error thrown up in your good old trusty Firebug console.
It expects a script to be returned as an ajax type datatype.So all you have to do is change your datatype to output as XML.
Mocha Java Decompiler Download
Mocha is a Java Decompiler and is 100% FREE to use.
The readme.txt file in the Mocha distribution offers the free usage license:
The distribution archive (file “mocha-b1.zip”) may be distributed freely, provided its contents (“mocha.zip” and this file, “readme.txt”) are not tampered with in any way.I am pleased to be able to make the Mocha distribution available under those terms:
mocha-b1.zip (121K)
You can visit the alternative download location here.
EAI_NODATA
Error message: Connection attempt failed with “EAI_NODATA – No address associated with nodename”.
The above error occured while using Filezilla (Ftp Client), it either means that you do not have an active internet connection, OR it means that you need to clear the private data because the connection to the server was lost while an active FTP connection was still present. Upon reconnection to the server (which is sometimes automatic) you will receive the EAI_NODATA error.
1180 Call to a possibly undefined method navigateToURL
1180 Call to a possibly undefined method navigateToURLIf you get the above error when trying to run your flash actionscript 3 file, you are obviously trying to use the
navigateToURL()function but have not imported the flash.net library code.The following code before everything will correct the problem.
import flash.net.*;..or a more of a direct unbloated method is as follows:
import flash.net.navigateToURL;Test Your Password Strength
I came across this site today and it’s quite an interesting one as it works out the approximate time it would take a desktop pc to crack the password.
Check it out here.
How to use a Timer in Actionscript 3
It is really easy to create a Timer in Actionscript 3.
Instantiate the Timer Class and pass a time in millions of 1000 to it to work in seconds.
var myTimer:Timer = new Timer(1000);Setup an event listener to call a function.
myTimer.addEventListener("timer", myTimerEventHandler);Start the Timer.
myTimer.start();Start the Timer.
function myTimerEventHandler(event:TimerEvent):void { trace(myTimer.currentCount+" seconds have passed."); }So altogether we have this.
var myTimer:Timer = new Timer(1000); myTimer.addEventListener("timer", myTimerEventHandler); myTimer.start(); function myTimerEventHandler(event:TimerEvent):void { trace(myTimer.currentCount+" seconds have passed."); }Now you know how to use a Timer in Actionscript 3.
Google Background Image
Google now allows you to add a background image to the google homepage to apparently make it more, like, home.. hmmmm
Just by clicking the button at the bottom left hand corner it allows you to either upload an image or select an image from google.
For indepth instructions as per Google, check this page out: http://www.google.com/support/websearch/bin/answer.py?answer=180720&hl=en
How to Hire a Hacker
I came across a very interesting and quite funny read, take a look here for How to Hire a Hacker: http://www.setec.org/hirehacker.html
If the program is already running, close it before attempting to run.
Launch Failed!
If the program is already running, close it before attempting to run.
I don’t know how many times I have gotten this error message while trying to Run a project in Adobe Flash Builder.
For all of you stuck with this message and unable to ever get your projects going, there is quite a simple fix to this.
All you need to do is open up Task Manager (Ctrl+Shift+Esc) and click on Processes, then “End Process” on any instances of “adl.exe” you find. Only one adl.exe instance can run at any given time.
Random Number In ASP for no Flash Caching
This is an example of how to create a random number in Classic ASP in order to append to a swf file so that the browser does not cache the swf file.
<% Dim SwfRndNum Randomize SwfRndNum = Rnd %>You can then add it to your swf embed code as follow, bear in mind that I am only showing the snippet around the swf file name and not the entire embed code.
Why we don’t choose MSSQL!
Everybody always raves how great Microsoft SQL Server is, and how much data it can hold, and how much bigger it’s “package” is than your own.
But the truth is that I hate it with a passion!
I use RDBMS‘ on a daily basis and never used to hate MSSQL so much until recently when I had to modify a very large site that was built in Classic ASP(yuck) and MSSQL.
How Do You Fire A Client?
How do you fire a client?
Let’s face it, some clients can be a real nightmare.
There are a whole bunch of tell-tail signs that a client is going to be a major problem for you shortly after or sometimes during your first interaction with them. This can be a phone call, a few emails or worst of all, a face to face meeting.
Remember that you need to be selective when it comes to work you take on, as a bad client can cause more trouble than they’re worth. They can even bankrupt you if you’re not careful.
How to get ‘how many days in February’ using Javascript?
It is quite handy to have a function that can tell you how many days there are in February due to the leap year shift of either 28 or 29 days.
Below is a function created in Javascript to return the exact amount of days according to the year given:function daysInFebruary (year){ return (((year%4==0)&&((!(year%100==0))||(year%400==0)))?29:28); }Weird Pagination on a Google Page
Not sure how long this one will last, but for now:
Go to: http://www.google.co.za/search?q=MFI/06/ASA-778658&hl=en&start=0&sa=NIf you scroll to the bottom, there are 4 pages (pagination), press Next, now there are only 2, WEIRD HUH!
Actionscript 2 – PHP Data Transfer
In the below example we will use Actionscript 2 to call a remote PHP file that will return data to it.
It is a simple way of transferring data between the server and client.Actionscript 2 Code:
callRemoteFile = function(ourVariable:String) { var result_lv:LoadVars = new LoadVars(); result_lv.onLoad = function(success:Boolean) { if (success) { if (result_lv.message=="success") trace("done! "+result_lv.returnValue); else trace(result_lv.message); } else { trace("Error connecting to server"); return false; } }; var send_lv:LoadVars = new LoadVars(); send_lv.ourVariable = ourVariable; send_lv.sendAndLoad("/example/file.php", result_lv, "POST"); } callRemoteFile("some text here");PHP Code:
<?php if (isset($_POST)) echo "a=1&message=success&returnValue=".$_POST["ourVariable"]."&b=2"; else echo "a=0&message=failed&returnValue=nothing&b=1";Unique Random Numbers in PHP
If you would like to show random numbers using PHP you can do this:
<?php $min = 1; $max = 100; $total = 100; $arrItems = array(); while ( count($arrItems) < $total ) { $item = mt_rand($min,$max); if (!in_array($item,$arrItems)) { $arrItems[] = $item; echo $item."<br />"; } }HTML mail() Sending as Plain Text
$to = "[email protected]"; $subject = "SUBJECT"; $message = "<b>MESSAGE</b>"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: Mailer ' . "\r\n"; mail($to, $subject, $message, $headers);The above code does not always send emails in HTML as it should, it turns out there is a PHP Bug (http://bugs.php.net/15841) that comes into play with QMAIL and carriage returns.
If this is the case you should replace “\r\n” with a “\n” only.Turbo C++ in DosBox for Windows 64bit
I had to compile a C++ application under a DOS environment and was running Windows 7 64bit.
Firstly, Turbo C++ is a 32 bit x86 application and therefore will not run when initialised from an x64 environment.
This can easily be solved by installing the DOS Emulator called DosBox. One can then mount the Turbo C++ folder as a drive and install it under a subdirectory.
e.g. mount c c:\PathToMyTurboCppDirectory\Once in there it’s quite easy to open and compile the source code, but good luck to anyone that tries to write anything from scratch, it’s really painful and half the keys are not mapped in the DosBox, eventhough you can press Ctrl+F1 to open the Keymapper.
Case Insensitivity with .htaccess files
If you have an
.htaccessfile to control the flow of URI’s on your site you may want to look at adding a nice little “case insensitive” feature to each line/item.So an example of a line of .htaccess without any case insensitive bells and whistles looks like this:
RewriteRule ^AndrewOdendaal$ index.php?go=2964We add our Case Insensitive feature by just adding a [NC] to the end of the line, like this:
Actionscript2: Split string by line length with & without word-wrap
Split string into sentences by max line length.
This uses a character array but doesn’t use word-wrapping.var personalMessage: String = "You got this far so we reckon that you could be curious enough to learn a little more, we?ll contact you shortly to answer any questions you may have."; _root.myArray = new Array(); _root.myArray = personalMessage.split(""); _root.mySentences = new Array(); var currentCharCount: Number = 0; var currentCharItem: Number = 0; var currentCharString: String = ""; var maxLength: Number = 65; for (var i = 0; i & lt; _root.myArray.length; i++) { if (currentCharCount & lt; maxlength) currentcharstring = "" += "_root.myArray[i];" if = ""(currentcharcount = "=maxLength" || = "" currentcharitem = "=(_root.myArray.length-1))" { = "" _root.mysentences.push(currentcharstring); = "" currentcharcount = "0;"; = "" } = "" currentcharcount++; = "" currentcharitem++; = "" trace(_root.mysentences.length); = "" trace(_root.mysentences[0]); = "" trace(_root.mysentences[1]); = "" trace(_root.mysentences[2]); = "" [ = "" code ] = "" this = "" outputs = "" the = "" following: = "" [code = "" lang = "c" ] = "" 3 = "" you = "" got = "" far = "" so = "" we = "" reckon = "" that = "" could = "" be = "" curious = "" enough = "" to = "" learn = "" a = "" little = "" more, = "" we? ll = "" contact = "" shortly = "" answer = "" any = "" que = "" tions = "" may = "" have. = "" split = "" string = "" into = "" sentences = "" by = "" max = "" line = "" length = "" and = "" use = "" word - wrapping. = "" var = "" personalmessage: string = "You got this far so we reckon that you could be curious enough to learn a little more, we?ll contact you shortly to answer any questions you may have." _root.myarray = "new" array(); = "" ");=" " _root.mysentences=" new " currentcharstring:string=" " maxlength:number=" 60; " for=" " (var=" " i=" 0; " i<_root.myarray.length;=" " i++=" " )=" " (currentcharstring.length<maxlength)=" " " = "" ";=" " ((currentcharstring.length=" ">= (maxLength-1)) || (i==(_root.myArray.length-1))) { _root.mySentences.push(currentCharString); currentCharString = ""; } else currentCharCount++; } & lt; /maxlength)> trace(_root.mySentences.length); trace(_root.mySentences[0]); trace(_root.mySentences[1]); trace(_root.mySentences[2]);This outputs the following:
Search and Replace Anchor Href using Javascript
I have a site that is under development and it was made really badly so I needed a quick way to replace all anchors on page to the relevant path.
The problem is because it was a testsite that lived away from the public facing domain, the anchors had to be changed because they were all coded in as absolute paths.
I included a JavascriptDebug file and put the following in there:
Error 29506 while installing SQL Server Management Studio Express
I was trying to install Microsoft SQL Server Management Studio Express (what a long name) on a machine and kept getting error 29506 right near the end with a Rollback action thereafter.
To get this program installed you will need to run Command Prompt as Administrator and then run the MSI (installer) from there.
Navigate to
C:\Windows\System32\then right click on cmd.exe and select Run as Administrator. Once the console has loaded, you can “cd” to the directory and then run the installer from there.Swap HTML Elements Using Javascript
It is quite easy to use javascript to swap between divs or any other html dom elements.
Using the function below you can pass the id of the element to show and to hide.function swapDivs(show, hide){ document.getElementById(show).style.display = "block"; document.getElementById(hide).style.display = "none"; }A PHP Mail Class
Below is a Mail class I created in PHP, it requires 4 arguments on initiation of the class via the constructor and uses the method ->send() to send the created mail once complete.
class Mail { var $to; var $subject; var $content; var $headers; function Mail($to, $subject, $content, $from){ $this->to = $to; $this->subject = $subject; $this->content = $content; $this->headers = "Content-type: text/html; charset=iso-8859-1\r\nFrom: $from"; $this->content = "".$content.""; } function send(){ return mail($this->to, $this->subject, stripslashes($this->content), $this->headers); } }iTunes keeps maximizing!
Oh my goodness, this can be an annoying issue with iTunes.
The problem is: iTunes will restore itself or maximize itself all the time every 20 or so seconds without being clicked on, it will also get main focus and whatever you were doing will have to wait!
I solved this by right clicking on the iTunes program icon where I launch it from and selecting Properties, then selecting “Compatibility” then making sure “Run this program as an administrator” was checked.
Replace newline break in Excel
Ever needed to find & replace the newline character in a large excel document?
In the Replace Dialog (Ctrl+F)
Find: Hold down [alt] and type 010 on the numeric keypad.
Replace: Replace with a space " " (without quotes)PHPExcel Class Usage
I just finished adding an export xls (excel) export feature to a web application.
I used the PHPExcel Class from CodePlex, its really great to work with – as far as the world of exporters go that is.
In the example below the “exportCheckpoints” function requires an imploded string seperated as “|||||”. Hopefully it gives an example of how easy it “could” be to export something from mysql to excel using php.
unexpected T_IF
Getting “Parse error: syntax error, unexpected T_IF” ?
Check if the preceeding line ends with a ;Worst Websites of All Time
http://www.theworstwebsite.com/ – beware, alert boxes coming!
http://www.pixyland.org/peterpan/
Think you’ve found the worst website of all time?
Post it below!
Set line leading / line spacing in flash actionscript 2
This is how to add text leading using Actionscript 2 for Flash.
var txtFormat:TextFormat = new TextFormat(); txtFormat.leading = 5; // change this to whatever you need it to be ttt.setTextFormat(txtFormat); ttt2.setTextFormat(txtFormat);There is also a GUI way of doing this:
Select your textfield and and under the paragraph section, set the top/right hand icon (Line Spacing) to whatever you like.
MySQL Main Query Types used in PHP to select, insert, update and delete data
MySQL Main Query Types
SELECT
SELECT * FROM tablenameINSERT
INSERT INTO tablename (col1, col2, col3,..) VALUES (val1, val2, val3,...)UPDATE
UPDATE tablename SET `col1`=`val1`, `col2`=`val2`, `col3`=`val3`,...DELETE
DELETE FROM tablename WHERE `col4`=`val6`Note
You will use a lot of WHERE clauses as well along with the above.
e.g.
SELECT * FROM tablename WHERE `id`='15'In PHP
Calling to MySQL is really easy in PHP, just use the mysql_query() function.
e.g.
mysql_query("SELECT * FROM tablename") $query = mysql_query("SELECT * FROM tablename"); while ($result = mysql_fetch_object($query)) { echo $result->aColumnNameInMysql; }Connect to mysql database from php
If you need to connect to a mysql database from php you can do it like this:
<?php $DBH = 'localhost'; $DBU = 'root'; $DBPWD = 'password'; $DBN = 'petstore'; $conn = mysql_connect($DBH, $DBU, $DBPWD) or die ("Error: Could not connect to database."); mysql_select_db($dbname);This allows you to make a connection to the mysql database and gets it ready for you to make queries and manipulate the data.
htaccess file and error 500 internal server error
I have a question for anyone that can answer it:
I create an .htaccess file in the root of a subdomain, but if I enter either of these two lines I get an erro 500 Internal Server Error:
php_flag magic_quotes_gpc off php_flag register_globals offAny suggestions anyone?
Quake 4 – Fatal Error: could not create destination file
If you get an error message similar to this one when trying to run Quake 4…
Fatal Error: could not create destination file C:/Program Files (x86)/id Software/Quake 4 Multiplayer Demo/q4mp/gamex86.dll
…then you should run the exe as Administrator.
So Right-click, “Run as Administrator” and all will be sorted.
phpMyAdmin – Invalid field count in csv input on line 1
I was trying to import a massive csv dataset into phpMyAdmin and it kept throwing error:
Invalid field count in csv input on line 1This is quite annoying as I followed all the usual steps as per normal.
To solve this I had to do the following:
- Import
- Browse for your CSV file.
- Select CSV using LOAD DATA (rather than just CSV)
- Change “Fields terminated by” from “;” to “,”
- Make sure “Use LOCAL keyword” is selected.
- Click “Go”
Done!
Choosing a programming IDE
This is somewhat of a debatable topic, but it has come up a lot of times without any real final clarity, so I will try and cover it all.
Lets begin by explaining exactly what an IDE is and then we can move onto the more debated areas of choosing the right one for you.
An IDE stands for “Integrated Development Environment” and is often used by programmers when creating their applications. It can be quite a different thing according to lots of factors including language, preference and perhaps a biased opinion.
Double border in CSS
CSS allows you to add a border to almost all html elements. This is one of many CSS techniques you can use to enhance your web pages, along with using CSS background image data for more advanced styling.
If you would like a double border you can use CSS like this:
style="border:double"For more CSS styling options and techniques, you might also be interested in exploring how Google uses background images on their pages.
[Exception… “Could not convert JavaScript” nsresult: “0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)”
What the heck is..
uncaught exception: [Exception… “Could not convert JavaScript argument arg 0 [nsIDOMHTMLDivElement.appendChild]” nsresult: “0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)” location: “JS frame :: PATH_TO_MY_JAVASCRIPT_FILE :: THE_METHOD_NAME :: line #” data: no]
For me it was just an appendChild() that was causing the problems. You can always try the innerHTML+= way if all else fails 😉
Error 1046: Type was not found or was not a compile-time constant: Event.
Error 1046: Type was not found or was not a compile-time constant: Event.You need to import the Event class!
import flash.events.EventAdd a date to a date in Actionscript 2
I needed to work out a date range according to the date 3weeks away from the current date.
After a bit of thinking, I found that it’s actually quite easy to achieve.var theDate:Date = new Date(); dateDay = theDate.getDate(); dateMonth = theDate.getMonth(); dateYear = theDate.getFullYear(); var theDate2:Date = new Date(dateYear,dateMonth,dateDay); theDate2.setDate(theDate2.getDate() + 21); dateDay2 = theDate2.getDate(); dateMonth2 = theDate2.getMonth(); dateYear2 = theDate2.getFullYear();The above code gets the current date and adds 21days/3weeks to it.
Remember that if you use getMonth to output the final month number, you will want to add 1 to it as it starts at 0;
Example:
dateMonth2 = theDate2.getMonth()+1;
So you would do it like this:
theDate2.getDate() +"/"+ (theDate2.getMonth()+1) +"/"+ theDate2.getFullYear();Add a month to selectable date range – Date Chooser – Actionscript 2
I have been working on a project where I need to select a date range starting today and ending a month from now, so the user cannot select anything in the past or over a month from now.
This is how I did it:
There is an instance of DateChooser on the stage with Instance Name “calDate”.
var todayDate:Date = new Date(); dateBeginDay = todayDate.getDate(); dateBeginMonth = todayDate.getMonth(); dateBeginYear = todayDate.getFullYear(); if ((todayDate.getMonth()+1)==12) { dateEndDay = todayDate.getDate(); dateEndMonth = 1; dateEndYear = todayDate.getFullYear()+1; } else { dateEndDay = todayDate.getDate(); dateEndMonth = todayDate.getMonth()+1; dateEndYear = todayDate.getFullYear(); } calDate.selectableRange = {rangeStart: new Date(dateBeginYear, dateBeginMonth, dateBeginDay), rangeEnd: new Date(dateEndYear, dateEndMonth, dateEndDay)}hitTest and Actionscript2
if (mc.hitTest(_root._xmouse, _root._ymouse, true))) { trace("hitTest Run"); }127.0.0.1:4664 and Google Desktop Search
Recently I checked my website stats and saw I had a few hits from “127.0.0.1:4664” and wondered to myself, what the heck is that? Am I looking at my own site from a localhost? Why am I getting backlinks from my local computer to my site.
After searching around a bit I found out that port 4664 is used by Google Desktop Search and when I typed in certain queries into Google it also returned items from my desktop search.
Limited numeric input in flash actionscript 2 textfield
If you want to only show numeric characters in a textfield in flash actionscript you can use the following code:
myTextField.restrict = "0-9";Embed pound symbol (£) in flash textfield
If you use a dynamic textbox in Flash and you want to embed the British Pound symbol (£) then you will want to also embed the “Latin I” glyphs with your textfield.
Enable / Disable Cursor Hand in Actionscript 2
If you have a movieclip that by default has the hand cursor showing on RollOver and you don’t really want this, you can disable it by doing the following:
myMC.onRollOver = function() { this.useHandCursor=false; }So the main code here is:
this.useHandCursor=false;Falsedisables it andtrueshows it.USB Device Not Recognized! in Windows
Believe it or not, this one is super easy to fix!
It’s actually a temporary problem with your motherboard, all you need to do is:
- turn off your computer
- if it’s a desktop then unplug it from the wall/powersupply
- if it’s a laptop then remove the battery
- let it sit for a minute
- plug it all in again
- reboot
- VOILA!
No need to uninstall/reinstall drivers or anything!
Calling event functions from movieclips in actionscript 2
In a flash movie I usually have a frame of actionscript that controls all elements in the file to keep everything in one place.
Sometimes I have an onPress(etc) function that refers to something happening in the scene when something is pressed, but what happens if we want another element to refer to that event for some reason?
Here’s an example of that code without anything “flashy”:
_root.myMC.onPress = function() { //code goes here }..and here’s our slightly more intersting flashy version:
Sudo install OpenGL & SDL on Ubuntu
A quick and easy way would be to type the following in one line with single spaces in the Terminal.
This way of installing OpenGL and SDL libraries only applies to Ubuntu.sudo apt-get install nvidia-glx-new-dev libglew1.4-dev libsdl1.2-dev libsdl-ttf2.0-dev libsdl-image1.2-dev libsdl-mixer1.2-devHow To Modify Hosts File On Windows
The hosts file is located at the following address:
C:\windows\system32\drivers\etc</span>
or
%systemroot%\system32\drivers\etc</span>
But you will need to open Notepad with “Run as Administrator” first and then open it through there otherwise it will give a permissions problemGet all directories in PHP
I think this may be the fastest way to get a list of all the directories in a given folder/directory using PHP.
$directories = array_filter(glob('*'), 'is_dir');..and of course, you can also add a path to it if you need to:
$directories = array_filter(glob($myPath.'*'), 'is_dir');Security error: securitySandboxError with Flash
You have a flash uploader and you get this error:
security error: securitySandboxError
This means that the flash is not trusted by the domain and you have to place an xml file in the root of the domain.
The file is called “crossdomain.xml” and this is what should be inside it:
Solved! 😉
Component Inspector in Flash has ISSUES!
I discovered a very annoying bug in the Flash IDE a little while ago, and it has happened to me quite a few times.
Today it happened again and so I write this post..
While in the Flash IDE you select a component on the stage, then you click “Component Inspector”.
This opens up into a modal window which is nice and everything BUT….
…..if you then give focus to another program and then try click back into flash, it hides the “Component Inspector” modal window but still keeps focus on it, so basically, you can’t use the program(Flash IDE) / save your file / or even close the program!Close/Delete Google Checkout Account
I have used Google Checkout to receive payments in the past and have had problems with some clients not paying and blaming it on Google Checkout that the money did not go through (like the guys over at Peartree DMS).
I decided that this account was not worth the trouble anymore and wanted to close my account.
I looked online everywhere and couldn’t find where to close the account – after quite a while I found how to do it, so here is how to close/delete/remove your Google Checkout account:
Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource
Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource
You have just gotten a warning when trying to check if an inserted row was successful but when calling mysql_affected_rows(mysql_query(“INSERT INTO……”)) you get a warning telling you that the supplied argument is not a valid MySQL-Link resource.
This is because mysql_query INSERT actually returns true or false and not a resource id.
So rather do this:
if (mysql_query(“INSERT INTO…”))
Capitalize First Letter in Word – Actionscript 2
You have a string and you want to capitalize the first character but have the rest of the word in lowercase.
DO THIS!
myStringVar = myStringVar.substring(0, 1).toUpperCase()+myStringVar.substring(1);HP Pavilion Laptop Madness
I have got an HP laptop and have started experiencing problems with it starting up for the past few months, it is only about 1.5years old and is supposed to be a decent one.
It is an HP Pavilion dv9700 by the way..
Today the damn thing just didnt want to startup and eventually after trying every trick in the book I got it to boot into Degugging Mode in Windows Vista.. What a nightmare!!!!
Why you should use OpenGL and not DirectX
Below is a very interesting article I found that proves all the myths about DirectX being better than OpenGL, a very well written paper describing it best.
Thanks for that guys at Wolfire.com!
http://blog.wolfire.com/2010/01/Why-you-should-use-OpenGL-and-not-DirectX
What does __FILE__ in php mean?
In php there are a few magic constants and I find FILE to be a very useful one.
It returns the full path and filename of the file in question.
Take a look at the PHP Manual – Magic Constants for more information on the others.
Woopra Failed to Connect?
I have used Woopra for a few months now and have started seeing this warning/error almost everyday now:
Could not enable live functionality at this time. Click to reconnect.
If you click the text/warning/error it seems to go away… Anybody konw what’s really going on under the cover?
What happened:
It turns out Woopra have upgraded their desktop application and will get to the web based application once they are done with everything else. The new structure broke the way the web based application worked, so they have removed it for the moment.
Change PHP Session Time
The default time for a php session is 1440 seconds.
You can change it by doing the following:
ini_set("session.gc_maxlifetime",1440);You can obviously adjust the second parameter (1440) to anything you like to change the timeout limit.
Stop mouse click in browsers
There have been multiple ways to stop your user/s from right clicking on your site, but many of them now fail due to the way firefox’s contextual menu loads.
Below is an example of how to do it:
function _c(e) {if (document.all) {if (event.button==2||event.button==3) {return false;}} else {if (e.button==2||e.button==3) {e.preventDefault();e.stopPropagation();return false;}}if (e.which) {}}if (document.all){document.onmousedown=_c;}else{document.onclick=_c;document.ondblclick=_c;}..and here is the full working example in a webpage:
<script><br /> function _c(e) {if (document.all) {if (event.button==2||event.button==3) {return false;}} else {if (e.button==2||e.button==3) {e.preventDefault();e.stopPropagation();return false;}}if (e.which) {}}if (document.all){document.onmousedown=_c;}else{document.onclick=_c;document.ondblclick=_c;}<br /> </script> testerMicrosoft apps never care!
I often seem to have this issue when dealing with Microsoft software.
You click “Cancel” and it just carrys on going, so you click it again a few more times and instead of it just stopping in it’s tracks, decides to rather tell you it’s cancelling and then shows a cancelling dialog box for the next 10 minutes!
Cummon guys, that’s not very professional!
Place HTML Div on top of Flash
If you have ever tried to place a div or similar HTML element on top of a swf flash object you will know that it always tries to take precedence.
You will need to do the following:
In the code for the flash in the embed area add:
wmode="transparent"If you are using SWFObject to insert swf files you can do the following:
<script type="text/javascript"> var so = new SWFObject("movie.swf", "mymovie", "400", "100%", "8", "#336699"); so.addParam("wmode", "transparent"); so.write("flashcontent"); </script>Get current working directory of php script/application
$myPath = realpath(dirname(__FILE__));or
$myPath = getcwd();Stage align and Stage scale in actionscript 3
If you want to position the flash top/left and not have it scale when you resize it’s bounding box window, you can set the following code.
stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE;For full documentation from Adobe take a look here.
Error 406?
So you received an error 406 while trying to upload a file and you have no idea to fix it!
Create an
.htaccessfile in the root of your local website and add the following into it:<IfModule mod_security.c> SecFilterEngine Off SecFilterScanPOST Off </IfModule>Firefox error in FeedProcessor.js
[Exception… “Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIChannel.contentType]” nsresult: “0x80040111 (NS_ERROR_NOT_AVAILABLE)” location: “JS frame :: file:///C:/Program%20Files/Mozilla%20Firefox/components/FeedProcessor.js :: FP_onStartRequest :: line 1440” data: no]
file:///C:/Program%20Files/Mozilla%20Firefox/components/FeedProcessor.js
Line 1440So what the heck does that all mean?
Basically, there is an exception error on like 1440 of the local Firefox javascript file “FeedProcessor.js”.The line in question is as follows:
channel.contentType = “application/vnd.mozilla.maybe.feed”;
The whole section of code reads as follows:
// nsIStreamListenermySQL select multiple ids
SELECT * FROM tablename WHERE `active`='1' AND `id` IN ('107' , '125' ) ORDER BY `id` DESC LIMIT 12`Force Download in PHP
This script works in all browsers, including Internet Explorer! 🙂
if (strstr($_SERVER['HTTP_USER_AGENT'],"MSIE")) { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application-download"); header("Content-Disposition: attachment; filename=\"".basename($filename)."\";"); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".@filesize($ab_file)); set_time_limit(0); } else { header("Content-type: application-download"); header("Content-Length: ".filesize($ab_file)); header("Content-Disposition attachment; filename=".$filename); } readfile($ab_file);Remove an onRelease Handler
After creating a onRelease handler in Actionscript 2 as follows:
myMovieClip.onRelease = function() { doWhatever(); }..you then want to remove the handler for whatever reason, you can remove it like this:
delete myMovieClip.onRelease;shortText function toggler in php
I often have to show a shortened version of a news item and then a link to show the entire news article or whatever.
Here’s a way to get that short text!
function shortText($text, $length) { if( strlen($text) > $length ) return substr(preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $text), 0, $length)."?"; return preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $text); }PHP – file() lines
$lines = file('all-words.txt'); foreach ($lines as $line_num => $line) { echo "Line number ".$line_num; }Windows Live Writer – Beta2
Start writing content to your blogs from your Windows Desktop now.
No need to login to your wordpress backend to post items anymore, there is now a decent desktop application that allows you to do exactly that!
I have looked at it before but not until recently when Beta2 came out did I gain more interest for it.
The WordPress functionality added is what got me going and now I am able to post directly! Excellent 🙂
Reported Attack Site!
What the heck is that?
So you’ve just visited a website using Mozilla Firefox and this message has popped up telling you that the site looks suspicious.
Usually the site has been marked as a possible virus containing website and Firefox will show you this message attempting to protect itself against Malware, Spyware or other forms of Viruses.
There are occasions when this is mearly a warning and not to be taken as concrete evidence of viruses or impending browser/computer doom!
Simple HEX Colour Values
Actual Display Colour HEX Colour #000000 #FF0000 #00FF00 #0000FF #FFFF00 #00FFFF #FF00FF #C0C0C0 #FFFFFF Send Email PHP Function
Ever find yourself typing the headers into the
phpmail()function over and over again?Try using a standard function and calling it when you need to send mail.
function sendEmail($subject,$content,$from,$to){ $header = "Content-Type: text/html; charset=iso-8859-1\nFrom:$from"; if( mail($to, $subject, $content, $header) ); }mySQL Development Tools
I came across a very interesting article about mySQL Development Tools.
http://www.smashingmagazine.com/2009/03/25/mysql-admin-and-development-tools-round-up/
1180: Call to a possibly undefined method getURL. Actionscript 3
Hello all actionscripters, you can’t use getURL anymore in Actionscript 3.
Below is how you should now start doing it:
var request:URLRequest = new URLRequest("/"); try { navigateToURL(request, '_blank');} catch (e:Error) { trace("Error occurred!");}Online Flash IDE Anybody?
Anyone up for an online Flash IDE?
Take a look at this:
http://antimatter15.com/ajaxanimator/build/Nice work!
Papervision Event Listener Idea
The problem:
While working on a Papervision3D Flash Project I had a problem where a back button that sits above the 3d canvas and acts as a main navigational item was required to change Events according to where the site was in 3d space at the time.The solution:
Everytime I’m about to add a new EventListener to the back button movieclip I call the function “delBB()” and then add my event listener using addBB(with the event here).Don’t cache my swf files!
I often have issues where ‘dumb browsers’ cache my published swf files and when they dynamically populate they don’t always update.
This is SUPER annoying and I have found a solution.
I will demonstrate the technique with a LoadsVars example
var nc = Math.floor(random(1000000) / random(1000)); var send_lv:LoadVars = new LoadVars(); send_lv.sendAndLoad(_root.siteURL+"profile.php?action=showallimages&nc="+nc, result_lv, "POST");So let me describe what is happening here.
The really ‘dumb browsers’ like IE7 in this case decide that seeing as the URL in question has the exact same name, it will be clever and just use the last version it saw and be totally lazy and not attempt to get the data again. But the really stupid part about this is that most of the time the results are DYNAMIC and will always return a different result.
Clear an array in Actionscript 3
I personally really like this way of clearing an array’s elements:
Declare your array to use:
var myArray:Array=new Array();Add elements:
for (var i:Number;i<10;i++) { myArray[i] = "an item"; }Clear the array:
Change combobox font size in Flash Actionscript
Ever needed to change the font size of a standard flash combobox component?
You will need to give it an instance name e.g. “myCombobox” and then add the following code:
myCombobox.setStyle("fontSize", 10);Wordwrap that PRE!
Ever used a
<PRE>in a limited width div container? You will notice that the line gets cut off almost as if word-wrap was not enabled.To correct this you can add the following code into your CSS file.
pre{ white-space: pre-wrap; /* CSS2.1 compliant */ white-space: -moz-pre-wrap; /* Mozilla-based browsers */ white-space: o-pre-wrap; /* Opera 7+ */ }This code was originally found somewhere else online but I found it really useful so reposted it!
If you’re the original author then comment and let us know 🙂Barclays ePDQ Payment Gateway
Hello all!
Today we will be talking about Barclays online payment gateway valled ePDQ.
You can take a look at what they have got to say by clicking here to view Barclays’ site or you could keep reading 🙂
Well, for all you php guys out there, this post if for you!Barclays ePDQ encrypts your data string of products in your basket and returns a result that is sent with your HTML form on your site.
BrainWHAT? programming language
I came across a programming language today that I have never heard of. Go take a look over here:
http://en.wikipedia.org/wiki/Brainfuck
Transparent swf in html
So you have now placed a swf file into your html page and you want to be able to see through it.
Lucky for you, this is a very easy thing to do!
The following code does the trick:
<object data="flash/home_side_left.swf" type="application/x-shockwave-flash" width="40px" height="550px"><param name="movie" value="flash/home_side_left.swf" /><param name="bgcolor" value="#ffffff" /><param name="wmode" value="transparent" /><param name="allowScriptAccess" value="always" /></object>Notice that by just adding the
wmodeand setting it as ‘transparent’ does everything for you!Constant updates?
I just hate it how everything always wants to update… and then restart all the damn time!
First things first:
This pops up telling me it’s doing a 309.6MB Adobe Reader Update! Which to me is just crazy… Surely the constant updates shouldn’t be a million times larger than the actual initial install file for the application?
I just click Cancel and then do this..
Not a minute later and this little guy pops up!
Will it ever end????Share the mouse and keyboard!
A very interesting project I found this morning, take a look at this one!
http://synergy2.sourceforge.net/What is CWS>+?
So what the heck kind of file starts with the characters “CWS>+” ?
That would be a flash swf file!
Papervision error 1046
Error: “1046: Type was not found or was not a compile-time constant: InteractiveScene3DEvent.”
I got this this morning when I opened up a project I have been working on. I was using the Flash IDE to compile and FlashDevelop to code in as I am not the biggest fan of the Flash IDE for coding in….. Who is? Right?
Anyways… I tried to publish my swf and I got loads of errors like the one above. So after looking into what was going on I discovered that half of my papervision classes were missing! How the heck that happened I have no idea, as I store them per project basis and not as one standard import.
How to Save a Dreamweaver document as UTF8!
Today I tried to save arabic text inside a javascript file and on saving encountered a dialog box asking me to first convert the document to UTF8.
Why it didnt just do it for me I’ll never know, so I had to do it myself.
If you encounter this then do the following to convert the document:
- Click on the Modify main menu item and select Page Properties.
- Change the Encoding/Document Encoding dropdown to say “Unicode (UTF-8)” or “Unicode 4.0 (UTF-8)”
- Click OK
- Save the document
16000 Limit!
Today I discovered that Flash truly has a limit!
- 16,000 frames: Exceeding this limit causes the movie playback to stop. While this limit is rarely reached by most developers, it is possible. If your movie must have more than this number of frames,try creating multiple movies with fewer than 16,000 frames each and then linking the movies togetherusing a method such as the ActionScript 2 loadMovie() command.
- 16,000 layers: Flash is not capable of working with more than 16,000 layers in a movie.
- 16,000 loaded movies: You cannot load more than 16,000 movies into Flash player.
- 16,000 symbol instances: Flash does not allow more than 16,000 symbol instances in a Flash movie
- 2880 x 2880 px canvas size: A Flash movie cannot be larger than 2880 px wide or 2880 px tall.
Take a look at the adobe knowledge base for more information…
htaccess ErrorDocument
Create a file called .htaccess in the root of your
public_html/htdocsof your domain.Inside add the following text:
Options +FollowSymLinks AddDefaultCharset UTF-8 RewriteEngine on Options +FollowSymLinks AddDefaultCharset UTF-8 RewriteEngine on ErrorDocument 404 /index.php ErrorDocument 301 /index.phpWith the
index.phpfiles being the pages that get redirected to.How to correctly form HTML
<!DOCTYPE html PUBLIC ?-//W3C//DTD XHTML 1.0 Strict//EN? ?http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd?> <html xmlns=?http://www.w3.org/1999/xhtml?> <head> <meta http-equiv=?Content-Type? content=?text/html; charset=UTF-8? /> <script type=?text/javascript? src=?javascript/javascriptfilename.js?></script> <title>Title goes here</title> <link href=?stylesheetname.css? rel=?stylesheet? type=?text/css? /> </head> <body> Page content goes here </body> </html>Trying to get variables into flash from the browser!
Ever wondered how to get variables from an html page to a flash element?
Well, it’s quite easy using the following actionscript 2 example:
I use javascript to embed my flash elements:
_
<embed src="somefilename.swf?varname=varvalue&vartwo=var2value" width="550" height="400"></embed>_Now in Flash I can just call:
_root.varname and it will give us `varvalue` _root.vartwo will give us `var2value`Wasn’t that easy?
Flash Tweening
tween is an actionscript class and can be used after importing the core files.
import mx.transitions.Tween; import mx.transitions.easing.*; //Tween( obj:Object, prop:String, func:Function, begin:Number, finish:Number, duration:Number, useSeconds:Boolean);e.g.
var myRot:Tween = new Tween(myText, "_rotation", Elastic.easeOut, 0, 360, 3, true);Cube Desktop on Ubuntu
Alright, so I run Ubuntu 7.10 and use the Desktop Effects via compviz, anyhow, I could get the 2d workspace but really wanted the 3d cube, even if I set up 4 desktops, it would still only show 2 sides of the cube(aka not a cube).
The solution is: In Terminal do:
gconftool-2 --type int --set /apps/compiz/general/screen0/options/hsize 4😉
Animate with Actionscript [part1]
// Created by Andrew Odendaal // // :: DESCRIPTION :: // Animate a ball moving to the top // of the screen/stage and back again // // :: HOW TO USE :: // create a circle shape, convert to a movieclip(mc) and // place the registration point at the bottom center. // give the circle mc an stage instance name of 'ball'. var ball:MovieClip; var initBallY:Number = _root.ball._y; onEnterFrame = function() { if (_root.ball._y < 2.31) { _root.ball._y = initBallY; } else { _root.ball._y=_root.ball._y-10; } }Kill Adobe Updater
So adobe updater keeps doing updates eventhough you’ve said ‘NEVER DO IT AGAIN!!!’.
The fix is to physically remove the dir with the info in.
On a windows system go to ‘c:\program files\common files\adobe', there is a nasty little folder called UPDATER5 in there that you can DELETE!
PROBLEM SOLVED 😉Apache Cannot be Run. Another web server is using the web port or port is blocked by firewall.
Tried to start EasyPHP: “Apache Cannot be Run. Another web server is using the web port or port is blocked by firewall.”
I was running Skype! And it was blocking the using the port.
Check in options->advanced->connection for the setting on port 80.Another way to stop this from happening and solve the problem quicker is to go into the “Configuration->EasyPHP” [Ctrl+E] and make sure that the “Check server’s TCP port before starting” checkbox is not checked. This forces apache to just start and seems to work just as well!
How to load xml into flash using actionscript 2
Create an xml object:
var myXmlObject = new XML();Perform action when xml file has been loaded:
myXmlObject.onLoad = function(success) { if (success) trace("XML File has been read."); }Load the xml file into the object:
myXmlObject.load("myXmlFile.xml");TypeError: node is null message=node is null
The following error message occurs in Firefox 3 when using Firebug.
TypeError: node is null message=node is null
The error can be tracked back to script tags being in the head of the document instead of where they’re needed, an example would be with the ShareThis control/component that is often added to blogs and etc.Cant start your browser?
Cant start your browser?
Try checking if any torrent apps are running.. Close them and retry.How to Temporarily Edit the Text of Any Website
Have you ever wanted to temporarily edit a webpage displayed in Chrome or another browser?
How it works
Let’s take a look at the Google homepage quickly.
Now, after we apply our little “page hack”, let’s look at it again!
How to temporarily edit a webpage
- Go to a website of your choice that you would like to edit.
- Enter the following javascript into the address bar:
javascript:document.body.contentEditable="true"; document.designMode="on"; void 0PHP __autoload function
When PHP encounters a class that hasn’t been defined yet, you can use __autoload to automatically add them instead of including masses of included at the top of your files.
e.g.
function __autoload($class_name) { require_once $class_name . '.php'; }IE6 on Vista?
I find myself constantly fighting the microsoft battle of making things work in their browsers (thanks guys).
On one of my machines I have Vista installed and needed to test a newly created site that apparently had some issues under Internet Explorer 6.
HOWEVER, to my horror IE6 was unable to run on Vista. Once again, thanks Microsoft for making life difficult for everyone out there!
After much grief, pain and agony with a million attempts to get it to run I stumbled upon a really great tool called IETester made by DebugBar.
Guillotine-Bug? Bug
Yes, it’s called a Guillotine-Bug and it’s yet another bug IE users get to look forward too 😛
So how does it work?
Basically, the hasLayout messes around and elements become invisible and visible according to random things. Rather silly, but a bit of a bitch to initially figure out.So how do you fix it?
Try this:
in your css file add:
* html .container {height: 1%;} .container:after { content: '.'; display: block; height: 0; clear: both; visibility: hidden; }then apply to all elements that have nested floats.
Sending data from javascript to php
If you ever find yourself needing to do some ajax and in turn sending strings of characters via javascript then you should really try encodeURIComponent() to wrap your strings in. The function escape() can also be used, but I would not recommend it as encodeURIComponent() is better, it also escapes your usual ampersand ajax limiters which solved me quite a bit of pain.
What is Eb in firebug?
Gmail produces the following error/warning in firebug.
Eb is not definedfunction Bb(a){if(a[sb]&&a[sb](daa)){var'ents)};f.x2b=c;f.B2b=b;f.y2b=a;return f}I initially started seeing this while while on clients’ websites, but can now say it’s a gmail thing. So don’t stress.. 😉
Add TinyMCE code button
I had quite a few problems adding the htmlCode button to a fairly old copy of TinyMCE (I think around version 2.x).
All is resolved now and this is what I had to change:
Both changes are made in “editor_template.js” file, I also swopped the 2 files so that I could include and edit editor_template.js instead of the compressed “editor_template_src.js.
Using the advanced theme I added the following line near the top of the file:
Runtime Error! (abnormal program termination) maya.exe
The Problem
When starting Maya 8.5 an immediate error message and program termination.
Runtime Error!
Program C:\Program Filesz\Autodesk\Maya8.5\bin\maya.exe
abnormal program termination
Solution
…
Need more than hover?
I had a hover effect on an html input element but also needed to have an active state.
The css was like this for the inputs in mention:.contactformdiv input:hover, .contactformdiv textarea:hover { background-color:#fff; }It was simple, I just added a focus…
.contactformdiv input:hover, .contactformdiv textarea:hover, .contactformdiv input:focus, .contactformdiv textarea:focus { background-color:#fff; }Getting an internet connection under VirtualPC running Windows XP and Internet Explorer 7
Getting an internet connection under VirtualPC running Windows XP and Internet Explorer 7
Open the ‘settings’ of the virtual machine and select Networking -> then change Adapter1 to “Shared networking (NAT)” and it will use your local machine’s network settings.
Uppercase text in Actionscript
var lowerCase:String = "sample text"; var upperCase:String = lowerCase.toUpperCase();Firefox too slow?
Is your Firefox starting to get realllllllly slow?
Every few months my Firefox starts dragging, so all I do is create a new profile and reimport all my bookmarks and reinstall needed addons.
For a rundown on how to create a new profile, click the following link..
http://kb.mozillazine.org/Profile_ManagerUppercase the first character of each word in a string using PHP
You can use “ucwords()” to uppercase the first character of each word in a string.
e.g.
$myVar = 'this is a test!'; $myVar = ucwords($myVar); // This Is A Test!Actionscript 3 equivalent of PHP’s print_r
A brilliant version of print_r for actionscript:
http://dev.base86.com/solo/47/actionscript_3_equivalent_of_phps_printr.html
Global variables and functions in Actionscript 2
In order to reuse a variable from a different timeline within the same fla file you will need to register the inital variable or function as a _global.
Todo this as a variable:
_global.myString:String = "My String";Todo this as a function:
_global.myFunction = function() {}Actionscript conflicting class name
I had a problem today where I got a flash source file from one of my developers’ and I couldnt compile it because it said that there was a conflicting class name, however, it turned out to just be a timestamp issue.
Read here for more information
http://www.epresenterplus.com/blog/archives/000030.html
expecting T_PAAMAYIM_NEKUDOTAYIM
What the hey? What does this mean?
You may one day end up seeing the following error message produced by PHP and wonder to yourself:
PHP Parse error: syntax error, unexpected ‘)’, expecting T_PAAMAYIM_NEKUDOTAYIM in ///File.php on line 160
You guessed it, “T_PAAMAYIM_NEKUDOTAYIM” is not english.
It’s actually a Hebrew word meaning “unexpected” or “Twice Colon”.
It happens when PHP tries to call the “::” (double colon) which is used when identifying an uninstantiated class’ method.
About
About Andrew Odendaal
I’m a software engineer and cloud architect based in Dubai. I’ve been writing code professionally since 2007, starting with PHP and Flash (yes, Flash) and working my way through the full stack into cloud infrastructure, distributed systems, and platform engineering.
Over the years I’ve worked across startups, enterprise consulting, and large-scale SaaS platforms. Most of my recent work involves AWS architecture, Kubernetes cluster management, Terraform-based infrastructure, and building internal developer platforms. I hold the AWS Certified AI Practitioner certification and have hands-on experience across 15+ AWS services in production environments.
-
-
-
-
-