Angry Docker Purge

If you receive No Space left error on Docker this the brute force solution:

It would stop and delete ALL containers, images and volumes.

docker stop $(docker ps -aq); docker rm $(docker ps -aq); docker volume rm $(docker volume ls -qf dangling=true);docker system prune -af


4
Babar

Run same command on different input/inputs

If you have to run the same command repetitively over different input/inputs.

Example input:

c595270372e3
c04094382ae1
498a6505a1f7
4ac0e1872789
170a7f2ec51a
930743cb4e19


Command:

pbpaste | xargs -I id docker image rm id


Note: pbpaste is clipboard paste command for Mac, would be different for operating systems.

1
Babar

Check for IKEA item availability

A bit of a hack, but we want to be notified if an item becomes available at IKEA.

This is just a shell script that should work on any *NIX that has curl installed.

This is how their API response looks like (replace th with your country code): https://www.ikea.com/th/en/iows/catalog/availability/S99067497

There are only two stores in Thailand, both of which are close enough to the Oozou office, we only care that it's available in one of those stores.

#!/usr/bin/env bash

url="https://www.ikea.com/th/en/iows/catalog/availability/$1"

# This is the string that we want to see changed
string="0"

while true; do
  # Get the API response and return as string
  text=$(curl -s "$url")

  # Get a count of how many times the substring matches
  count=`grep -o "$string" <<< "$text" | wc -l`

  # If less than 2, then it's available!
  if (( $count < 2 )); then
    echo "AVAILABLE, yay.";
    # Notify us via Slack
    curl -X POST --data-urlencode "payload={\"channel\": \"…\", \"username\": \"ikea\", \"text\": \"Item $1 is now available at IKEA.\", \"icon_emoji\": \":shooping_bags:\"}" https://hooks.slack.com/services/…
    break
  else
    # If not available, sleep for 30s
    echo "$1 not in stock"
    sleep 30
  fi
done



Pass in your item ID to start:

$ ./check.sh S99067497


5
Const

How to Create an HTML Element with Attributes in One Line in JavaScript

When working on a JavaScript project, it's common to create HTML elements dynamically. Traditionally, you might use several lines of code to create an element and set multiple attributes individually, as shown below:

const a = document.createElement('a')
a.setAttribute('class', 'foo bar')
a.setAttribute('id', 'id')
a.setAttribute('innerHTML', 'Hello World!')
a.setAttribute('href', 'https://www.google.com/')


While this approach is functional, setting each attribute one by one can be tedious, especially when working on large codebases. It also leads to bloated code, which can make your codebase harder to maintain and more difficult to debug.

In this article, we'll explore a more concise method to create an HTML element and set attributes in one line, making your code more efficient and readable.

Creating HTML Elements in One Line with Object.assign()


JavaScript's Object.assign() method allows you to create an HTML element and assign multiple properties at once. By doing this, you can streamline your code and reduce the repetition involved in setting attributes individually.

Here’s how you can achieve this:

Object.assign(document.createElement('a'), {
  id: 'id',
  class: 'whatever class',
  href: 'https://www.google.com/',
  innerHTML: 'This is a link'
});


With this one-liner, you're creating an anchor (<a>) tag and setting its id, class, href, and innerHTML properties all at once. Not only does this save time, but it also makes your code cleaner and easier to maintain.

Breaking Down the Code:

  • Object.assign() is a method that copies all properties from one or more source objects to a target object. In this case, the target is document.createElement('a'), which creates a new anchor element.
  • Inside the second parameter of Object.assign(), you pass an object containing the attributes you want to assign to the element.
  • Each key in the object corresponds to an HTML attribute or property (id, class, href, etc.), while the value is the attribute’s value.

Benefits of Using Object.assign()

  • Cleaner code: You can set multiple attributes in a single line, reducing code repetition.
  • Maintainability: This approach makes your code easier to maintain. Since attributes are set together, it’s simpler to manage them in one place.
  • Improved readability: By consolidating attribute assignments, the code is more readable and requires fewer lines.

When to Use Object.assign()

While this method is useful for most scenarios, it’s particularly helpful when:

  • You need to dynamically create multiple elements with different attributes. 
  • You want to minimize the number of lines in your code, especially in large projects. 
  • You want to ensure consistency across similar elements by applying a batch of attributes in one go.

Other Alternatives for Creating Elements with Attributes in One Line

Using Spread Operator and Destructuring

Another way to create HTML elements with attributes in a single line is to use JavaScript’s spread operator and destructuring capabilities.

const attributes = {
  id: 'id',
  class: 'foo bar',
  href: 'https://www.google.com/',
  innerHTML: 'Hello World!'
};

const a = Object.assign(document.createElement('a'), {...attributes});


Here, we store the attributes in an object (attributes), and use the spread operator (...attributes) to assign the properties when creating the element. This method is flexible and makes it easy to reuse the same attribute set for other elements, or customize attributes dynamically.

Using a Custom Function

You can also create a reusable function to create elements with attributes in a single line.
function createElement(tag, attributes) {
  return Object.assign(document.createElement(tag), attributes);
}

const a = createElement('a', {
  id: 'id',
  class: 'foo bar',
  href: 'https://www.google.com/',
  innerHTML: 'Hello World!'
});


In this example, createElement() takes two arguments: the tag name (such as 'a', 'div', etc.) and an object containing the desired attributes. This custom function can be reused throughout your code, making it more modular and easy to update.

Conclusion


Setting attributes individually on an HTML element can be time-consuming and lead to repetitive code. Using Object.assign() allows you to create an HTML element and assign multiple attributes in one line, improving code readability and maintainability. Additionally, other methods like using the spread operator or a custom function can help streamline your code and make it more efficient.

By incorporating these techniques into your JavaScript projects, you’ll be able to write cleaner, more maintainable code—particularly useful in complex web applications where efficiency is key.


FAQs


1. What is Object.assign() in JavaScript? 
Object.assign() is a method that copies all enumerable properties from one or more source objects to a target object. It is commonly used for merging objects or setting properties on an object in a concise manner. 

2. Is it possible to create an HTML element with multiple attributes in one line? 
Yes, using Object.assign() or similar methods, you can create an HTML element and assign multiple attributes in one line. 

3. What are the benefits of using Object.assign() for setting HTML attributes? 
Using Object.assign() makes your code cleaner, more readable, and easier to maintain. It reduces the need to set attributes individually, consolidating them into one line. 

4. Can I use Object.assign() with other JavaScript features like the spread operator?
Absolutely! You can combine Object.assign() with the spread operator or even destructuring to further enhance code readability and reusability. 

5. What are some alternatives to Object.assign() for setting attributes in one line?
Alternatives include using the spread operator, destructuring, or creating a custom function that encapsulates the logic for setting attributes on an element.

By optimizing your JavaScript code with methods like Object.assign(), you’ll enhance your development process, making it more efficient and reducing the amount of boilerplate code. This approach aligns well with modern best practices, ensuring scalability and maintainability for your JavaScript applications.

26
Babar

Change Ruby version for single command with rbenv

You can switch Ruby version temporarily with rbenv local

But it'd need to be switched back after you're done. Specially for a single command it's kind of pain. In those cases, you can use RBENV_VERSION env variable.

RBENV_VERSION=2.6.3 ruby -v


This might be useful in a shell script or so.

1
Babar

Go through a file Git history (GUI)

$ gitk --follow file


Ali

Reset Postgres table sequence after DELETE

When deleting recent records from a table, you can reset it's sequence counter if auto-increment field continuity is important to you. Consider actions on the following table, users
 
select max(id) from users;

+-----+ 
| max | 
+-----+ 
| 896 | 
+-----+ 
1 rows in set (0.03 sec)

Then, some delete action against most recent rows: 
delete from users where created_at > timestamp 'yesterday';
96 rows in set (0.15 sec) 

The next auto-increment value for id would be 897 on the next insert. Use the following command to reduce the sequence value for the users table by 96.
select setval('users_id_seq',(select max(id) from users));

+--------+
| setval |
+--------+
| 800    |
+--------+
1 rows in set (0.04 sec)

Why Reset the Sequence?


Resetting a sequence in Postgres is necessary when you want to reinitialize the sequence to a new starting value, allowing for a new contiguous sequence to be generated. This is often required when you need to merge data from multiple databases, change the structure of your database, or recover from data corruption. By resetting the sequence, you can ensure that your primary key columns continue to generate unique and contiguous integers.

Understanding the Primary Key Sequence


A primary key sequence is a database object used to generate unique integer values for primary key columns in a table. It is a crucial component of a relational database management system, as it ensures that each row in a table has a unique identifier. The primary key sequence is typically created when a table is created, and it is used to generate values for the primary key column. Understanding how the primary key sequence works is essential for managing your database effectively.

How to Reset the Sequence


To reset a sequence in Postgres, you can use the ALTER SEQUENCE command. This command allows you to change the definition of a sequence generator, including its starting value, increment, and maximum value. To reset the sequence, you need to specify the name of the sequence, the new starting value, and the increment. For example, to reset a sequence called “my_sequence” to start from 100 with an increment of 1, you would use the following command: ALTER SEQUENCE my_sequence RESTART WITH 100 INCREMENT BY 1; Alternatively, you can use the SETVAL function to reset the sequence to a specific value. This function sets the current value of the sequence to the specified value, and it can be used to reset the sequence to a new starting value. For example: SELECT setval('my_sequence', 100);

Precautions and Considerations


Before resetting a sequence, it is essential to take precautions to avoid data corruption or inconsistencies. Here are some considerations to keep in mind:

  • Make sure you have a backup of your database before making any changes to the sequence.
  • Ensure that you have the necessary permissions to modify the sequence.
  • Be careful when resetting the sequence, as it can affect the integrity of your data.
  • Consider the impact of resetting the sequence on your application and users.

Alternative Methods


In addition to using the ALTER SEQUENCE command or the SETVAL function, there are alternative methods for resetting a sequence in Postgres. One approach is to use the pg_get_serial_sequence function to retrieve the name of the sequence associated with a column, and then use the ALTER SEQUENCE command to reset the sequence. For example: SELECT pg_get_serial_sequence('my_table', 'id'); ALTER SEQUENCE my_table_id_seq RESTART WITH 100; Another approach is to use the SQL function to migrate the primary key sequence to a new starting value. This can be particularly useful when you need to ensure that the sequence values are contiguous and unique across multiple tables or databases.
1.07 Thousand
Jeff

Kill unresponsive SSH session

Occasionally an SSH session may become unresponsive. If I put my laptop to sleep this happens fairly often. Rather than killing the tab you can use SSH Escape Characters to kill the session

$ ~.


To view all escape characters check man ssh and search for ESCAPE CHARACTERS $ /ESCAPE CHARACTERS

Joe

PostgreSQL UPDATE Join

This query shows how to use the PostgreSQL UPDATE join syntax to update data in a table based on values in another table. for example;

updating subscription_missions.giftbox_type with rewards.gift_box_type through mission_rewards table (tested on 300k records, crazy level fast)

  UPDATE
        subscription_missions sm
  SET
        giftbox_type = r.gift_box_type
  FROM
        mission_rewards mr,
        rewards r
  WHERE
        sm.giftbox_type IS NULL
        AND sm.id = mr.subscription_mission_id
        AND mr.reward_id = r.id;



1
Ali

Kill rails that got stuck

I'd like to kill rails running w/specific port. (My laptop running several rails servers. )

kill -9 $(lsof -i :3000|grep ruby|head -1|awk '{print $2}')

Alyson