teleren/devto huggingface dataset:
Objetos e Estruturas de Dados (Código Limpo: Que Bruxaria é Essa?!?! - Parte 4)
Tags: cleancode, javascript
Published: 2021-09-25 16:29:52

## Use ***getters*** e ***setters***

O uso de ***getters*** e ***setters*** para acessar dados pode ser melhor que simplesmente procurar por uma propriedade em um objeto. Talvez você pergunte: "Por quê?!". Bom, aqui você vai ver uma lista desorganizada de motivos:

* Quando você quer fazer mais do que obter a propriedade de um objeto, você não tem que procurar e mudar cada dado acessível na sua base de códigos.
* Simplifica a inclusão de validações ao usar um `set`.
* Encapsula a representação interna.
* Facilidade de inclusão de tratamento de registros e erros no momento de obtenção e configuração.
* Você pode fazer o carregamento lento das propriedades do seu objeto, vamos dizer obtendo-as de um servidor.

### Não é recomendável:

```javascript
function makeBankAccount() {
  // ...

  return {
    balance: 0
    // ...
  };
}

const account = makeBankAccount();
account.balance = 100;
```

### É recomendável:

```javascript
function makeBankAccount() {
  // this one is private
  let balance = 0;

  // a "getter", made public via the returned object below
  function getBalance() {
    return balance;
  }

  // a "setter", made public via the returned object below
  function setBalance(amount) {
    // ... validate before updating the balance
    balance = amount;
  }

  return {
    // ...
    getBalance,
    setBalance
  };
}

const account = makeBankAccount();
account.setBalance(100);
```

## Faça com que objetos tenham membros privados

Esse feito pode ser alcançado por meio de ***closures*** (ES5 e versões anteriores)

### Não é recomendável:

```javascript
const Employee = function(name) {
  this.name = name;
};

Employee.prototype.getName = function getName() {
  return this.name;
};

const employee = new Employee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined
```

### É recomendável:

```javascript
function makeEmployee(name) {
  return {
    getName() {
      return name;
    }
  };
}

const employee = makeEmployee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
```

E aí? Gostaram? Até a próxima tradução! 🤗
Postman Collections & Environment Variables
Published: 2021-09-25 16:08:58

### Intro to Collections
* Collection in Postman means a group of API requests that are already saved in the Postman and can be arranged into folders. Any number of folders can be created inside a collection.
* Putting similar requests into folders and collections helps the client in better organization and documentation of their requests.
* All the APIs requests can be stored and saved within a collection, and these collections can be shared amongst the team in the Postman workspace.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tunoq7q6ng67i2wvabhs.png)

### Advantages of creating collections
* **Easy APIs import and export**
A collection can be imported or exported. Thus it can save time for transferring the requests.
* **Request categorization**
Requests can be grouped into folders and collections for easy access.
* **Passing data among requests**
Scripts can be used to pass data between API requests.
* **Running collections/folders**
You can run individual requests or folder or collection as a whole in the Postman.
* **API documentation**
Postman provides you an option to add a name and description to your request, folder, and collections.
* **Building Test suits**
Test scripts can be added to requests, and integration test suites can be built.
* **Time-saving**
Setting any variable for collections will automatically apply the same to the folders generated under the collection and requests; thus, it saves time.

### Environment in Postman
An environment in Postman is a set of key-value pairs. An environment helps us to differentiate between the requests. When we create an environment inside Postman, we can change the value of the key value pairs and the changes are reflected in our requests. An environment just provides boundaries to variables. When we create different environment we can make track of all the variables and how to use them inside our requests. There can be many variables inside one environment. At once, we can work only in one environment although we can create any number of environments in Postman.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61jp2zih8fk1d7qpa392.png)

### Set Environment Variable in Postman
A variable in the Postman is same as in any programming language. A variable is an entity whose value can be changed. The key part in the key-value set in environment is called variable. This variable can have any value and in place of the key we can use the variable name in every request. This will be clear with an example shown below and steps shown thereafter. The below image shows three variables inside environment Test Environment 1

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jp6a1gqaknevuu9hxpkq.png)
Today I learned - Day 13 (25 SEP 2021, Sat)
Published: 2021-09-25 16:02:04

## NOTE: 
I'm posting my personal journey of participating in a boot camp and of becoming a developer. So it might not contain useful information at the moment. But hopefully, after four months, I will post things that are encouraging to aspiring developers, with current posts as evidence of how much I have grown since the beginning. 


#### Hours put-in today: 7h 39mins clocked.


## What I did/learned:
- Read the FLASK documentation to have a better understanding of FLASK. It really helped me understand FLASK a lot. For anyone who just went through a video tutorial of FLASK, I recommend reading the documentation. 

- Studied about the HTTP request methods. Beforehand, I thought "get" and "post" methods were a part of ajax. I now know that it's one of the HTTP request methods, and Jquery.ajax() is a part of Jquery library that performs "an asynchronous HTTP (Ajax) request." 

- built some web app with GET and POST APIs (followed a tutorial, but I only referred to it only when I needed help). 

- followed a tutorial of making a web app that shows uploaded images users upload from their local environment. 
   Description: client side(upload files) -> server side -> MongoDB -> server side -> client side. 


## Learned of:
- Template literals. ${}. For a few days, I thought `${}` was part of jqeury. So I searched hours trying to find out the difference between $() and ${}. I now know that the former is jquery, and the latter is ES6 JS. 
- The concepts of client-side rendering and server-side rendering.
Assembly Language Lab SPO600 - Lab 02
Tags: beginners
Published: 2021-09-25 15:58:12

Hello everyone, I'm Tuan Thanh Tan aka Dustin. If you happen to read this blog. Thank you!

This is the lab 2 for my SPO course. This lab is about writing code in 6502 assembly language. One of the most difficult and cumbersome lab I've ever had. 


```
lda #$00	; set a pointer at $40 to point to $0200     
	sta $40 
	lda #$02 
	sta $41

	lda #$05	; colour number

	ldy #$00	; set index to 0

top: sta ($40), y;  

top:        sta ($40), y         ; set pixel 

              iny                      ; increment index

              cpy #$20            ; compare y value with 20. If the index is 20, end the loop

              bne top

              lda #$05

              sta $41               ; point the last page 

              lda #$06             ; set color blue
              ldy #$e0             ; set the index to indicate the last linex

bottom:  sta ($40), y      ; set pixel  
              iny                      ; increment index  
              bne bottom         ; continue until done the line
right_left: lda #$07         ; set index to 0 
        
              sta ($40), y          ; set the color yellow 

              tax                       ; transfer a to x   
              tya                       ; transfer y to a  
              clc                       ; clear carry flag to do ADC (add with carry) 
              adc #$1f              ; add with #$1f so it indicates the last line   

              tay                       ; transfer a to y  
              txa                       ; transfer x to a  

              lda #$04              ; set the color purple  
     
              sta ($40), y          ; set pixel            
              iny                       ; increment index  
              bne right_left       ; continue until done the page   : 2

              inc $41                ; increment the page      
              ldx $41                ; get the page      
              cpx #$06             ; compare with 6 (the last page is 05 so if it is 06, it means all pages are already painted)

              bne right_left       ; continue until done all page

```

I found this language has a great deal of complexity and difficulties. But as time goes on, I'll get used to it.


For the performance, I used [this website](https://www.masswerk.at/6502/6502_instruction_set.html) to get the number of circles of each instruction and sum it up. The result that I have is 106.
Developer Diaries: Week 11 - Exploring Libraries
Tags: typescript, react, devjournal, library
Published: 2021-09-25 15:32:58

This week - aside from surviving food poisoning - I really only had one mission. Another dev on our team had built a modal asking for a user to select their `country` and `timezone`, and I needed to use some libraries to get those options and make sure they were consistent with the same libraries we used for a feature we're planning to release down the road that also has a form asking users to select those options.

Thankfully I'd already worked with them before, but this time I got to take the reins with implementing them and really got to dive right in to not just copying and pasting, but actually solving through all the bugs to make that code work on this new modal, which was on an entirely different branch of the app.

I solved most of the bugs but not everything (got a little stuck on a weird spread operator typescript nonsense... if you ever see "oh no you can't use that, try using `--downlevelIterator`", well you can do that, or you can use `Array.from(your_array_you_were_using_the_spread)`.

# Using `Moment.Tz` library

I used the [Moment-Timezone](https://momentjs.com/timezone/) library, which returns, well, all the timezones! Super easy to get started with, just add using `npm` or `yarn` to add it, and then add `import moment from 'moment-timezone';` to the top of your file.

![getting time zones](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kogf5r929gzpxrbe2kya.png)

I needed to get a wee bit fancy with it, and this returns ALOT of things, but I only needed the names of the timezones. So I pulled out just the names, and then sorted them alphabetically.

![moment timezone guess](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/asungcj33cqic4n3cwdu.png)
 

Then to make it easier on a user,  I used the guess function to look in the browser and figure out what their timezone is, and if it's part of my list, then woohoo awesome, if not, then just return an empty string and make them go select it.


# Using Iso

For the country field, we needed a standard list of countries, so I used the [i18n iso countries library](https://www.npmjs.com/package/i18n-iso-countries). (Easy to install from `npm` or `yarn`. And just add `import { getNames } from 'i18n-iso-countries';` to the top of your file.

![iso-countries-library](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b8hnsoozgnetcs1bxwn.png)
 
I asked it to grab the names of countries, then look at the first couple letters we pull on a user's locale to determine if we show in another language or in English, if we don't have their locale info.

Then I created an array of objects with a value and text of the country codes and country names, along with pushing a default option of "Select country" as the first option.

Viola!!

Here's how it looks.

![demo of country and timezone options](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uj9w2tvrw1j5g7qjxhjf.png)
How to Filter List Elements in Python?
Tags: python, programming, codenewbie, tutorial
Published: 2021-09-26 08:08:10

---
title: How to Filter List Elements in Python?
published: true
date: 2021-09-25 15:05:08 UTC
tags: #python #programming #codenewbie #tutorial
canonical_url: https://itsmycode.com/how-to-filter-list-elements-in-python/
---

ItsMyCode |

The **`filter()`** method filters the given sequence of elements with the help of a function that tests each element in the sequence to be true or not.

**Syntax:**

**filter(function, sequence)**

**Parameters:**

- **function** : the function that tests if each element of a sequence true or not.
- **sequence** : the sequence which needs to be filtered. It can be any iterable object such as sets, lists, tuples, or containers.

**Returns:** The method returns an iterator that is already filtered.

## **Example** – Filter a Python List with filter()

```python 
# function that filters vowels
from os import truncate

def even(x):
    if x%2==0:
        return True
    else:
        return False

# creating a list in Python
mylist= [3,5,1,5,7,8,2,6]

# using filter function to find even numbers
filtered = filter(even, mylist)

print('The even numbers are:')
for s in filtered:
	print(s)

```

**Output**

```python 
The even numbers are:
8
2
6
```

## Example – Python Filter List with Lambda

Alternatively, we can use a lambda function statement to create the function to pass it as an argument to the**` filter()`** method.

```python 
# creating a list in Python
mylist= [3,5,1,5,7,8,2,6]

#filter all the odd numbers using list Comprehension
result = [x for x in mylist if x%2!=0]
print('The odd numbers are ',list(result))

#filter all the even numbers using list Comprehension
result = [x for x in mylist if x%2==0]
print('The even numbers are ',list(result))
```

**Output**

```python 
The odd numbers are [3, 5, 1, 5, 7]
The even numbers are [8, 2, 6]
```

## Example – Filter with List Comprehension

The best way to filter the list elements is using the list comprehension statement **`[x for x in list if condition]`**. The condition can be replaced with any function which can be used as a filtering condition.

```python 
# creating a list in Python
mylist= [3,5,1,5,7,8,2,6]

#filter all the odd numbers using lambda
result = filter(lambda x: x % 2 != 0, mylist)
print('The odd numbers are ',list(result))

#filter all the even numbers using lambda
result = filter(lambda x: x % 2 == 0, mylist)
print('The even numbers are ',list(result))
```

**Output**

```python 
The odd numbers are [3, 5, 1, 5, 7]
The even numbers are [8, 2, 6]
```

The post [How to Filter List Elements in Python?](https://itsmycode.com/how-to-filter-list-elements-in-python/) appeared first on [ItsMyCode](https://itsmycode.com).
Check Status Code URL Google Sheet
Published: 2021-09-25 14:18:32

function getStatusCode(url) {
  var url_trimmed = url.trim();
  // Check if script cache has a cached status code for the given url
  var cache = CacheService.getScriptCache();
  var result = cache.get(url_trimmed);
  
  // If value is not in cache/or cache is expired fetch a new request to the url
  if (!result) {

    var options = {
      'muteHttpExceptions': true,
      'followRedirects': false
    };
    var response = UrlFetchApp.fetch(url_trimmed, options);
    var responseCode = response.getResponseCode();

    // Store the response code for the url in script cache for subsequent retrievals
    cache.put(url_trimmed, responseCode, 21600); // cache maximum storage duration is 6 hours
    result = responseCode;
  }

  return result;
}
stack in python using LinkedList or List
Tags: python, stack
Published: 2021-09-25 14:14:11

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nda7bpl5ik5x00rb7pdl.png)

1. Stack is a <strong>type of data structure</strong>. They are preferred over arrays or lists due to their fast insert and delete operations.

2. Stack works on the <strong>last in first out (LIFO)</strong> 
principle i.e <strong>insertion</strong> and <strong>deletion</strong> happens at only one end.

3.stack has an <strong>O(1) time complexity for pop or push operation</strong>.

<p>look at the code below to understand how to implement stack on our own and how to use it.</p>

<strong>Note:</strong> We can implement a stack using LinkedList or lists in python. Both implementations work fine and have the same time complexities for all the operations but I prefer implementing them using a list because it's much easier.

##Stack using list
```python
class stack:
    def __init__(self):
        self.data = []

    def push(self,elem):
        self.data.append(elem)

    def pop(self):
     try:
        popped_item = self.data.pop()
        return popped_item
     except IndexError:
        print('Stack Underflow')

    def peek(self):
     try:
        print(self.data[len(self.data)-1])
     except IndexError:
        print('No elements in stack')

    def size(self):
      return len(self.data)

my_stack = stack()
my_stack.push('1')
my_stack.push('2')
my_stack.push('3')
print("data:", my_stack.data, "size:", my_stack.size())
```
###Output
```output
data: ['1','2','3'] size: 3
```
##Stack using linkedlist
```python
class node:
  def __init__(self,val):
    self.val = val
    self.next = None

class linkedListStack:

  def __init__(self):
    self.head = None

  def push(self,val):
    if (self.head == None):
      self.head = node(val)
    else:
      new_node = node(val)
      new_node.next = self.head
      self.head = new_node

  def pop(self):
    if (self.head == None):
      print('Stack underflow')
    else:
      popped_val = self.head.val
      self.head = self.head.next
      return popped_val

  def peek(self):
    if (self.head==None):
      print(None)
    else:
      print(self.head.val)

  def display_stack(self):
    dummy = self.head
    while(dummy):
      print(dummy.val,end=" <- ")
      dummy = dummy.next

lls = linkedListStack() 
lls.push(1)
lls.push(2)
lls.push(3)
lls.push(4)
lls.pop()
lls.peek()
lls.display_stack()
```
###Output
```output
3
3 <- 2 <- 1 <-
```
Implementation of Queue in python
Tags: python, queue, datastructures
Published: 2021-09-25 14:13:37

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxbkjjvgsbhedqu6ws0q.png)

1.Queue is a type of data structure.Queue is based on the principle <strong>first in first out (FIFO)</strong> i.e first inserted element will be deleted first.

2.In queue Insertion of elements is done at one end <strong>i.e rear</strong> and deleting of elements is done at other end 
<strong>i.e front</strong>.

3.Queue works similar to queue at a <strong>ticket counter</strong> the first person in the queue is the <strong>front</strong> and the last person is the <strong>rear</strong>.

<p>Now let us look at some example to implement a <strong>queue using a LinkedList</strong></p>


##Example:
```python
class node:
    def __init__(self,val):
        self.val = val
        self.next = None

class queue:
    def __init__(self):
        self.front = None
        self.rear = None

# push element on rear side
    def push(self,val):
        if (self.rear == None):
            self.front = node(val)
            self.rear = self.front
        else:
            new_node = node(val)
            self.rear.next = new_node
            self.rear = self.rear.next

# pop deletes the first inserted element in queue in front side
    def pop(self):
        if (self.front == None):
            print('No elements to pop in Queue')

        else:
            self.front = self.front.next

# To show where front is currently at
    def show_front(self):
        print('front: ',self.front.val)

# To show where rear is currently at
    def show_rear(self):
        print('rear: ', self.rear.val)

    def display_queue(self):
# To display the whole queue we have to traverse the linkedList
# Using a dummy node starting from head
        q = []
        dummy = self.front
        while(dummy):
            q.append(dummy.val)
            dummy = dummy.next
# Reverse 'q' to avoid confusion
        q.reverse()
        print('Queue data: ', q)
```
###Input
```input
x = queue() # instantiates a queue object named 'x' 
x.push(1)
x.push(2)
x.push(3)
x.push(4)
x.push(5)
x.push(6)
x.push(7)

x.display_queue(), x.show_front(), x.show_rear()
x.pop()
# front is changed after pop operation
x.display_queue(), x.show_front(), x.show_rear()
```
###Output
```output
Queue data:  [7, 6, 5, 4, 3, 2, 1]
front:  1
rear:  7
# after pop operation
Queue data:  [7, 6, 5, 4, 3, 2]
front:  2
rear:  7
```
try-except in Python
Tags: python
Published: 2021-09-25 13:51:44

Hello! Today we will learn how to use the try-except statements. Here is a scheme of how try-except works:
```python
try:
    # This code tries to execute, but if there's an error, stop execution
except <err_name>:
    # This code will get executed if the try block fails to execute
else:   # Optional
    # This code executes after the try block, only if try block doesn't return an error
finally:   # Optional
    # This code will always get executed
```
Also, you will need to replace __<err_name>__ with the error you want to catch. Ok, so let's see an example:
```python
i = input()

try:
    i = int(i)
    print(f"Your number: {i}.")
except TypeError:
    print("Your input isn't a number!")
finally:
    print("Goodbye!")
```

if we input 6673 we will get:
```
Your number: 6673.
```
With that, Goodbye and have a nice day!