teleren/devto huggingface dataset:
#1 SOLID - Single Responsibility Principle | Swift | iOS Development
Tags: ios, swift
Published: 2023-07-05 14:16:04

> SRP state that a class should have only one reason to change.

Below is an implementation for a Debt calculator.

```swift
public class DebtCalculatorOld {
    
    private var totalDebt: Int = 0
    
    public init(totalCalories: Int = 0) {
        self.totalDebt = totalCalories
    }
    
    public func update(_ amount: Int) {
        self.totalDebt += amount
        
        if self.totalDebt > 500 {
            //Notify user about the change
            print("Limit Reached")
        }
    }
}
```

- Each class should focus on performing a single task.

- The below class is for managing debt of a user. If the total debt reaches a certain amount then we should notify the user about it. 

- Here we have added everything in one class which not recommended as per single responsibility principle.

- In future, if we want to change the notification type to be email. Then we will have to change the update function in the DebtCalculator.

- There should not be multiple reasons for a class to change.

```swift
public class DebtCalculator {
    
    private var totalDebt: Int = 0
    private var notificationManager: NotificationManager
    
    public init(totalCalories: Int = 0,
                notificationManager: NotificationManager = NotificationManager()) {
        self.totalDebt = totalCalories
        self.notificationManager = notificationManager
    }
    
    public func update(_ amount: Int) {
        self.totalDebt += amount
        
        if self.totalDebt > 500 {
            notificationManager.notify(totalDebt)
        }
    }
}

public class NotificationManager {
    
    public init() {}
    
    func notify(_ current: Int) {
        print("Limit Reached - \(current)")
    }
}
```
- Here we have seperate class for Adding debt releated features and Notification releated features.
- In future if we want to chagne the Notification type to email we can change it without making changes in `DebtCalculator`
Introducing VSCode News Headline
Tags: vscode, typescript
Published: 2023-07-05 14:14:46

Have you ever found yourself wanting to stay informed about the latest world events while writing code in a programming editor like Visual Studio Code? Here's a plugin that displays news headlines on the status bar of VS Code.

https://marketplace.visualstudio.com/items?itemName=TomohiroEndo.newsheadlines


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j0ciznrgzs3ta7rgnj7c.png)



Although it can only accept RSS 2.0, you have the flexibility to add any news sources in the settings.

```
"newsheadlines.newsSource": [
    "https://news.google.com/rss/search?q=inurl:www.reuters.com&hl=en-US&gl=US&ceid=US:en",
    "https://news.google.com/rss/search?q=inurl:www.cnn.com&hl=en-US&gl=US&ceid=US:en",
]
```

Here is the default setting. By adding or editing URLs, you can receive news updates on the status bar.

My colleague has used it and mentioned that this tool is great for taking a break when he becomes slightly fatigued from coding.

I hope it brings you some enjoyment.
How To Enable Cors In Node.js Express
Published: 2023-07-05 14:04:07

In this article, I will explain you about Cross-origin resource sharing. Normally we can make http request with the same origin in our application. Means in the http request the domain and port must match to load the data. The restriction is there for security reasons. Whenever we want to load data from other origin then we need to perform some task while working with express framework of node.js application.



### Implementing CORS

CORS is implimented through **Access-Control-Allow-Origin** header. In node.js express it is very easy to implement CORS. For that there is a npm package which is used to do the task with the command **npm install cors** over terminal. One cors is installed via terminal then use the cors in express app using below code:

``````app.use(require(cors)());``````

After making the above change in our express app, Once we make any request we will see a new header will return like below:

``````Access-Control-Allow-Origin: *``````
 
In the above code, The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from all origin).



### Enable CORS to specific routes

We will use cors in a specific routing

``````app.use('/user', require('cors')());``````



### Restricting specific host

Suppose we have to restrict to a single origin, Can do by below code:

``````app.use(cors({  origin: 'http://specificip.com' }));``````



### Configuring CORS w/ Dynamic Origin


``````var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}``````



## Conclusion

Adding CORS in Express is fast and easy, especially if we use the CORS library.

 

That’s all for now. Thank you for reading and I hope this article will be very helpful to understand how to  to enable cors in nodejs express.

Let me know your thoughts over the email **demo.jsonworld@gmail.com.** I would love to hear them and If you like this article, share with your friends.

This article is originally posted over [jsonworld](jsonworld.com)
How to run Emacs macro via CLI without remembering complex shell commands
Tags: go, cli, emacs
Published: 2023-07-05 13:57:35

Proof of concept

## Introduction
When I convert file or replace some text, if the repeat is necessary,

1. Use unix commands
2. Combine 1
3. Write scripts

are standard selection routine. 

Sometimes complex 2 is called as **shell art** (in Japanese).

Although we can understand the program if the number of commands are a few, the command with many combinations is dark magic.

To ease this pain, one of the approach is rb command, which is simplified Ruby. This approach make Option 3 close to 1 and 2.

https://ja.algonote.com/entry/rb

This is useful, but command is long because it is simply Ruby. Also the speed of Ruby is slow compared with native Unix commands.

When the other engineers use option 2,  in most cases, I simply use Emacs macro. If we can do this by CLI (Make Option 1 &2 rich), it's very helpful. 

## What is Emacs Macro?
In Emacs, we can record keyboard strokes and paly it (keyboard macro).  Keyboard macro can be repeat run like the other Emacs commands using `C-u`. 

1. Record start: `C-x (`
2. Do custome action.  Using `C-a`(Move to head) on head ,`C-n`(newline) on end makes action stable
3. Record end: `C-x )`
4. Run many times:`C-u <repeat number> C-x e`

This concept is also available in Excel+VBA, Windows+UWSC too. Save format is long compared with Emacs Macro anyway.

Emacs operation is basically just key input, `C-`(Ctrl)  and `M-`(Meta).

If we assume

* `^A` => `C-a`
* `^a` => `M-a` (Under struggle)

, escape word in only `^`. Very simple.

## Implementation
node.js is one option but I use golang for multiplatform support and speed. Interface is the copy of grep. 

https://github.com/hiromichinomata/emacro

```
$ cat test/sample.csv
2020-04-01 01:23,user01,male,17
2020-04-01 02:34,user02,female,27
2020-04-01 03:45,user03,male,37

$ grep female test/sample.csv
2020-04-01 02:34,user02,female,27

$ emacro '^S,user^D^D' test/sample.csv
2020-04-01 01:23,user,male,17
2020-04-01 02:34,user,female,27
2020-04-01 03:45,user,male,37

```

another example

```
$ emacro "as^Adf" test/sample.csv
dfas2020-04-01 01:23,user01,male,17
dfas2020-04-01 02:34,user02,female,27
dfas2020-04-01 03:45,user03,male,37

$ emacro "as^F^Fdf" test/sample.csv
as20df20-04-01 01:23,user01,male,17
as20df20-04-01 02:34,user02,female,27
as20df20-04-01 03:45,user03,male,37

```

## Is regex only expression for string DSL?
The most famous string DSL is probably regular expression. Regular expression is useful but main focus is pattern match. IMO, the weight is more on find than replacement.

The final purpose of text replacement is imitation of text editor. **String DSL is not only regular expression. Simple expression of text editor operation can be competitor.** That is my assumption.

Unix philosophy says do one thing well.  Alghough Regex is very complex, we recognize regex is one operation.  If we can invent simple DSL instead of shell art, that DSL will be recognized as one thing after ten years ago .

https://github.com/hiromichinomata/emacro
Ativando Reusable Component
Tags: sdelements, beginners, security, devops
Published: 2023-07-05 13:57:00

Antes que os componentes reutilizáveis do SD Elements sejam disponibilizados para uso em projetos, os administradores devem habilitar o recurso. Esta é uma operação única e é necessária apenas para a instância do SD Elements na qual você está experimentando o recurso Reusable Components.

Pré-requisitos:
O usuário tem a permissão **Organization** → **Manage features**.

Passos:
1. Navegue até a guia **System** (ícone de engrenagem).
2. Selecione **Features**.
3. Marque a caixa de seleção **Reusable Components**.
4. Clique em Salvar.

O recurso Componentes reutilizáveis agora está ativado e disponível para uso nesta instância do SD Elements. 
Acesse o recurso em **Library** → **Components**.
Criando uma pergunta personalizada
Tags: sdelements, beginners, tutorial, security
Published: 2023-07-05 13:57:00

Mesmo com a imensa biblioteca que já vem por padrão na ferramenta, e que está sendo constantemente atualizada, pode ser necessário criar uma pergunta personalizada para alguma necessidade especifica do seu projeto. 

As perguntas fazem parte da pesquisa, ou Survey, que gera os pontos de atenção do nosso projeto. Com a criação das personalizadas, consegue otimizar o poder da ferramenta da Security Compass.

Para fazer isso, na barra superior clique em **Library** e depois em **Project Survey** e clique no botão **+Add Section** no canto superior direito. Caso queria adicionar a uma seção já existente, selecione-a em vez de criar uma nova.

Depois clique em **+Add SubSection**, definindo um nome para essa sub seção e depois em **+Add Question**. 

Responda o formulário para criar sua pergunta personalizada. 
Para mais detalhes, pode saber tudo sobre as pesquisas clicando [aqui](https://docs.sdelements.com/release/2023.1/guide/docs/customization/library/project_settings.html#_question_details).
AI Alarm Bells?
Tags: ai
Published: 2023-07-05 13:18:56

As an AI layman, I am looking for an insider perspective from people who work in the field.  Working in industry, I am acutely aware that there is a massive push towards AI development.  As a sci-fi fan all my life, I am also a big Dune fan - where thousands of years before the first book takes place, mankind was almost wiped out by AI and barely escaped extinction, to evolve a series of religious and legal frameworks where "thou shalt not make a thinking machine" was meant to avoid that extinction-level event.  Also, the voice of Arnold Schwarzenegger keeps ringing in my head:  "I'll be back."  Followed by a truck smashing through the police station.

So, it seems to me that we are well on our way towards Skynet - AI development where the AI pushes a social or political agenda, and AI becomes more and more capable, more and more connected - those 2 ingredients alone are a recipe for disaster.  Imagine AI watching your social media, determining you are posting posts in violation of the leading party's political agenda, and cutting you off from your bank account, locking you out of your house, and reporting your whereabouts to the police.  Farfetched?  Absolutely not.

Background aside, my questions stem from that - what controls are being put in place to ensure those realities don't come about?  I think Elon Musk, who knows a LOT about the matter, warned they are missing.  And, if controls are being put in place - what controls?  It isn't enough just to look at one aspect, say the chance for AI to start running away with generating code updates for itself.  We need to look at *every* aspect - from sociopolitical, to psychological, to governmental and so on.

What preventions are there from a rogue nation-state (think DPRK) from using a cadre of programmers to generate code for the AI that subverts the "free" world?  And, if you say "oh, it's Open Source, that makes it impossible" then I say, "Why?  You are saying that there are enough knowledgeable people who have the time and expertise to review all that code prior to submission, and that we know there are no sleeper routines?"  If so, I don't believe it.  For example, a group proved that Apple's App Store review process was prone to a flaw where malicious code could be broken apart and hidden by the app, and then reassembled at runtime by the app under certain conditions not met during App Store review.  (Kind of like the VolksWagon emissions scandal.)
Criando uma contramedida
Tags: sdelements, beginners, devops, security
Published: 2023-07-05 13:56:00

Mesmo com a imensa biblioteca que já vem por padrão na ferramenta, e que está sendo constantemente atualizada, pode ser necessário criar uma contramedida (ou Countermeasure no original) personalizada para alguma necessidade especifica do seu projeto. 

Para fazer isso, na barra superior clique em **Library** e depois em **Countermeasure**. Clique no botão **+Add Countermeasure** no canto superior direito.
No formulário, defina:
- Titulo
- Prioridade
- Fase onde ela se localiza
- Fraqueza relacionada
- Solução
- Requisitos adicionais
- Como resolver

No canto direito, pode definir quando ela vai ser aplicada(exemplo: Em uma Web Aplication)
What is a package manager and what is the difference between YARN, NPM, PNPM?
Tags: beginners, development, webdev, discuss
Published: 2023-07-05 13:55:14


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ne54gv79po2xplh47n63.png)


I really want to joke about a package with packages. But no, this article is about something else. First, let’s figure out why I wrote it and who it might be useful for:

Front-end developers like me, who always used the standard manager and were not interested in others, can relate. And then suddenly, they wanted something new, and had to read more than one article to gather information and choose the appropriate option.

Back-end developers who are transitioning to Node.js.
Juniors who only joke about packages and have only heard of them.

## Why did I even start messing with packages?

I believe that if a developer is completely unconnected to business goals, he will be of little use. He should understand how to choose technologies, to build the architecture so that the product would work best in the end. For example, if you use native JS instead of a reactive framework, it is logical to assume that the development speed will be slower, and therefore the final product will be much more expensive.

How else can the business benefit from such a small change? Let’s say you are from a large outsourcing company, let’s call it Malabar. At Malabar, everything is great: a lot of clients, a lot of developers, a big stack. But all the employees are used to using different technologies. Some like npm syntax, some like yarn, and some like pnpm.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iuztxhmu045unphqf2g7.png)

So this third person from Malabar is sent on vacation. He’s flying to see Dubai. But the project can’t wait for him, someone has to replace the lucky guy. Another developer, who has always used NPM, is transferred to the project. He stumbles upon a new technology he has never worked with before. And then the fun part starts.

Problems may pop up at the moment of dependencies installation:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygnnm4yz8hb7pgtii9wy.png)


What to do? Replace the existing technology with another? Well, that’s one way out — it’s someone else’s project. What is the result? The developer has to spend extra time to study the new technology in order to start the tasks.

And it’s not just about package managers, it’s about the unification of different technologies within a company. If all projects use identical core technologies, onboarding will be reduced to a minimum. And that, by the way, is also a plus for business.

If you're interested same as me, you can [continue reading](https://medium.com/@dev.family/what-is-a-package-manager-and-what-is-the-difference-between-yarn-npm-pnpm-622df5b6b38c) on Medium.
Be the Next XRPL Campus Ambassador
Tags: xrp, xrpl, blockchain
Published: 2023-07-05 13:52:35

Calling all blockchain enthusiasts! The application window for the Fall 2023 XRP Ledger Campus Ambassador program is now officially open! This program runs from September to December and offers an exciting opportunity for students to engage in blockchain technology and contribute to the growing Web3 ecosystem. This is your chance to empower a new generation of developers.

- **Applications due: July 30, 2023**
- Apply today: [http://xrpl.org/ambassadors.html](http://xrpl.org/ambassadors.html)

**Why become an XRPL Campus Ambassador?**
The XRP Ledger Campus Ambassador program—founded between the XRP Ledger Foundation and Ripple, is designed to empower, educate, and engage students across campuses worldwide. As Campus Ambassadors, participants will help to further establish the XRPL community within their respective universities through workshops, hackathons, and other related events.

Selected Ambassadors will also earn various privileges, including:

- Access to Ambassador-only events and conferences
- Hands-on experience in building their professional network.
- Tutorials and workshops from industry-leading XRPL and blockchain developers
- Mentorship from notable members of the XRPL and blockchain community
- Funding to back their XRPL growth-fueling ideas and initiatives on campus
- Swag for your work and represent XRPL in style

Reflecting on the Spring 2023 cohort, Derrick N., a Lead Ambassador from Toronto Metropolitan University, shared, "This program provided me with a unique opportunity to learn about blockchain technology, form valuable connections, and introduce other students on campus to the intriguing world of the XRP Ledger. It broadened my horizons and allowed me to witness the potential of blockchain technology and its real-world applications. It's been an enriching journey for which I am grateful."

All students are welcome to [apply to be a part of the Fall 2023 Ambassador Program cohort](https://xrpl.org/ambassadors.html). Applications are open now until July 30th, 2023!
Style your mark and leave a mark
Tags: webdev, html, css, beginners
Published: 2023-07-05 13:29:19

Recently I browsed the web and ran into an article on Medium from 2017. It talked about [multi colored backgrounds](https://blog.prototypr.io/css-only-multi-color-backgrounds-4d96a5569a20). 

It said that linear gradients are cool for styling backgrounds. 
No doubt. No doubt. 

So of course, I used one of them... ON MARK ELEMENT!
Another on span... 

And voila. They look great! 
Today in a world where you have web color generators that basically mix those colors for you, into nice ones, it would be a shame not to utilize it on a web page. 

So code and enjoy in making web prettier.

```css
mark
  {background: linear-gradient(110deg, #fdcd3b 60%, #ffed4b 60%);}
```


[Example on jsFiddle](https://jsfiddle.net/xbhaL0fd/)
How to set active class on NavLink for multiple react routes
Tags: react
Published: 2023-07-05 13:27:25

I recently got into one use case of highlighting the navlink for multiple routes. 

Lets say we have two routes 
1. customer listing (/customers). 
2. customer details (/customer-details/:customerId). 

The entry point in ui is customer listing and when you click on any record, we will be navigated to customer details page. 

Now i have a navlink like this

```typescript
<NavLink to={PATHS.CUSTOMERS}>Customers</Navlink>
```

The use case is for both the routes, the navlink should be in active state. And this is the logic i implemented:

```typescript
import { NavLink, matchPath, useLocation } from "react-router-dom";

export function NavigationBar() {
  const { pathname } = useLocation();
  const setNavlinkClasses = (paths: string[]) =>
    paths.some((path) => matchPath(path, pathname))
    ? "navlink active"
    : "navlink";

  return (
    <nav>
      <NavLink
        to={PATHS.CUSTOMERS}
        className={setNavlinkClasses([PATHS.CUSTOMERS, PATHS.CUSTOMER_DETAILS])}
      >Customers</NavLink>
    </nav>
  );
}

```

And that's it.

Hope it helps :smile:
Kiran :wave: :wave:
What framework should I use to create an accessible component library?
Tags: webdev, javascript, discuss, programming
Published: 2023-07-05 13:16:26

So I need to create a component library, and the requirements are:

1. Components must be accessible. Be careful with this. More info [here](https://alice.pages.igalia.com/blog/how-shadow-dom-and-accessibility-are-in-conflict/), [here](https://coryrylan.com/blog/accessibility-with-id-referencing-and-shadow-dom), and [here](https://nolanlawson.com/2022/11/28/shadow-dom-and-accessibility-the-trouble-with-aria/).

1. Components must work with different technologies, like, SSR and SPAs like Angular.

1. The library has to be lightweight.

Candidates: Stencil, Lit, FAST, Solid, anything else?

I think Lit does not allow removing shadow dom (because of accessibility) and use slots. Does Stencil?

I need opinions!!
Types Aliases and Interface are tricky..
Tags: typescript, cheatsheet
Published: 2023-07-05 13:16:21

```
type BirdType = {
  wings: 2;
};

interface BirdInterface {
  wings: 2;
}
```

- Both declare the shape of an object
- Both support extending other interfaces and types
- It's possible to intermix their use
- Interfaces are open whereas type aliases are closed
- Typescript gives better error messages for interfaces
- Prefer interfaces for publicly exposed types

Sources:

- [TS Playground](https://typescriptlang.org/play#example/types-vs-interfaces)

- [Interfaces vs Types](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/52682220#52682220)

- [Interfaces vs Type Aliases: what's the difference?](https://youtu.be/QYO-sieqLD4)

- [TypeScript: Should you use Types or Interfaces? ](https://youtu.be/zM9UPcIyyhQ)