Saturday, 28 May 2022

Toggle icon class across all the rows in the table

In this javascript code below there are two icons. fa-circle-pause and fa-circle-play.

When a user clicks the play icon in any one of the rows in the table, it is updated with the icon fa-circle-pause. I have been able to do that for the single rows.

But I am not able to update the rest of the rows in the table with the icon fa-circle-play.

How can I do that using just the javascript?

const data = [{
  Name: 'Chapter 1',
  TrackId: 1
}, {
  Name: 'Chapter 2',
  TrackId: '2',
}, , {
  Name: 'Chapter 3',
  TrackId: '3',
}, , {
  Name: 'Chapter 4',
  TrackId: '4',
}]; // any json data or array of objects
const tableData = data.map(function(value) {
  return (
    `<tr>
           <th scope="row">
            <span data-track-id='${value.TrackId}' class="play-button btn">
                <i class="fa-solid fa-circle-play"></i>
            </span>
          </th>
          <td>${value.Name}</td>
     </tr>`
  );
}).join('');
const tabelBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;

const pauseIconClassName = 'fa-circle-pause'
const playIconClassName = 'fa-circle-play'

const btns = document.querySelectorAll('.play-button')

function onChange(event) {
  // get the button elememt from the event
  const buttonElement = event.currentTarget.querySelector('i');

  const isPlayButton = buttonElement.classList.contains(playIconClassName)

  if (isPlayButton) {
    buttonElement.classList.remove(playIconClassName)
    buttonElement.classList.add(pauseIconClassName)
  } else {
    buttonElement.classList.remove(pauseIconClassName)
    buttonElement.classList.add(playIconClassName)
  }
}

btns.forEach(btn => {
  btn.addEventListener('click', onChange)
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet" />

<table border="2">
  <thead class="thead-dark">
    <tr>
      <th scope="col">#</th>
      <th scope="col">Track</th>
    </tr>
  </thead>
  <tbody id="tableBody">

  </tbody>
</table>


from Toggle icon class across all the rows in the table

Decrypting Windows EC2 password in Python

I would like to launch a Windows EC2 instance and programmatically get the admin password using Python. I know this can be done using the CLI like this, but I would prefer to decrypt locally to avoid sending my private key over the internet.

aws ec2 get-password-data --instance-id i-0d4d8273cadcae0a0 --priv-launch-key .ssh/elliott2.pem

After reading Cryptodome docs, I tried like this:

import boto3
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

ec2 = boto3.resource('ec2', 'us-west-2')
i = ec2.Instance('i-028dee2acb533fc59')

encrypted_str = i.password_data()['PasswordData']
with open('mykey.pem') as fp:
  key = RSA.importKey(fp.read())

cipher = PKCS1_OAEP.new(key)
print(cipher.decrypt(enc_str))

This fails with error:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    print(cipher.decrypt(encrypted_str))
  File "/Users/elliott/Library/Python/3.8/lib/python/site-packages/Crypto/Cipher/PKCS1_OAEP.py", line 167, in decrypt
    raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.

I think cipherkey must be exactly 256 Bytes. But the password data is longer than this, so I'm not sure what to do.



from Decrypting Windows EC2 password in Python

Non FK models tied together by ID (unmanaged model) - how to filter in Django?

I have two models that are related - but they are not a FK relationship in Django because one is a non-managed model with the data coming from a pre-populated DB table.

class Enrollment(models.Model):
    # This comes from a 'shared app' that is used in other projects 
    id = models.IntegerField(db_column="ID", primary_key=True)
    location_id = models.IntegerField(db_column="locationID")
    grade = models.CharField(db_column="grade", max_length=10)

    class Meta(object):
        managed = False
        db_table = "mytable_Enrollments"

class Location(models.Model):
    # This model exists in an app in the specific project I am working on
    name = models.CharField(max_length=50)
    alternate_name = models.IntegerField()

I'm trying to filter Enrollment models using a list of Location models - but they are not tied together in a FK relationship.

I am trying to get enrollments for a particular location like this:

# This does not work properly because it is returning an empty Queryset when it should have results - but does not hit the db which is what I want
location_ids = Location.objects.filter(id=1).values_list("id", flat=True)
enrollments = Enrollment.objects.filter(location_id__in=location_ids)

The above code returns an empty queryset.

If I cast location_ids to a list (like this: list(location_ids)) and then filter on that, it works.

# This works properly - but hits the db which is NOT what I want
location_ids = Location.objects.filter(id=1).values_list("id", flat=True)
enrollments = Enrollment.objects.filter(location_id__in=list(location_ids))

Is there a way to use the Django ORM to get what I want in this case without causing it to evaluate the queryset?

Additionally, I have tried just returning values instead of values_list but it also returns an empty Queryset when it should not.

# This returns empty queryset
location_ids = Location.objects.filter(id=1).values("id")
enrollments = Enrollment.objects.filter(location_id__in=location_ids)


from Non FK models tied together by ID (unmanaged model) - how to filter in Django?