A Little Wood Making Project

I had a tiny wood making project over the last two weeks, involving making a more comfortable place for my cat to poop.

I got a litter box enclosure from Etsy 1-2 years ago but the size I got left my cat a bit too little vertical space. So I found a shelf in my buildings basement, ordered a jigsaw from Amazon for $35, and made four little raisers for each corner. Turned out pretty okay I think.

Readable Code

Readable code means that the code has a good balance of being easy to understand in terms of what it is doing, and of being concise.

Why does readable code matter?

When code is easy to read, it’s easy to debug, maintain, and extend. 

It’s not uncommon for a developer to write code at the beginning of a system development process, and then realize a year later that they don’t understand their own code and thus will need to re-teach themselves their own system. 

If someone else wrote the code, and it’s unreadable, it’s not uncommon for developers to re-write the entire system as a result, which is an inefficient way to build software.

Tips

Structure Your Code

Classes and methods should be consistent, easy to understand, and easy to navigate.

Simplify Your Code

Aim to make your code elegant—simple to read, orderly, and easy to understand. Don’t try to over-complicate things with elaborate tricks. Keep your classes a reasonable size and most of your functions short. 

Stick To The Style Guide

If the repository you’re working in has standard code formatting and style guidelines, use them. Stick to the maximum length per line used in other code in that repository, etc.

Names Should Be Self-Explanatory

A big aspect of making your code easy to read lies in the names you choose. The names of your functions should clearly describe their purpose. Name your variables, function, and methods in a way that describes what they do or what they are. 

For example, if your variable gets something, consider including “get” in its name. If you can’t name the method or function without using many words, the function may be too complicated. Consider going back and breaking complicated functions into smaller functions to simplify.

Ensure Blocks Are Self-Contained

The single responsibility principle means that every building block does only one thing. All building blocks, including methods, variables, and classes, follow this rule so it’s easy for the person reading the code to understand their responsibility. 

When your code follows this principle, it’s easier to maintain and more scalable. When concerns are separated, you can focus on what features you actually want to work on rather than having to navigate interconnected lines of code.

Ensure Comments Are Minimal

Comments shouldn’t tell us what we already know. They should tell us why things are happening. You shouldn’t have to write more than 1-2 lines in a comment to explain what the code is doing. If you have to, consider rewriting the code until it is more readable. If the code is obvious, avoid comments altogether. The code should be able to speak for itself in many cases. 

Sources

How to Review a PR (Pull Request)

This post is about reviewing Pull Requests (PRs) on a software engineering team, often submitted in a source code system like Github. It’s meant to be a concise guide.

Goals of a PR Review

  • Catch issues in the code that the submitter may have missed
  • Offer advice in making the code submission better
  • Complete any team-specific PR review required steps

For many PRs, you don’t need to be an expert in the stack or programming language that is used in the PR. 

The time it takes to review a PR is directly related to how long the PR took to create and how many changes it includes. You should expect to spend more time reviewing a large PR than a small PR.

Required Steps When Reviewing

The steps below apply to PRs with changes to code. If it’s a non-code PR (e.g. a wiki update), the reviewer should just check for typos and that the changes make sense to them.

  1. Confirm that the PR description contains at least 1-2 items describing the changes being made and the reason for those changes.
  2. If there aren’t automated tests, confirm that the PR description contains at least 1-2 items describing how the changes were tested.
  3. Check each changed file for potential bugs that the submitter may have missed.
  4. Check to see if the code is readable.
  5. Check for typos in the comments and readmes.
  6. If you’re not proficient with the programming language or framework used, make a note of that in your review.
    1. For example, “I’m a beginner when it comes to JavaScript. This PR looks good to me, but if you have any doubts about your code or would like a more in-depth review, please consider requesting a second review in ___ channel.”
    2. You don’t have to be an expert in the system which the PR is changing, but you should have a basic understanding of what’s going on. If you have absolutely no clue, it’s best to either loop in someone who does, suggest that the submitter bump their request for a review, or ask for a review in another channel. 
  1. If there are any parts that are particularly difficult to understand, consider suggesting that the submitter refactor or add a comment.

Example

🎉 Lgtm!

My gitlab CI configuration experience level: beginner.

I did not see any obvious errors, everything looks readable and elegant.

If at all possible, try to make future PRs smaller. If not possible, please note that in the PR description.

  • If many files are being renamed, I suggest making a separate PR just for the renaming.
  • There were also formatting/lint updates in this PR. In the future, I suggest a separate PR or including automatic changes like that in a separate renaming PR.

ci/scripts/pipelines.py

  • Is it possible to move the configuration constants (e.g. ROLE_PREFIX) to a config file or AWS systems manager? If yes, no need to change this PR, but please consider for a future PR.

It looks like there are some major changes to the gitlab pipeline in this PR. I reviewed the testing methodology, and it looks pretty good, but due to the size of this PR, please take a second look at the tests you did to make sure these changes wont break anything before merging the PR.

Great work 🔥. Thank you for making these gitlab CI improvements!

Cloudlist – the ADHD Todo App

One of the things I struggled with a lot was organizing all the ideas and things I want to do.

There’s always 1000 things I want to do, another 100 things I _need_ to do, and probably 1-3 things I _can_ do (because of available willpower, energy, etc).

For example, this morning I wanted coffee and a shower. In the bathroom, I realized I “needed” to trim the bathroom mat’s decorative tails because the roomba kept getting jammed on them. I also knew that the apartment was a mess and should be cleaned up a bit.

Anyway, I was able to do all of those things, but thinking about them, as well as all the other things I wanted to do, was de-motivating as it felt kind of overwhelming.

Currently the way I usually deal with this kind of thing is I open up my ongoing “Daily Plans” Apple note and add “coffee, shower, bath mat, clean” to the top and it will help me get those things done. Often, after adding these and doing them, I might not remember/care enough to remove them from that note.

This results in that note becoming very very long, and stressing me out, because it makes me wonder if I missed any important todos in it. In the last couple of years, at some point I will just skim it and accept that I might have missed important things and archive it. That’s why the current iteration of this note is called “Daily Plans 2022 After August.”

I’ve been trying to utilize a slightly more prioritized version of this with a google spreadsheet, but it hasn’t worked that well because I hate using google spreadsheets on my phone.

I’ve looked at various todo apps and other prioritization methods that might work for me, but never really found anything.

So in the last few months I’ve been thinking of a new cross-platform app to help me with this, and this morning I wrote up a description and posted it on upwork (https://www.upwork.com/jobs/~013e843563e016fa31), the website I use to hire developers to build apps for me.

Does this idea resonate with anyone?

The current working app name is RomanDo. It’s very egocentric, I know. Does anyone have better name ideas :)?

В чем разница между войной на украине и войной в ираке?

Мне очень ужасно за то что случается в Украине, с русскими и украинскими ребятами, с репутацией россиян и россии.

Я недавно увидел сообщение от русского друга моего друга, в котором она спрашивала, почему США могут «расплющить [Ирак и Иран] в блин», а Россия должна « спокойно наблюдать за экстремистской и террористической деятельностью на его границах».

Она сказала, что никто не может четко объяснить разницу между «демократическим» и «авторитарным» насилием.

Текст ниже был переведен с помощью Google Translate. Прошу прощения, если тяжело читать.

Я нашел статью в New York Daily News, которая, по моему мнению, была довольно хорошим объяснением некоторых важных различий между вторжениями в Украину и Ираком. Я думаю, что это достойный ответ на вопрос этого человека, поэтому я решил опубликовать русский перевод.

Я призываю вас прочитать всю статью Daily News, но основные отличия, которые в ней упоминаются:

  1. Саддам Хусейн был диктатором с историей убийств и нарушений нескольких резолюций Совета Безопасности ООН. Зеленский — демократически избранный лидер, пользующийся общественной поддержкой.
  1. Войну в Ираке вела коалиция, в которую на момент вторжения входила 31 страна, включая Великобританию, Австралию, Италию, Испанию и Турцию. Владимир Путин время от времени находил союзника в лице соседнего диктатора, белоруса Александра Лукашенко.
  1. Граждане Ирака оказали большую поддержку войне, когда она началась.
  1. США пытались оправдать вторжение в Организации Объединенных Наций (ООН) до его начала. Вторжение в Ирак никогда не осуждалось ООН. Вторжение в Украину было почти единодушно осуждено ООН, и Россия никогда не пыталась оправдаться перед ООН.

Несмотря на вышеуказанные причины, большинство американцев быстро пожалели о поддержке вторжения в Ирак

Мой вопрос к человеку, который утверждает, что между этими двумя вторжениями нет разницы: почему вы до сих пор поддерживаете войну в Украине?


Перевод статьи

Вторжение в Украину сильно отличается от Ирака

  • Кэти Янг, Нью-Йорк Дейли Ньюс, 15 апреля 2022 г., link

В то время как мир наблюдает за жестокой войной России в Украине, в то время как Соединенные Штаты возглавляют борьбу, чтобы остановить и наказать агрессора, «А как насчет Ирака?» – частая реплика, призванная обвинить предполагаемое американское лицемерие.

На Ирак ссылались дружественно настроенные к Кремлю правые, такие как активистка и эксперт Кэндис Оуэнс (которая саркастически спросила, почему Америка не получила финансовых санкций за вторжение в Ирак, в результате которого «были убиты сотни тысяч иракских мирных жителей»), а также левые, такие как как эксперт MSNBC Мехди Хассан, который утверждал, не оправдывая Россию, что сходство между двумя войнами очевидно и заметно. Недавние отчеты о российских зверствах также опровергаются ссылками на гибель мирных жителей в Ираке.

Но не нужно одобрять войну в Ираке, чтобы увидеть, насколько неправдоподобно это сравнение.

Во-первых, в отличие от Украины, Ираком руководил кровожадный диктатор, вторгшийся в другую страну (Кувейт) в 1990 году, потерпевший поражение от коалиции, в которую входили США, и которому было позволено остаться у власти благодаря перемирию на условиях, которые включали инспекции на наличие оружия массового поражения. Саддам Хусейн нарушил несколько резолюций Совета Безопасности ООН, последняя из которых, принятая в ноябре 2002 года, предусматривала принудительное выполнение.

Некоторые эксперты в области права утверждают, что эта резолюция санкционировала действия возглавляемой США «Коалиции желающих». Большинство не согласны, и тогдашний генеральный секретарь ООН Кофи Аннан сказал, что война могла быть юридически санкционирована только другой резолюцией ООН, специально разрешающей военную силу. (США и Великобритания пытались, но не смогли добиться такой резолюции.) Тем не менее, стоит отметить, что вторжение никогда не осуждалось ООН, и даже Аннан ждал больше года, чтобы сказать, под прямым давлением, что оно было незаконным. по уставу ООН. Это резко контрастирует с быстрым и почти единодушным осуждением войны, которую Россия начала, даже не пытаясь оправдаться перед ООН.

Войну в Ираке также вела коалиция, в которую на момент вторжения входила 31 страна, включая Великобританию, Австралию, Италию, Испанию и Турцию. Владимир Путин время от времени находил союзника в лице соседнего диктатора, белоруса Александра Лукашенко.

Более того, если в Украине сценарий приветствия вторгшихся солдат как освободителей был зловещей фантазией, то в Ираке, по крайней мере поначалу, он был реальной реальностью: падение Саддама Хусейна было встречено всеобщим ликованием. В опросе 2004 года 46% иракцев заявили, что дела обстоят лучше, чем до войны, а 49% считают, что вторжение было абсолютно или в какой-то степени правильным; 39% считали, что дела обстоят хуже и что вторжение было неправильным.

Позже эти цифры изменились по мере ухудшения ситуации и ухудшения отношения к коалиционным войскам. Тем не менее, к началу 2009 года только 28% считали вторжение «абсолютно неправильным»; в других опросах трое из четырех иракцев согласились с тем, что устранение Саддама того стоило, несмотря на трудности. Это примечательно, учитывая, что большинство людей инстинктивно ненавидят иностранных захватчиков — особенно когда существуют серьезные культурные и религиозные различия — и что по крайней мере некоторые респонденты имели привилегированный статус при Саддаме.

Ужасный факт, что десятки тысяч иракских мирных жителей погибли в результате авиаударов коалиции и других военных действий (не считая убитых повстанцами и межконфессиональными распрями). Но трагическая гибель мирных жителей в результате ударов по военным объектам морально не эквивалентна преднамеренным бомбардировкам россиян в качестве террористической тактики, не говоря уже о их шокирующей жестокости на оккупированных территориях Украины. Да, некоторые американские солдаты в Ираке совершили военные преступления, такие как убийство 24 мирных жителей в Хадисе в 2005 году, и не понесли должного наказания; но даже это отличается от зверств как стратегии.

Также полезно помнить, что альтернативой войне России для украинцев был мир. Альтернативой американской войне в Ираке было жестокое репрессивное государство, которое, по данным Хьюман Райтс Вотч, убило не менее 250 000 своих собственных. Даже президент Обама, последовательный противник войны, в своем выступлении в Овальном кабинете в 2010 году признал, что американские войска «нанесли поражение режиму, который терроризировал свой народ».

Некоторые эксперты, такие как Ноа Ротман из Commentary, утверждают, что создание нового Ирака — развивающейся демократии, не представляющей угрозы безопасности, — следует рассматривать как положительное достижение. Это трудно сделать, если взвесить все минусы: гибель американцев и иракцев; региональный хаос и подъем ИГИЛ; причастность США к оккупации, которая почти неизбежно вовлекла нас в нарушения прав человека; ущерб общественному доверию дома от войны, первоначально оправданный заявлениями об оружии массового уничтожения, чиновникам было известно, что они основаны на недостоверных доказательствах.

Кто-то может поверить, что война в Ираке еще не вынесена, или что она однозначно осуждена как ужасная ошибка. Но предлагать аналогию с войной Путина на Украине неверно как с исторической, так и с моральной точек зрения.


Оригинальное сообщение от этого русского друга друга

Вот не надо передергивать – в интернете огромное количество людей борется не за Путина и за “спецоперацию”, а за примитивный здравый смысл. 

Ни один, подчеркиваю, ни один новорожденный  “квазипацифист” не может ответить на самые элементарные вопросы вроде почему США и НАТО можно бомбить Югославию и “раскатывать в блин” Ирак с Ираном, а Россия (да и любые другие страны) должна молча смотреть на экстремистскую и откровенно террористическую деятельность у своих границ. 

Никто внятно не может объяснить, чем “демократическое” насилие отличается от “авторитарного” и почему первое можно, а второе – категорически нельзя. Одним словом, или полно равенство всех и каждого, или только “право сильного” и право войны.

What is the difference between the wars in Iraq and Ukraine?

I absolutely hate what’s happening in Ukraine, to both the Ukrainian and Russian people who are there, and to Russia’s reputation.

Recently I saw a message from a Russian friend of a friend, asking why the USA can “flatten [Iraq and Iran] into a pancake,” but Russia has to “quietly watch as extremist and terrorist activities occur at its borders.”

They said no one can clearly explain the difference between “democratic” and “authoritarian” abuse.

I found a New York Daily News article, which I thought was a pretty good explanation of some important differences between the Ukraine and Iraq invasions. I think it is a decent response to that person’s question, so I decided to publish a Russian translation.

I encourage you to read the whole Daily News article, but the main differences it mentions are:

  1. Saddam Hussein was a dictator with a history of murder and violating several United Nations Security Council resolutions. Zelensky is a democratically elected leader with public support.
  1. The war in Iraq was conducted by a coalition that had 31 member countries at the time of the invasion, including the United Kingdom, Australia, Italy, Spain and Turkey. Vladimir Putin found one on-and-off ally in the dictator next door, Belarus’s Aleksandr Lukashenka.
  1. There was large support of the war by the citizens of Iraq when it initially began.
  1. The US tried to justify the invasion in the United Nations (UN) before it began. The Iraq invasion was never condemned by the UN. The Ukraine invasion was near-unanimously condemned by the UN, and Russia never tried justifying it to the UN.

Despite the reasons above, most Americans quickly regretted supporting the invasion of Iraq

My question to the person, who is arguing that there’s no difference between these 2 invasions: why are you still supporting the war in Ukraine?


Original message from the Russian friend of a friend

Below is a google translation of their message. I apologize if it’s difficult to read.

There is no need to distort – on the Internet a huge number of people are fighting not for Putin and for a “special operation”, but for primitive common sense.

Not a single, I emphasize, not a single newborn “quasi-pacifist” can answer the most elementary questions, such as why the United States and NATO can bomb Yugoslavia and “roll into a pancake” Iraq and Iran, while Russia (and any other countries) should silently look at extremist and openly terrorist activities at their borders.

No one can clearly explain how “democratic” violence differs from “authoritarian” violence and why the first is possible, while the second is categorically impossible. In a word, either the equality of all and everyone is complete, or only “the right of the strong” and the right of war.

Stretches and Exercises for Lower Back Pain

A little unusual of a post for this blog, but recently, my recurring lower back pain soreness and pain has returned. In order to address this soreness, I found an incredibly helpful set of stretches on youtube from a channel called Activ Chiropractic. By doing each stretch for about 10 seconds, a lot of my soreness and pain goes away.

In order to make these stretches easy to reference, I made a screenshot of each stretch and a single image with all the stretches combined. Since it’s been so helpful to me, I figured I would share it with the world on my blog.

Build a Javascript Slack App

A Summary of the Official Building a Bolt JS App

  1. Create a new slack app in the apps portal.
  2. Go to Basic Information page in the apps portal and install the app in your Slack instance.
  3. To edit and host the code for your slack app: Create a Glitch app from Slack’s template.
  4. Copy the signing secret and the Bot token from Basic Information and OAuth pages in the apps portal into your glitch app’s .env file.
  5. Go to Event Subscriptions in the apps portal and add app_home_opened.
    1. request_url for glitch apps is https://YOUR_APP_NAME.glitch.me/slack/events.
    2. Add bot event app_home_opened. Save changes.
  6. Go to your app’s “home” page in the Slack app. You should see the example text and button from the code in Glitch.
  7. You can now use shortcuts, listen for events, post messages, and more with the bolt js framework. To try one, just replace the example “app.home.opened” function.
  8. Each of the functions above has listener functions for interacting with Slack. 

Add a Shortcut in a Bolt JS Slack App

  1. Go to your app’s Interactivity page in the apps portal.
    1. request_url for glitch apps is https://YOUR_APP_NAME.glitch.me/slack/events.
    2. Name is whatever you want showing up in the Slack app.
    3. callback_id is your function name that you will use in your code.
  2. In glitch, add the code from https://slack.dev/bolt-js/concepts#shortcuts.
  3. That’s it. To add more functionality to your shortcut, check out https://github.com/slackapi/bolt-js#making-things-happen.
slack shortcut example
slack shortcut example

Kubernetes FAQ

Recently I’ve been working a lot with kubernetes at my job. I’ve written up a bunch of internal documentation based on my work, and because it’s not company-specific I decided I’m going to share it here for anyone trying to find answers on the internet.

Table of Contents:

  1. what is k8s?
  2. view nodes in a nodegroup
  1. view pods on a node
  2. restart deployment
  3. insufficient cpu, insufficient memory errors
  4. deployment is not ready
  5. CrashLoopBackoff
  6. pod didn’t trigger scale-up
  7. how do I avoid accidentally running a kubectl command on the wrong cluster?

What is Kubernetes? How do I use it?

Check out kubernetes docs here: https://kubernetes.io/docs/home

View Nodes in a Nodegroup

Confirm the nodegroup you’re checking actually exists (e.g. you’re looking for pods running under engtools-infra/my-app) by listing all the nodegroups in a certain namespace:

k get nodegroup -n engtools-infra

Get the nodes under that nodegroup:

k get nodes -o wide | grep my-app

View Pods on a Node

View pods under a node with the following command (replace NODE_NAME_GOES_HERE with the node’s name, e.g. ip-10-10-12-123.ec2.internal).

k get pod --field-selector=spec.nodeName=NODE_NAME_GOES_HERE -owide --all-namespaces | grep -v -E "( kube-proxy-| kube2iam-|  local-volume-provisioner-| node-monitoring-| localusers-)"

Restart Deployment

Make sure you’re in the right cluster, get the deployment name, then use the rollout command.

k config current-context
k get deployment -n [NAMESPACE]
k rollout restart deployment [DEPLOYMENT_NAME] -n [NAMESPACE]

insufficient cpu, insufficient memory errors

If you’re seeing errors about insufficient resources, or node(s) had taint … that the pod didn’t tolerate warnings, you probably need to define instanceType and resources attributes in your service k8s objects / charts. For example, something like the following:

  instanceType: c5.2xlarge
  resources:
    requests:
      cpu: "3"
      memory: "4G"
    limits:
      cpu: "4"
      memory: "6G"

Deployment is not ready

A log you might see when deploying with Bazel is Deployment is not ready: <service>. 0 out of 2 expected pods are ready. This usually means k8s pods are in a CLB or some other non-ready status.

Use kubectl commands to check on the pods’ status and logs. Usual status check command:

kubectl -n NAMESPACE get pods

CrashLoopBackoff

If you see CrashLoopBackOff status on one of your pods, that means it’s crashing (I know, thanks captain obvious).

Check the pod logs: k logs CRASHING_POD -n NAMESPACE.

Find the deployment.yaml file describing the launch instructions for this pod. Find the command attribute in that file, comment out the value underneath it, and add the following:

          - tail
          - "-f"
          - /dev/null

Then re-deploy the pod. This will allow you to SSH into the pod, run the failing command manually, and generally get more info about the problem.

You might also need to comment out the liveness/readiness container specs in deployment.yaml, as those will often cause the pod to crash as well if there’s an issue with the primary container.

More info about troubleshooting crashloopbackoff pods can be found in this releasehub.com article.

pod didn’t trigger scale-up

Normal   NotTriggerScaleUp    19m                  cluster-autoscaler   pod didn’t trigger scale-up: 3 node(s) had taint {node: database-rev-eng-8c38-pool1}, that the pod didn’t tolerate…

Potentially a node group or a scaling group issue. For example, you might have a single AutoScalingGroup (asg) under your nodegroup-controller which has reached its max size. In this case, adding autoscaling: true option to your charts may be required in order to have more ASGs created.

If adding nodegroup options, you may need to delete the existing nodegroups (krm ng NODEGROUP_NAME -n NAMESPACE) for the option to take effect. After creating the new nodegroup, the cluster autoscaler may need to pass by, which can take a few minutes. So if you’re still seeing the scale-up messages and your pod in a Pending status after such a change you may need to give it a little time.

How do I avoid accidentally running a kubectl command on the wrong cluster?

Use Explicit Context in Commands

kubectl –context cluster3.us1.test.com get pods -n mynamespace  

Kube-ps1

kube-ps1 will show you what cluster and namespace you’ve set in your prompt, which helps avoid this issue:

After installing it with homebrew, add this to your .rc file and restart your terminal to enable it:

source /usr/local/opt/kube-ps1/share/kube-ps1.sh
PROMPT='$(kube_ps1)'$PROMPT

It works great in conjunction with using kubectx and kubens to change your context/cluster/namespace.

It’s very easy to change contexts in a different terminal and have a stale prompt showing the old context. Press enter to refresh the prompt.

Powerlevel10k

If you use powerlevel10k, it can dynamically update your prompt with the current context when you’re typing a kubectl command – https://github.com/romkatv/powerlevel10k#show-on-command.

Troubleshooting