teleren/devto huggingface dataset:
Leetcode: Valid Anagram (Kotlin)
Tags: kotlin, android, interview, algorithms
Published: 2021-12-04 01:26:58

I will show you my approach to solving the Leetcode easy problem, Valid Anagram, using Kotlin. The problem statement is: Given two strings s and t, return true if t is an anagram of s, and false otherwise. They also give two examples shown below:

![Leetcode Valid Anagram Examples](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhv3xkyfr06dpbo8yigo.png)

Basically, a valid anagram of another string consists of a string that contains the same characters and the same count of each character. Anytime you need to keep a count of something, using a hashmap can be considered. This is the approach I took in solving this problem.

These are the steps I took in solving this:

1. Compare the size of both strings. If they are not equal, we do not need to do anything else and can return false.

2. Create a HashMap with Char keys and Int values.

3. Create character arrays of both strings.

4. Loop through one of the character arrays and add the count of each character to the HashMap.

5. Loop through the other character array and check if each character is in the HashMap. Decrement the count if the character is found and the count is bigger than 0. If the count is 0, return false since there is a higher count of this character.

6. After you go through checking if every character in the second character array is in the map, this means both strings are valid anagrams.

Check out the code below:

```
fun isAnagram(s: String, t: String): Boolean {
        
    if(s.length != t.length) return false
        
    val map = HashMap<Char, Int>()
        
    val sArray = s.toCharArray()
    val tArray = t.toCharArray()
        
    for(c in sArray) map[c] = map.getOrDefault(c, 0) + 1
        
    for(c in tArray){
        var current = map.getOrDefault(c, 0)
        if(current < 1) return false
        map[c] = --current
    }
        
    return true
        
 }
```

![Leetcode Valid Anagram Submission Results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mb2lt92lpvwqekvgu702.png)

Check out the codelab version of this solution:
https://cmcoffeedev.com/codelabs/leetcode-valid-anagram/index.html

Check out the video version of this solution here:
{% embed https://www.youtube.com/watch?v=js02umcc_-w %}
Replaced curl-request with http module.
Tags: node, express
Published: 2021-12-04 01:15:20

I'm currently working on a celebrity face recognition app, leveraging the api provided by Clarifai team. 

This api returns a list of candidates' name when you send a image url with celebrities face(s) to it. 

To increase the performance, I decided to not only show the names of the candidates, but also attach a thumbnail of the celebrity, like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvyx9aes74f5cv2wu6s2.png)

The solution came up to my mind is using wikipedia to get the profile page of that celebrity, which normally contains an image of the celebrity as well.

But how should I parse the page and retrieve the thumbnail url from it? 

I tried to use the curl-request package first, which worked well locally. But when I tried to deploy it on Heroku, I got a whole bunch of errors. It turned out that one of the dependancy package of curl-request - node-gyp is not supported by node higher than 10.x, which is sebsequently not supported by npm higher than v6. When I use npm 6.x to build the project, I also get error from heroku.

To solve this conflict, I started to think about whether I really need to use curl-request. And the answer is No. 

After googling, I found this solution - using http module to get the html code then parse it. 

{% stackoverflow 64038999 %}

Up until now I've understood why we have to think carefully when we are adding a new package. Because when you add a new package, it means you are being dependant on it. Once it's deprecated, you might get trouble.
100 días de código: 31, proyecto de biblioteca.
Tags: spanish, 100daysofcode, webdev
Published: 2021-12-04 00:50:10

¡Hey hey hey!

Bienvenidos a este día 31, hoy me encontré con la necesidad de finalizar el proyecto de la biblioteca con pruebas de javascript basado en prototipos para seguir avanzando. Realmente siento que aun me toma bastante tiempo codificar y crear sitios aunque sean simples. 

Al hacerlo me pongo a pensar que realmente no se cuanto debería tardar una persona en realizarlo.

Así que me gustaría preguntarles cuanto tiempo creen que se tomarían en hacer un sitio para guardar sus libros.

Ahora sigamos con la sección regular. 

### Ayer:
- Avance hasta la sección del proyecto de biblioteca en la ruta de Javascript.
- Practique 30 minutos de Touch Typing.
- Hice algunos ejercicios de Hacker Rank.

### Hoy:
- Aprendí un poco de TypeScript, sobre todo sobre como hacer que las funciones reciban solo una serie de datos y compilar archivos de ts para volverlos Javascript con ayuda del comando `tsc`.
- Avance bastante con la funcionalidad de las animaciones del input en mi proyecto de biblioteca de The Odin Project.
- Practique 30 minutos de Touch Typing.

No escribiré mas porque quiero avanzar un poco mas en el proyecto. 
Espero que tengan mucho éxito con sus proyectos.

Adiós mundo!
Object Accessors in Ruby
Published: 2021-12-04 00:37:19

In Object Oriented Ruby an object's instance variables are variables that are declared inside of a class and are bound to an instance of that class. These can be set and returned with object or attribute accessors. We use what are called a setter(aka writer) method and a getter(aka reader) method. The reader returns the value of the instance variable and the writer sets it. These can be implemented manually as the following : 
 
```ruby
class Car 
 
 def model=(model) # Writer
  @model = model 
 end   
		 
 def model # Reader 
  @model 
 end

end 
```   

Though in Ruby there is a much more convenient option for your setter and getter or reader and writer methods called macros. When implementing macros they are followed by the attribute name they are being used on. You can sort of think of these as methods that create the definitions of other methods.  These are written as follows: 
```ruby
class Car 
  attr_writer :model 
  attr_reader :model 
	
end
```
Or for both the reader and writer methods in one you can use the attr_accessor macro as a way to both read and write to the same attribute: 
```ruby
class Car 
 attr_accessor :model 
end 
```

## Summary
Macros are generally preferred over the manual method of writing out your reader and writer methods every time you need to make a new attribute. If you don't need to manually customize something within your method then macros should usually be used over the alternative. In object oriented Ruby sometimes *less is more!*
Leetcode - Same Tree (Kotlin)
Tags: leetcode, kotlin, android, interview
Published: 2021-12-04 00:30:02

I am going to discuss my approach to solving the Leetcode problem “Same Tree” using the Kotlin programming language. The problem statement asks us to check if two binary trees are structurally identical and have the same values.

They give us three examples shown below:

![Leetcode Same Tree Examples](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gwj0silzp4xr8ym8enj.png)

My first idea was to do an in-order traversal of both of the trees and check that way. The fact that it needs to be structurally identical made me think of also doing a breadth-first search. I ended up choosing the breadth-first search approach.

First I created a queue and added both nodes to it. While the size is greater than 0, I get two nodes at a time and check the similarities here.
The first check I make is if both of the nodes are null. In this case, we are probably after two leaf nodes from both trees.

Next, I check if either node is null. This handles the case that they are not structurally identical (Example 2 above).
My last check is if both values at the level are the same.
If all of those checks pass, I add both nodes' children to the queue.

Lastly, if all of the checks pass for every level, I will return true, since both trees are the same.

```
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {
    val queue = LinkedList<TreeNode?>()
    queue.offer(p)
    queue.offer(q)
        
    while(queue.size > 0){
        val one = queue.poll()
        val two = queue.poll()
            
        if(one == null && two == null) continue
        if(one == null || two == null) return false
        if(one.`val` != two.`val`) return false
            
        queue.offer(one?.left)
        queue.offer(two?.left)
        queue.offer(one?.right)
        queue.offer(two?.right)
            
    }
        
    return true
 }
```


![Leetcode Submission Results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zw615pahoxgx1u1cy6hc.png)

Check out the codelab version of this solution here: https://cmcoffeedev.com/codelabs/leetcode-same-tree/index.html#0

Check out the video version of this solution:
{% embed https://www.youtube.com/watch?v=XhYCa6IK3Vw %}
Break glass in case of emergency
Tags: emergencyresponse, emergencies, pullrequests, codereview
Published: 2021-12-08 14:04:14

---
title: Break glass in case of emergency
published: true
date: 2021-12-04 00:00:00 UTC
tags: emergencyresponse,emergencies,pullrequests,codereview
canonical_url: https://jhall.io/archive/2021/12/04/break-glass-in-case-of-emergency/
---

Over the weekend I had a chat with a friend who asked me to settle a debate between him and a colleague.

One of them felt it was important to make pull request approvals mandatory before merge. The other felt thought it was important to allow merging without approval, in case of an emergency when approval is not possible.

Before you read on, which approach do you prefer, and why? How do you think I weighed in?

You probably guessed, I picked the third, unlisted option. I chose the “break the glass” option.

Let me explain.

Many commercial buildings will have a fire hose positioned behind a glass panel with visible instructions “Break glass in case of fire”.

![](https://jhall.io/images/break-glass-fire_hu46766d4d23f8808c55eb1a2259732e3f_7079274_400x0_resize_q85_box.jpg)

Breaking the glass serves two purposes. First, it gives you access to the emergency response tools you need immediately; namely a fire hose. Second, it triggers a fire alarm, which will alert anyone else in the building to the danger, and call the local fire department to send a crew who can help with the emergency, in case your fire hose efforts were not sufficient. And by putting the fire hose behind glass, we discourage inappropriate use. If the hose were just sitting there in the open, perhaps someone would use the fire hose to clean the floor, which I imagine we want to discourage.

We can apply the same pattern to a number of software development practices. For our pull request scenario, the idea is to allow an unapproved pull request, but to trigger an alarm of some sort when it happens. This can be done pretty simply by adding a check to your merge pipeline that counts the number of approvals. If that number is 0, an email or slack message can be sent to the team.

This will discourage inappropriate use of unapproved merges, while allowing them in case of emergency. And in either case, the team will be able to do a post-merge review of the code.

The same “break the glass” principle can be applied to many other processes that come up in software delivery as well, where you may want to allow human interaction, but only in case of an emergency. Human access to production servers or databases, rollbacks, service restarts, etc. Find a way to allow these activities if you need them, but alert when they’re done.

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Debug x86 assembly with GDB
Tags: assembly, nasm, x86
Published: 2021-12-04 19:19:16

---
title: Debug x86 assembly with GDB
published: true
date: 2021-12-04 00:00:00 UTC
tags: assembly,nasm,x86,assembly
canonical_url: https://www.mourtada.se/debug-x86-assembly-with-gdb/
---

This is the sixth post about x86 assembly. In this post I will show how to debug your x86 assembly code with the GNU Project debugger(GDB). GDB can be used with a lot of languages for example assembly, C, C++ and Rust.

## Generating debug symbols

First of all you need to tell nasm to generate debug information. This is done with `-g` and `-F dwarf`. The `-g` option tells nasm to generate debug information and the `-F dwarf` sets the debugging format to the standardized debugging format `DWARF`.

## Start GDB

Start gdb with `gdb <your_assemlby_program>` to enter its interactive shell. You can set breakpoints by writing `break <function_name or line number>`. By default gdb uses AT&T flavor to change to intel flavor type `set dissambly-flavor intel`. To start debugging the program type `run`.

## Debugging the program

The program will run until a crash happens or to any breakpoint you set and pause. If you want to look at the values currently in the registers type `info registers` or if you want to see the next instructions at the same time as the value of the registers type `layout regs`.

To execute the next instruction type `next`. If you want to step into a function call type `step`. If the program crashes gdb will tell you which line that was the last one executing. You can type `backtrace` to see the full stack trace
Advent of code, day 3
Tags: beginners, programming, 42, adventofcode
Published: 2021-12-03 23:28:47

Ok, day 3 part one was nice and simple. FIrst I defined a couple of utility static methods, then just rolled over the data.
In this code I managed to showcase a unique feature of 42 'for-in':
you can update the element under iteration!

```
Pow2 = {class method I (I that) =
  if that==0I 1I else 2I*This(that-1I) }
Is1 = {class method Bool(S that, I i) =
  that.startsWith(S"1" leftOffSet=i)}
MainPart1 = (
  input = Fs.Real.#$of().read(\"input")
  tot = I.List[0I;0I;0I;0I;0I;0I;0I;0I;0I;0I;0I;0I]
  var size = 0I
  for s in input.split(S.nl()) (
    size+=1I
    for var e in tot, i in Range(tot.size()) (
      if Is1(s i=i) e:=e+1I //update the value inside of 'tot'
      )
    )
  var gamma = 0I
  var epsilon = 0I
  for e in tot, i in Range(tot.size()).reverse() (
    if e+e>size gamma+=Pow2(i) 
    else      epsilon+=Pow2(i)
    )
  Debug(gamma*epsilon)
  )
```

The second part, I found it involved in a boring way. I think there must have been a smarted way to solve it, but I could not find it. I had to read the description a couple of time to understand that I had to look for the most common bit in the REMAINING elements...

```
Part2 = {class method I (S that, Bool geq) = (
  res = S.List()(for s in that.split(S.nl()) \add(s))
  size = res.left().size()
  var remaining = res.size()
  for  i in Range(size) (
    if remaining==1I ( Break() )
    e = Match.Count()(for s in res if s!=S"" \add(Is1(s,i=i)))
    seek1 = ( if geq e+e>=remaining else e+e<remaining )
    for var s in res if s!=S"" && seek1!=Is1(s,i=i) (
      s:=S"" remaining-=1I 
      )
    )
  var resI = 0I
  for s in res if s!=S"" (
    for j in Range(size), i in Range(size).reverse() (
      if Is1(s,i=j) resI+=Pow2(i)
      )
    )
  resI
  )}
MainPart2 = (
  input = Fs.Real.#$of().read(\"input")
  ogr = Part2(input,geq=\.true())
  co2sr = Part2(input,geq=\.false())
  Debug(ogr*co2sr)
  )
```
As you can see, I just end up calling the same function twice.
You can notice that I'm still unsure how to format my code:
for example I wrote

```
for var s in res if s!=S"" && seek1!=Is1(s,i=i) (
  s:=S"" remaining-=1I 
  )
```
instead of the more conventional 

```
for var s in res (
  if s!=S"" && seek1!=Is1(s,i=i) s:=S"" remaining-=1I 
  )
```
or the even longer version with also the 'if' indented.
What would be more readable? and why?
Day 490 : Mind Up
Tags: hiphop, code, coding, lifelongdev
Published: 2021-12-03 22:49:57

_liner notes_:
- Professional : Worked on a demo for a blog post. Also finished up planning for 2022, well as much as I could, because you know, things change. Especially with the past couple of years. Who could have see that?!

- Personal : Went through some tracks for the radio show last night. Watched the 3 6 Mafia and Bone Thugs-N-Harmony Verzuz battle. It was okay. Did some more research on my stream projects. The show ended pretty late so I went to sleep.

![Overhead photo of the coastline of Big Sur, CA, USA with a lot of trees and the waves from the ocean crashing into it and some smaller islands nearby.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwpaavftnkuliyxd3kke.jpg)

It's Bandcamp Friday so I'm going to pick up some new music and put together this week's radio show. Good thing is that I over prepared on the number of tracks last week, so I don't need to do as much, but I'll probably still do it so that I can keep ahead. Oh and during my lunch break I shut down some servers I had running. I woke up to an almost $300 charge! Messed my mind up! haha I got an email last month about suspicious activity on one of my servers and said it could be doing crypto mining. I looked and everything seemed normal, so I didn't pay any mind. My plan was to copy over he files from the server at a later time. Well, I saw the charge and shutdown all my random servers that I was doing experiments on. The problem server was the one I was using o run GitLab to store my side project's code. Maybe I didn't patch something, no clue, but I checked and I have most my current projects on my Chromebook and hopefully the older ones on are on another laptop. Going to go through them this weekend and back up to GitHub. I really have no business setting up servers if I'm not going to keep up with them. haha Lesson learned.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 6iOfbpxiV9I %}
Cheating and building secure iOS games
Published: 2021-12-03 08:32:27

---
title: Cheating and building secure iOS games
published: true
description: Hacking your own iOS app in order to cheat can tell you how to further secure it.
co-author: Stijn Spijker
tags: 
canonical_url: https://xebia.com/blog/developing-secure-ios-games/
---
You probably have one of the million games where you earn achievements and unlock specials on your iPad or iPhone. If you develop games, you’ve probably wondered about people cheating your games? In this blog we’re going to show you how to try cheating out yourself and how to build secure iOS games.The actual question at hand: how can you break the integrity of an app on iOS?

---

## Cheating is influencing state
A lot of games on the iOS App Store have absolutely zero protection against cheating. Either because developers don’t even consider adding some security or because they might think it’s very hard or expensive to implement. In this post we’re going to be looking at some games that use local state, such as a database or plists (or other formats) on your device. These kinds of games can be cheated by opening up some local files and editing values to your liking.

## Influencing the local state
For this example we’re going to use a random game that we found in the appstore. This game does not send any game-related data to the server and thus probably saves everything locally.
 
We’re using a jailbroken device to be able to access the device file system. This reveals that the game saves a database file in the apps documents folder. When we open this with an SQLite DB Browser we can read and modify the database. In this case the SQLite database contains two interesting keys named `registry-stash-stars` and `registry-stash-coins`. We edit these files with SQLite and re-upload the database to the device.

![Scoring table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95bf7h1xyz256hn1noqn.png)

We restart the game and we have 15000 stars and 5000 coins!

## Securing your iOS game as a developer
The best way to prevent local state manipulation is, you guessed it: server side validation. Of course, if you don’t want to work with servers, you could also take a look at encrypting your data (hiding it) and then HMAC it (verifying integrity). Don’t forget to store the keys for encryption and the HMAC creation in the keychain. It won’t be watertight but you just got rid of quite some cheaters.
GameOff 2021 - How we made entire game in one month? 🤯
Tags: unity3d, showdev, gamedev, programming
Published: 2021-12-03 22:47:25

Hi, after one month of after-hours development, we've made game for GameOff 2021 game jam (hackathon) organised by Microsoft and GitHub. 

Here is the progress video and final results:
{% youtube gmboSkO28F4 %}

Code repository:
{% github pilotpirxie/die-bug %}
Deep Clean Your Android Studio to Fix Weird Issues
Tags: android, beginners
Published: 2021-12-03 22:43:41

**Apart from fixing the weird issues, it also helps to clean up your disk spaces!**

I have encountered quite numbers of weird compilation and some run-time issues. I wonder is this very common to Android developer in their day-to-day work?

These are the steps I usually do to resolve them:

## 1. Clean Project

The first thing I do is "**Build -> Rebuild Project**". It is similar as "**Build -> Clean Project**" and "**Build -> Make Project**". Sometimes it works and sometimes it doesn't work.

![deep_clean_android_studio_01.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1634357995254/V9ietHYIR.gif)

## 2. Invalidate Caches

If "Clean Project" doesn't work, I will try "**File -> Invalidate Caches / Restart ...**"

![deep_clean_android_studio_02.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1634361236600/uMBg8Rgyf.gif)

Both steps work 99% of the time until I see this type of error indicating something wrong with the cache in the `.gradle` folder.

![deep_clean_android_studio_03.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1634361431447/qy06bj_1L.png)

## 3. Delete .gradle Folder
So I go to the user home directory and delete the `.gradle` folder, then the issue is resolved. This folder can be safely deleted, and it may be better if you close Android Studio before deleting it.

The folder is very big! So it can also save you a lot of disk spaces. Mine one is 10G bytes. 

Your project folder also have the `.gradle` folder. I haven't encountered any issues yet that I need to delete it. 

## Summary
Well, these are the 3 steps I always do when I encounter weird errors. The last step "**delete `.gradle`**" folder is not usual, but it helps to save disk spaces. Maybe it is good to clean this up once a while?

The second step "**Invalidate Caches**" is less usual than the first step - "**Clean Project**" which is my daily routine in Android development.

---

*Originally published at [https://vtsen.hashnode.dev](https://vtsen.hashnode.dev/deep-clean-your-android-studio-to-fix-weird-issues)*.