teleren/devto huggingface dataset:
Chrome eklentileri ile SPA'leri desteklemek
Tags: chrome, extension, spa
Published: 2022-02-23 20:49:49

---
title: Chrome eklentileri ile SPA'leri desteklemek
published: true
description: SPA'lerde eklentilerin çalışması nispeten biraz daha zordur, peki bunu nasıl çözeriz?
tags: chrome,extension,spa
//cover_image: https://direct_url_to_image.jpg
---

Chrome eklentileri ile sayfa içeriğini modifiye edebilir ve belirli sınırlar dahilinde sayfa içeriğine müdahale edebilirsiniz. Chrome eklentileri [content-script](https://developer.chrome.com/docs/extensions/mv3/content_scripts/) adı verilen dosyalar ile DOM API üzerinden değişiklikler yapmanıza olanacak sağlar.

Örneğin bir sayfa içerisindeki bütün linkleri bularak bunların renklerini content-scriptler ile değiştirebilirsiniz.

Normal sayfalarda basitçe [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) olayını (event) yakalayarak işlemimizi yapabiliriz. Aşağıdaki örnekte basitçe "load" olayını yakalarayarak sayfada işlemler gerçekleştirebilirsiniz.

```js
window.addEventListener ("load", function () { 
	// Kodunuz
}, false);
```

### Peki SPA'ler

SPA'lerde sayfa ilk yüklendiğinde `content-script`'imiz çalışacaktır. Yine link rengi değiştirme örneğinden gidecek olursak sayfa yüklendiğinde o sayfa içerisindeki bütün linklerin rengini değiştirecektir ancak başka sayfalara geçtiğinizde linklerinin renginin değişmediğini göreceksiniz.

### Peki çözüm nedir?

Eminim bu problem için birden fazla çözüm vardır ancak ben size kendi kullandığım yöntemden bahsedeceğim. 

Çözüm için birkaç aşamaya ihtiyacımız var. İlk olarak arka plan komut dosyası kullanacağız. Arka plan komut dosyası, yeni bir sayfaya gitme, bir sayfayı kapatma vb. gibi bir tarayıcının tetiklediği olayları izlemek için arka planda çalışan bir programdır.

Bunun için manifest.json dosyamıza, aşakğıdaki bölümü ve `background.js`'i eklenti dosyalarımız arasına eklememiz gerekiyor.

```json
"background": {
  "scripts": ["background.js"],
  "persistent": true
}
```

Bu aşamada SPA sayfa değişimlerini yakalamamız için [webNavigation API](https://developer.chrome.com/docs/extensions/reference/webNavigation/)'ı kullanmamız gerek. Bunun içinse izinlerimizin arasına `webNavigation` eklememiz gerekiyor.

```json
"permissions": ["tabs", "webNavigation"]
```

Artık `background.js` içerisinde adres değişikliklerini takip edebiliriz

```js
chrome.webNavigation.onHistoryStateUpdated.addListener(details => {
  tabId = details.tabId;
  chrome.tabs.sendMessage(tabId, {name: 'page_changed'});
});
```

Basitçe bu kod parçası Chrome'da geçmiş güncellendiğinde gerçekleşen olayı yakalayarak değişikliğin yapıldığı taba dilediğimiz mesajı yolluyor. 

Artık `content-script`imizde bu mesajı dinleyerek dilediğimiz işlemi yapabiliriz.  Unutmayın `chrome.runtime.onMessage` birçok mesaj alacaktır bu yüzden mesajınıza bir isim vermenizde bu ismi filtreleyerek işleminizi gerçekleştirmenizde yarar olacaktır.

```js
chrome.runtime.onMessage.addListener(function(request, _sender, _sendResponse) {
  if (request && request.name === 'page_changed') {
    convertLinks()
  }
});
```
Arreglos al romper grub 
Tags: linux, fix, windows, grub
Published: 2022-02-23 20:48:24

Hace unos ya dos meses que trabajaba simultáneamente en Linux y Windows con un multi-boot (creo que se llama). Bueno el otro día decidí quitar Linux ya que me limitaba el disco de Windows y decidí quitar dicha partición desde Windows usando la tecla SUPR, todo correcto hasta que reinicio y veo que he roto grub xd. Mirando video todos decían de comandos que se usan en Linux o usando un pen y reparando desde un instalador de Windows. Pues yo decidí probar nuevas cosas ya que no tenia dicho PEN y dentro de la BIOS cambie el sistema de boot a CSM y nuevamente cambiar a EFI, al parecer esto reparo EFI y me permitió arrancar mi Windows sin complicación, esto no lo vi en ningún video y espero que os sea útil y no perdáis tiempo. Un gusto!
Dart basics - part 1
Tags: dart, flutter, basics
Published: 2022-02-23 20:19:21


**Dart** is an open-source general-purpose programming language. It is originally developed by Google and later approved as a standard by ECMA. Dart is a new programming language meant for the server as well as the browser. Introduced by Google, the Dart SDK ships with its compiler.


dart has many similarities to other languages

in this topics we are going to focus in some basics of this new languages  so can help you in your journey especially for those who want to try **flutter**

**Variables** :


in dart you van create variable use **var**   keywords , or instead you specify the variable type




 ` var x=   'abdo';
  
  //  or
      
  String y ='ahmed';`



  using **var**   is what they called it inferred type
 so the type of the variable is detected by it's value


**Note:**
when using var keyword to initialize variable with a value which from specific type  you cannot update the variable with value of different type

`
   var x=   'abdo';
  x=90;  //  show an error`


`Control Structure:`


    we mean the conditional  and iteration statements including:


    -  if elese   
    -  switch case
    - for loop
    - etc
**
IF ELSE**

 `int x =9;
  if(x>8){
    print("x  is bigger than 8");
  } else {
    
    print("x is less or equal  to 8");
  }`
  


**Loop**

 ` for(int c=0;c<9;c++){
     print(c);
   }`


same to for loop in other languages like **java**

there is special loop come with list type like an array
called **foreEach**

it is a callback for the array ,  it iterates through all elements of the given array


` List numbers =[2,232,23,89];
    numbers.forEach((n){
      print(n);
    });`





**SWITCH CASE **


     same as switch case in java and many languages



  
`  var name ='ali';
  
  switch(name){
    case 'ahmed':
      print('it is ahmed');
      
      break;
    case 'ali':
      print('it is ali');
      
      break;
      
    default:
       print('none of above');
      
      
  }
  `






continued...
TIL that code splitting is a must have for a performant React application
Tags: todayilearned
Published: 2022-02-23 20:02:51

## What I Learned

Today i learned code splitting in React. I have been hearing of it but never really understood why it was important till today.

## And why exactly is this interesting? 

While working on v2 of an open-source internet shutdown circumvention tool [SMSWithoutBorders](https://smswithoutborders.com), code splitting helped improve page load speeds solving the problem of blank pages due to large bundle sizes

I found [this tutorial](https://reactjs.org/docs/code-splitting.html) helpful
Testeando endpoints con Django Rest Framework
Tags: python, django, testing, webdev
Published: 2022-02-23 19:57:04

En mi trabajo decidimos empezar a utilizar tests unitarios como una manera rápida de identificar errores a la hora de llevar algo a producción.

Lo primero que hice fue testear una de las primeras funcionalidades del proyecto que yo mismo realicé(es un proyecto muy nuevo) y encontré diferentes maneras de hacerlo. 

- Endpoint a testear:
  - /topic/create/

- Permisos necesarios:
  - Estar logueado 
  - Ser administrador

Lo primero que tenemos que hacer es importar lo siguiente adentro del archivo test.py del proyecto:

```python
from rest_framework.test import APITestCase, APIClient
from django.urls import reverse
from rest_framework import status
from .models import *
```

Lo siguiente es crear una clase en donde vamos a reunir todos los casos de testeos:

```python
class TestTopics(APITestCase):
```

es importante que esa clase herede de APITestCase.

Una vez que tenemos la clase vamos a crear el método de configuración: acá adentro vamos a escribir todas las configuraciones necesarias para poder testear/probar nuestro endpoint, crear usuarios, asignarle permisos, crear grupos etc..


```python
class TestTopics(APITestCase):
    def setUp(self):
        
        administrator_group = Group(name='administrador')
        administrator_group.save()
        
        administrator_group = Group.objects.get(name='administrator')
        
        admin1 = User(username="administradorprueba", first_name="Admin", last_name="Dos")
        admin1.set_password("administradorprueba")
        admin1.save()
        admin1.groups.add(administrator_group)
```

DATO IMPORTANTE: cuando vayamos a testear nuestro endpoint y este necesite que un usuario se encuentre logueado y con todos sus permisos, no hace falta que hagamos una petición para loguearnos y obtener el token para después hacer la petición hacia nuestro endpoint. DRF nos trae por defecto en APIClient un método llamado force_authenticate al que nosotros le pasamos la instancia de nuestro usuario y se loguea por nosotros.

```python
    def test_create_topic_only_name_and_description(self):

        client = APIClient()
        data = User.objects.get(username='administradorprueba')
        client.force_authenticate(user=data)

        response = client.post(
                    reverse('create_topic'), {
                    'name': 'productos recomendados',
                    'description': 'solo productos bien rankeados por la comunidad',
                },
                format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
```

Como ven, ahora a través de client podemos enviar la petición después de habernos logueado con force_authenticate.

En esta línea **reverse('create_topic')** lo que estamos haciendo es buscar el endpoint con el name="create_topic" definido adentro de nuestro script urls.py


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0pa5brtn24ows39jyhpf.png)
Estructura Datos. Conceptos
Tags: spanish, tutorial, computerscience, español
Published: 2022-02-23 19:54:09


Si acabas de encontrar esta publicación, antes de continuar te recomiendo que le des un vistazo a [Introducción a Estructuras de Datos](https://dev.to/szalimben/introduccion-a-la-estructura-de-datos-1ak2) el cual brinda una introducción a los conceptos preliminares para comprender las Estructuras de Datos.

---

Una **Estructura de Dato** es una colección de datos que pueden ser caracterizados por su organización y las operaciones que se definen en ella, es la implementación de un TDA en algún lenguaje de programación, es decir, la representación de algún tipo de dato y de sus operaciones asociadas.

### Simples y Compuestos
Se dice que son tipos simples o primitivos cuando se definen sobre sí mismos, es decir, no están compuestos de otras estructuras de datos, *e.g.* números enteros, reales y carácter (char). Mientras que aquellas estructuras que se definen en función a otros se denominan compuestos o agregados, es decir, están construidos basados en tipos de datos primitivos, *e.g*. el tipo cadena (string) basado en el conjunto de caracteres.

![Datos Simples y Compuestos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyn2k69amqf6yro4lehd.JPG)
>
> Cada lenguaje de programación dispone de su propio conjunto de tipos primitivos y compuestos
>

### Estáticos y Dinámicos
Las estructuras de datos estáticas son aquellas en las que el tamaño ocupado en memoria es fijo, este se define antes de que el programa se ejecute y el tamaño reservado de memoria no puede ser modificado durante la ejecución del programa.

Mientras que las estructuras de datos dinámicas se pueden ampliar y comprimir a medida que se requieran durante la ejecución del programa, es decir, pueden reservar y liberar espacios de memoria de forma dinámica.

En la siguiente figura se observa que la estructura *Vector*, tiene un tamaño igual a la cantidad de letras del abecedario, por lo tanto ya no se pueden agregar más elementos, esta estructura es estática. Por otro lado, la estructura *Grafo* está compuesta por otras estructuras de datos dinámicas denominadas *Nodos*, que pueden ser instanciadas en cualquier momento, es decir, se pueden agregar más elementos en tiempo de ejecución del programa, esta estructura es dinámica.

![Estáticos y Dinámicos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vupgz56sg45p8yzvdj3x.png)

### Lineales y No lineales
Las estructuras de datos lineales son aquellas donde los elementos ocupan lugares sucesivos en la estructura y cada uno de ellos tiene un único sucesor y un único predecesor.
Sin embargo las estructuras de datos no lineales no cumplen con esta restricción.

![Lineales y No Lineales](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/she4ceq3n0chvux1c9st.png)

---

¡Gracias por leer! 

Ponte en contacto en Twitter [@sZalimben](https://twitter.com/sZalimben), y si te gusta mi contenido, puedes *[invitarme un café](https://www.buymeacoffee.com/szalimben)*.
Variable Keywords in JavaScript: var, let, and const
Published: 2022-02-23 19:18:52

There are three keywords in JavaScript that are used to declare variables. These are var, let, and const. This article will show the main differences between the three of them.

**var**

the var keyword is the oldest of the three in JavaScript.  Unlike const and let, it is globally scoped, not block scoped.  The one exception to this rule is if the var is declared within a function.  We can refer to the var keyword as "function scoped" for this reason.  Here is an example:  

```
if(5 === 5){
var some = 6;
};

function test(){
  var thing = 5;
};
console.log(some);
//prints 6 to the console

console.log(thing);
//Console throws ref error: thing is not defined;
```
The var keyword is also unique in that its declaration is hoisted to the top of the global scope as long as it is not declared within a function.  The var is initialized with a default value of undefined until it reaches the point in code where it the author initialized it.  For example:

`
console.log(foo);
var foo = 'bar';
console.log(foo);
`
Outputs:
`
undefined
bar
`

**let**

The let keyword shares a couple similarities to the var keyword in that it can be reassigned and can not be accessed when declared within a function.  Unlike var, a let variable is scoped to if blocks and loop blocks.  It is scoped to whatever set of curly braces contains it.  We can more simply call lets "block scoped" because it is confined to whatever code block encapsulates it.  It should be mentioned that the let variable is hoisted to the top of the scope, but unlike var, the let variable is not initialized as undefined until it reaches the point code where the let was first initialized.  The console will instead throw a reference error.  An example will provide more detail:

`
if (2 + 2 === 4){
  let town = 'car';
  console.log(town); // prints 'car'
};
console.log(town); 
//throws reference error: town is not defined

console.log(babe); ref error: babe is not defined;
let babe = 'pig'
console.log(babe); // prints 'pig';
`

**const**

The const keyword is very similar to let.  It is block scoped.  It also is hoisted in the same fashion as let.  The major difference is that it can not be reassigned.  Also const variable can not be declared without initiation.  However you can perform functions on const variables.  Let's take a look:

`
const TOP = 'hat';
TOP = 'dog'; //Type Error: assignment to constant variable;
`
`
const NUMBERS = [1, 2, 3]
NUMBERS.pop();
console.log(NUMBERS); // prints [1,2];

**Conclusion**

It is generally best practice to use const by default when declaring/initializing variables.  Because let and const are block scoped, it keeps the global object from being cluttered with many undefined variable at the top.  Another reason is that it acts as a security measure to keep developers from making mistakes when defining variables.  If one decides that they are going to need to change the value of a const, one can always go back and change the initial const to a let.  If a developer knows that they will need to change the value of a variable later on, they can use let instead of const.

`
Announcing the AppSec Ambassador Program
Tags: cybersecurity, softwareengineering, applicationsecurity, informationsecurity
Published: 2022-02-24 21:07:48

---
title: Announcing the AppSec Ambassador Program
published: true
date: 2022-02-23 19:10:37 UTC
tags: cybersecurity,softwareengineering,applicationsecurity,informationsecurity
canonical_url: https://blog.shiftleft.io/announcing-the-appsec-ambassador-program-ee90975d007c
---

#### Passionate about securing software? Become an AppSec Ambassador!

![](https://cdn-images-1.medium.com/max/1024/0*D3RDVQqJnz4ATV0y)
_Photo by Emmanuel Ikwuegbu on Unsplash_

Interested in helping developers write secure code from the start? ShiftLeft has launched a program to support you in the mission of helping your community write secure code.

We will be financially supporting conference speakers, content creators, and infosec influencers. Read on to find out more!

### The ShiftLeft conference scholarship

Want to share your knowledge about SAST, SCA, and the secure development processes at a conference? Here at ShiftLeft, we are committed to helping developers improve code security and show developers how they can stay secure while continuously shipping cool products.

If you’d like to share your knowledge at a conference, we’ll help you with your conference abstract submission and fund your travels to an in-person event. Apply here for the scholarship: [https://go.shiftleft.io/ambassador-conference-scholarship-program](https://go.shiftleft.io/ambassador-conference-scholarship-program).

### Your content, our support

We believe that security is a team effort between developers and security professionals, and a big part of securing the Internet is to share knowledge about security.

Create blog posts, videos, or live streams about topics related to application security and share them with your network! We will help promote your content on ShiftLeft’s accounts. Best pieces of educational content will also win a cash prize and exclusive ShiftLeft swag! Submit your content here: [https://go.shiftleft.io/ambassador-content-program-fund-program](https://go.shiftleft.io/ambassador-content-program-fund-program).

### Social competitions

Want to spread the word about the SAST and ShiftLeft? Post about @shiftleftInc, or #shiftleft to be entered into our social competition for a cash prize or exclusive swag. Start posting on Twitter and LinkedIn!

### Join our ambassador network

Join the people defending applications on the frontlines, and stay in touch with the latest best practices in cybersecurity from your ambassador community. Join us here: [https://discord.com/invite/5vj9YACAK3](https://discord.com/invite/5vj9YACAK3).

* * *
How to add pagination to your custom relationship fieldtype in Statamic
Tags: statamic, extending, fieldtype, laravel
Published: 2022-02-23 18:54:27

Usually when building a custom relationship fieldtype you want to work with data from somewhere else than Statamic. 

In this example we extended the relationship fieldtype in order to provide a list of imported tags. Thanks to the [Statamic docs](https://statamic.dev/extending/relationship-fieldtypes), this is pretty easy.

```php
class Tags extends Relationship
{
    protected array | string $tags;

    // Fetch tags from api. 
    // Using a facade makes it nice to read and easier to test.
    public function __construct()
    {
        $this->tags = Api::tags();
    }

    
    // Define columns.
    protected function getColumns()
    {
        return [
            Column::make('title'),
        ];
    }

    // Take search requests into account. 
    // Just comparing strings. Nothing fancy.
    public function getIndexItems($request)
    {
        return collect($this->tags)
          ->filter(function ($tag) use ($request) {
            if (! $request->search) {
                return true;
            }

            return Str::contains($tag['title'], $request->search);
        });
    }
}
```

In many cases this would already be it. But what if you have a huge amount of tags or items that need to be loaded into Statamics `selector stack`?
I found that loading about 16000 tags at once into the selector stack would either cause unbearable loading times or  even make the browser freeze.

This issue could be solved by enabling pagination. But unfortunately the relationship fieldtype does not automatically enable pagination when loading a specific number of items.

In order to do so and show pagination at the bottom of the selector stack you need to return an instance of the `\Statamic\Extensions\Pagination\LengthAwarePaginator` instead of a collection in the `getIndexItems` method. 

This could be done like this:

```php
public function getIndexItems($request)
    {
        $tags = collect($this->tags)->filter(function ($tag) use ($request) {
            if (! $request->search) {
                return true;
            }

            return Str::contains($tag['title'], $request->search);
        });

        return $this->paginate($tags);
    }


    protected function paginate($tags): LengthAwarePaginator
    {
        $currentPage = Paginator::resolveCurrentPage();
        $perPage = 50;
        $total = $tags->count();
        $result = $total ? $tags->forPage($currentPage, $perPage) : collect();

        return new LengthAwarePaginator($result, $total, $perPage, $currentPage, []);
    }
```

_Curios about the LengthAwarePaginator? Read more in the [Laravel Docs](https://laravel.com/docs/8.x/pagination#manually-creating-a-paginator)_

Et voilà - a custom relationship fieldtype with added pagination: 

![A custom relationship fieldtype with added pagination in Statamic](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75kjlxwsn8q9fzmw4zqj.png)
How to use SetTimeout in JavaScript
Tags: javascript, beginners, tutorial, html
Published: 2022-02-23 18:47:01

In this video we are going to learn about the javascript setTimeout method. The setTimeout method allows you to set a timer and then execute a function at the end of that timer. The setTimeout timer can be canceled by calling clearTimeout and passing in the setTimeOut id(TimerId)

To help us better understand the setTimeout method we will explore the function itself and also build a sample application.

The sample application is really simple. Pressing the change color button will disable the button and start a timer.  At the end of the timer the button will be re-enabled and the box in the center of the screen will change color. The timeout will be on a 2 second delay. To cancel the timer we will have a cancel button which will invoke the clearTimeout method passing in the timerID.

{% embed https://youtu.be/xGew__dINl8 %}
What Exactly Is A Bootloader? Why Is This Important?
Tags: android, bootloader, java, opensource
Published: 2022-02-23 18:08:18

## 👉WHAT IS A BOOTLOADER?? AND WHY IT IS IMPORTANT??👈

In short, A bootloader is a software that runs every time your phone starts up. It tells the phone what programs to load in order to make your phone run
When you turn on the phone, the bootloader does the important job which is starting up the OS. And this is the reason why phone keeps their bootloaders stored in stable memory.

## 👉WHY IT IS IMPORTANT?? 👈


The bootloader has more important functions, Bootloader can start up Recovery Mode, it can execute large pieces of code that totally rewrite the Android Operating System
The bootloader is important because it loads both of these pieces of software. With a working Bootloader, your phone is nothing but just a useless brick.

## 👉WHAT IS A LOCKED BOOTLOADER??👈


A locked bootloader means you can't install your own Operating System. It means if you want to install the latest version of any custom ROM with a locked bootloader it is impossible!! Sorry but this is the TRUTH!!
Locking the bootloader is a very serious practice with some serious implications. It might be disliked by Android Developers and Enthusiasts who wish to install Custom ROMs or something to change the phone.