teleren/devto huggingface dataset:
How to reduce memory usage for your Rails app - R14 - Memory Quota Exceeded in Ruby (MRI)
Tags: ruby, rails, memory, heroku
Published: 2023-06-30 16:56:07

If you have just started building your Rails app and discovered that your memory quota is reaching nearly 1 GB - that's not normal. Fortunately, I have the exact solution for you. I've successfully brought my Rails app -https://receipt-AI.com 's memory usage from 1 GB to 268 MB.

&nbsp;
###**1. Lower your worker count**
The default Puma worker pool size is 4, but you can reduce it if you are not using a lot of concurrent connections.
```
heroku config:set WEB_CONCURRENCY=1
```

&nbsp;
###**2. Remove unused gems and set some to require: false**
It could be that the gems you used are not required for boot time. To determine how much memory your gems consume during boot time:

```
group :development do
    gem 'derailed'
end
```
and then run bundle install and
```
bundle exec derailed bundle:mem
```
Bear in mind that if any gems is set to `require: false`, make sure to add require to the file where it is used.

&nbsp;
###**3. Use rack-mini-profiler to monitor your database queries.**
Uncomment this gem in your Gemfile and run bundle install. This tool allows you to measure the speed of your HTML page. It's super straightforward.
```
  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"
```

&nbsp;
###**4. Caching**
Rails has a built-in way to cache your view, as simple as:
```
<%= render partial: 'hero', cached: true %>
```
You should only use caching on partials that are used frequently and whose output does not change frequently, such as your home page, which is also the most visited.

&nbsp;
###**5. Garbage collector turning**
I have read multiple sources that state the default value of RUBY_GC_HEAP_GROWTH_FACTOR in Ruby is 1.8. Some sources mention that it may vary depending on the Ruby version. Nevertheless, you can configure the value by running:
```
heroku config:set RUBY_GC_HEAP_GROWTH_FACTOR=1.03
```

With this approach, your Rails app will be running super crisp and smooth without the need to upgrade the dyno.


&nbsp;

---------------------------------------------------------------------------------------------------------

&nbsp;
###**Ruby memory use**
https://devcenter.heroku.com/articles/ruby-memory-use

&nbsp;
###**Garbage collection tuning**
https://blog.appsignal.com/2021/11/17/practical-garbage-collection-tuning-in-ruby.html
Webhooks
Tags: webhooks, beginners
Published: 2023-06-30 16:51:37

**WEBHOOKS**

**Webhooks** are ways for a web application and external service to send real-time notification to one or more applications. They are automated [HTTP](https://www.freecodecamp.org/news/what-is-http/) requests, triggered when specific events such as comments being posted to a blog, occurs in a source system and sent to a destination system, sometimes with a payload of data.

![Cartoon Webhooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvuqz9uzkj4ej8o4idpf.png)



The concept of webhooks consists of two parties:

- 
**The sender**:- The application that is notifying another system about an event. It gathers important data about the event and packages it in a payload, then initiates an [HTTP POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request containing the payload data to the webhook URL or endpoint already provided by the receiver.

- 
**The receiver**:- The application that receives and processes the webhook data. It receives the HTTP request and extracts and processes the payload data.


![Sender and Reciever](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1qtzr6o17wo7x0xx2c7.png)




**THINGS TO NOTE ABOUT WEBHOOKS**

- 
Webhooks payloads are usually in serialized form-encoded [JSON](https://www.json.org/json-en.html) or [XML](https://aws.amazon.com/what-is/xml/#:~:text=Extensible%20Markup%20Language%20(XML)%20is,implemented%20for%20structured%20data%20management.) [](url)formats.

- 
Both the sender and receiver applications must have the necessary functionalities to send and receive HTTP requests.

- 
A secure HTTPS  URL endpoint should be provided as the webhook receiver.

- 
It is best to respond with a 200 or 302 [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) when a notification is sent.

- 
A single webhook request can be distributed to multiple destinations that need the information. 

**USES OF WEBHOOKS**

Webhooks are used in web development to enable communication between different services, some other uses are;

- 
Data Synchronization

- 
Integration with Third-Party Services

- 
Real-time Updates

- 
Web Analytics and Tracking


**CONCLUSION**

Webhooks have become a popular method  to improve efficiency among online platforms by enabling real-time communication between applications.
How to write PostgreSQL extensions in C++
Tags: postgres, apacheag
Published: 2023-06-30 16:41:14

Creating a completely new extension for PostgreSQL involves several steps.
Here we will create a basic extension with that adds SQL function to calculate factorial of a given integer. We will write the extension code in c++.
## Create the Factorial Extension
**Setp 1:**
Create factorial_extension folder in `share` directory in the postgres installation folder.
**Set up the folder structure.** This folder contains file `factorial_extension.control`, `factorial_extension--1.0.sql`, `factorial_extension.cpp` and `MakeFile`.
```
factorial_extension/
    |
    +-- factorial_extension.control
    |
    +-- factorial_extension.cpp
    |
    +-- factorial_extension--1.0.sql
    |
    +-- Makefile
```

**Setp 2:**
Write code for factorial in C++

```
#include <postgres.h>
#include <fmgr.h>
#include <utils/numeric.h>

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

extern "C" {
    PG_FUNCTION_INFO_V1(factorial);

    Datum factorial(PG_FUNCTION_ARGS) {
        int32 arg = PG_GETARG_INT32(0);

        if (arg < 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("Factorial input must be a non-negative integer")));

        int64 result = 1;
        for (int i = 2; i <= arg; ++i)
            result *= i;

        PG_RETURN_INT64(result);
    }
}

```

**Setp 3:**
Write the control file. The control file for an extension, also known as the .control file, is a metadata file that provides information about the extension. It contains details such as the name, version, author, module path, dependencies, and other important attributes of the extension.

```
# factorial_extension.control
comment = 'Extension to calculate factorial'
default_version = '1.0'
module_pathname = '$libdir/factorial_extension'
relocatable = false
```

**Step 4:**
Write the SQL script (factorial_extension--1.0.sql):

```
-- factorial_extension--1.0.sql

-- Create the extension schema
CREATE SCHEMA factorial_extension;

-- Create the SQL function
CREATE OR REPLACE FUNCTION factorial_extension.factorial(integer)
RETURNS bigint AS 'factorial_extension', 'factorial'
LANGUAGE C STRICT;

-- Grant execute permission to public (change to appropriate roles if needed)
GRANT EXECUTE ON FUNCTION factorial_extension.factorial(integer) TO PUBLIC;

```
**Step 4:**
Write the MakeFile:
```
MODULES = factorial_extension
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
```

## Run the Extension
**Step 1:** Start or restart the PostgreSQL server
**Step 2:** Connect to the database where you want to install the extension
**Step 3:** To install the extension run the following command.
```
CREATE EXTENSION factorial_extension;
```

## Use the Extension

```
SELECT factorial_extension.factorial(5);
```
How to create extensions in PostgreSQL?
Published: 2023-06-30 16:28:11

Creating a completely new extension for PostgreSQL involves several steps.
Here we will create a basic extension with that adds SQL function to calculate factorial of a given integer. This example is written using the PL/pgSQL procedural language.

## Create the Factorial Extension
**Setp 1:**
Create factorial_extension folder in `share` directory in the postgres installation folder.
Set up the folder structure. This folder contains file `factorial_extension.control` and `factorial_extension--1.0.sql`

```
factorial_extension/
    |
    +-- factorial_extension.control
    |
    +-- factorial_extension--1.0.sql
```
**Setp 2:**
Write the control file. The control file for an extension, also known as the .control file, is a metadata file that provides information about the extension. It contains details such as the name, version, author, module path, dependencies, and other important attributes of the extension.

```
# factorial_extension.control
comment = 'Extension to calculate factorial'
default_version = '1.0'
module_pathname = '$libdir/factorial_extension'
relocatable = false
```
**Step 3:**
Write the SQL script (factorial_extension--1.0.sql):

```
-- factorial_extension--1.0.sql

-- Create a new schema for the extension
CREATE SCHEMA factorial_extension;

-- Create the factorial function
CREATE OR REPLACE FUNCTION factorial_extension.factorial(n INTEGER)
RETURNS BIGINT AS $$
DECLARE
    result BIGINT := 1;
BEGIN
    IF n < 0 THEN
        RAISE EXCEPTION 'Factorial is not defined for negative numbers';
    ELSIF n > 1 THEN
        FOR i IN 2..n LOOP
            result := result * i;
        END LOOP;
    END IF;
    RETURN result;
END;
$$ LANGUAGE plpgsql;

-- Grant execute permission to public (change to appropriate roles if needed)
GRANT EXECUTE ON FUNCTION factorial_extension.factorial(INTEGER) TO PUBLIC;

```


## Run the Extension
**Step 1:** Start or restart the PostgreSQL server
**Step 2:** Connect to the database where you want to install the extension
**Step 3:** TO install the extension run the following command.
```
CREATE EXTENSION factorial_extension;
```

## Use the Extension

```
SELECT factorial_extension.factorial(5);

```
Memgraph Community Call: Querying Memgraph through an LLM
Published: 2023-06-30 16:27:53

Memgraph has organized its fair share of community calls to bring its community closer together and spread knowledge about important topics related to the graph database world. Attendees had the opportunity to meet the Memgraph team and talk with them about new features or their day-to-day responsibilities. They also had the chance to take over the stage and talk about the projects they worked on.

We are looking forward to many calls like this, and it proved to be great to have an open channel of communication directly with the Memgraph community to hear the most honest feedback about the product and experiences with building their products using graph databases. 

In case you missed our community calls and want to catch up before the next one, head over to <a href="https://www.youtube.com/watch?v=QYFU5d_xLIs&list=PL7Eotag2rRhZssS4f11PKAHuCykMCljg3" target="_blank">Memgraph’s YouTube channel</a>.

## Memgraph entering the world of LLMs

**On July 7th, at 6 PM CEST**, Memgraph is organizing the next community call on **Querying Memgraph through an <a href="https://en.wikipedia.org/wiki/Large_language_model" target="_blank">LLM</a>**. Our guest speaker is <a href="https://www.linkedin.com/in/brett-brewer-967182/" target="_blank">Brett Brewer</a>, who has broad experience as a chemical engineer in industrial process automation and who has been a VP at Microsoft throughout his 25-year long career there. Now retired, he found a new way to have fun - he jumped into the AI rabbit hole to expand his knowledge and contribute where he can. That’s how he connected with Memgraph and gave us an idea to integrate with <a href="https://langchain.com/" target="_blank">LangChain</a>. That was not an easy task, but not to spoil too much, <a href="https://us02web.zoom.us/j/84734174129?pwd=aGtkc0UwVm10L3Qva2VveU01U1ozdz09" target="_blank">join our community call</a> to hear and talk all about that journey!

## Hang out with the community

To wrap it up, if you want to stay in touch with the Memgraph community, set up a reminder for this and similar events – <a href="https://www.discord.gg/memgraph" target="_blank">join our Discord server</a>! We try our best to keep the community engaged, questions answered, and every community member listened to. 

Once again, here are the community call event details:

Topic: Querying Memgraph through an LLM <br>
Speaker: Brett Brewer <br>
Date and time: Friday, July 7th, 6 PM CEST <br>
Zoom link: https://us02web.zoom.us/j/84734174129?pwd=aGtkc0UwVm10L3Qva2VveU01U1ozdz09 <br>
Hope to see you there 👋😀
Nepal U-16 secure 84 runs victory over Malaysia U-16 in 2023 Match
Tags: nepalu16, malaysiau16, accmatchnepalvsmalesiya, acc
Published: 2023-06-30 16:20:32

**

### Nepal U-16 secure 84 runs victory over Malaysia U-16 in 2023 Match: acc match nepal vs malesiya

**
Tailender Ashok Dhami came up with an all-round performance for Nepal as they Thumped hosts Malaysia by 84 Runs to seacure Toop finish in Group ‘A’ of the ACC Men’s Under-16 East Zone Cup at the Bayuemas Oval, Bangi, on Friday.
{% embed https://onlinelatestarticles.com/nepal-u-16-secures-an-84-run-victory-over-malaysia-u-16/ %}
SECURE VPN MOD APK 4.1.8 (VIP UNLOCKED) FOR ANDROID
Published: 2023-06-30 16:15:24

**

## [Secure VPN MOD APK](https://securevpnmodapk.co/) 4.1.8 (VIP Unlocked APK) for Android

**
{% embed https://securevpnmodapk.co/ %}
Hide the 1password button on a form field
Tags: webdev
Published: 2023-06-30 16:09:48


![1Password icon, uninvited](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ojm5jc9486kny35ifhy.png)

As a web developer, I sometimes have a field in a form (e.g. inside a CMS) where it makes no sense for 1Password to pop up.

So, to prevent 1password browser extension from showing the 1Password icon on a form field, simply add this attribute:

```
data-1p-ignore
``` 

Example:

```html
<input type="email" id="email" name="email" autocapitalize="none" autocorrect="off" spellcheck="false" required  placeholder="Enter your email address..." >
```

source: [1password's (angry) forum](https://1password.community/discussion/117501/as-a-web-developer-how-can-i-disable-1password-filling-for-a-specific-field).
Debugger vs console.log
Tags: javascript, beginners, spanish
Published: 2023-06-30 15:54:17

Cuando estas programando en #JavaScript ¿para todo ocupas un console.log()?, bueno pues a pesar de que te fue útil y lo mas seguro es que hayas resuelto esos problemas que te aquejaban en su momento pues no es la mejor forma de ir revisando el comportamiento de tu código fuente y también su ejecución a través del tiempo.

Lo ideal es el uso de la palabra reservada debugger ya que esto el navegador lo va a interpretar y va a detener la ejecución en ese punto para mostrarte que es lo que se esta pasando ese momento.


![Ejemplo de debugger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oo8pdvye1wsjntw1c4vv.png)

Se abrirá una consola y te mostrará el contenido de las variables que en ese punto de tu programa existen y su contenido. Así que a partir de ahora ocúpalo y happy coding.


![Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/go8xkrqd20k0kn321vtp.png)
The other side of using requestAnimationFrame
Tags: javascript, webdev, animation, vue
Published: 2023-06-30 15:36:29

## Backstory
I was looking through the Vue source code and came across this:
**vue.js**
```javascript
function nextFrame(cb) {
      requestAnimationFrame(() => {
          requestAnimationFrame(cb);
      });
  }
```

It turns out that Vue uses the requestAnimationFrame function twice when adding and removing classes during transitions.

## What's the purpose of double requestAnimationFrame?
I spent a considerable amount of time trying to understand the reason behind this approach. While I may not have fully grasped its intricacies, here's what I discovered.

Consider this example:

**index.html**
```html
<button class="btn btn-primary" id="btnStart">Start</button>
<div class="alert alert-success move-animation" id="target">Hello world</div>
```
**style.css**
```css
.move-animation {
    animation: move 2s linear;
}

@keyframes move {
    0% {
        transform: translateX(0);
    }

    50% {
        transform: translateX(100px);
    }

    100% {
        transform: translateX(0);
    }
}

.testClass {
    color: red;
}
```
**script.js**
```javascript
var element = document.getElementById('target');
var btnStart = document.getElementById('btnStart');

function raf(fn) {
    window.requestAnimationFrame(function () {
        window.requestAnimationFrame(function () {
            fn();
        });
    });
}

function addClass() {
    element.classList.add('testClass');
}

btnStart.addEventListener('click', () => {
    element.classList.remove('testClass');
    raf(addClass);
});
```


If you decide to test this code, you may not notice a significant difference between `raf(addClass);` and simply `window.requestAnimationFrame(addClass);`. However, in more complex projects, when a user on a Macintosh device visits your site, they may experience flickering and potentially incorrect rendering of elements during animations. While I cannot provide concrete evidence, rest assured that using the double `requestAnimationFrame` method does not introduce more performance overhead than `window.requestAnimationFrame(addClass);`. There may be a slight difference, but after extensive browser testing, I did not observe any additional burden.

## Summary
Employing double `requestAnimationFrame` ensures that the `addClass` function executes successfully during the next two consecutive animation steps, resulting in smoother and synchronized animations without undesirable effects.

P.S. Whether or not to utilize this approach is a personal choice. I encourage you to share your thoughts in the comments and engage in discussions regarding this matter. Personally, I find value in using this method, particularly when working with the DOM through JavaScript and dealing with elements that have CSS-defined animations.
Validators in Flask
Tags: flask, backend, beginners
Published: 2023-06-30 15:31:23

As you begin to create and manage databases it's important to keep in mind that the type of data you are allowing users to input can have large effects on your databases. Validators are used to do just that; maintain the integrity of the data flowing into your databases.

You must imagine every possible edge case for how a user will interact with your webpage and then utilize validators to protect against those cases.

Using validators is generally very intuitive and basic. 

Within your models and class definitions on the back-end you can define validators as so:

```
class User(db.Model, SerializerMixin):
   __tablename__ = 'users'

   ##here all your relationships will lie##


   ###below you are defining what variable you will be validating.##
   @validates('username'):
   ##creating a validation##
   def validate_username(self, key, value):
      if not value:
           raise ValueError('Please enter a username')
   ##forcing a user to enter a value for their username to proceed, otherwise they will see a value error##
      return value
   ##returning the value if a username is provided by the user##
```
Above is an example of how you would do a simple validation for one variable. You'll notice I passed through 'value' rather than 'username' and checked against value. The reason for that is so you can check multiple variables if they require the same validation. The example below is how you would force a user to input a value for both username and email.

```
class User(db.Model, SerializerMixin):
   __tablename__ = 'users'

   ##here all your relationships will lie##

   @validates('username', 'email'):
   def validate_username(self, key, value):
      if not value:
           raise ValueError('Please enter a username')
      return value
```

At the end of the day validating isn't too daunting and it's something that is important to implement upfront to save you time on the _back-end_ haha ;).
What's the best approach?
Published: 2023-06-30 14:19:02

Hi,

For a personal project that I hope could turn into a service I'll sell subscriptions for, I want to make sure what the best design should be.

In my previous jobs, I've only built monolith applications but now, I'm wondering if a modular approach would be better, especially thinking of maintainability, scalability, and security.

My question is general and so the service I want to build is irrelevant, I want to understand what the best approach is.

I thought if I went with a modular approach, it may be easier to update without too much impact on usability (updating the admin features, for example, would not impact the users' front end, etc).
Additionally, I thought it might be better to separate admin and user endpoints, as well as separate user data from everything else, especially from where users have access.

The idea was that if a user manages to hack into the system via the user endpoint and access the DB, it would not have access to users' private data.

But now, I'm wondering if I'm making it too complex for too little benefit.

Here is a graph to illustrate my idea:
![A graph of the solution I have described](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxgx7siblo9nonheso60.jpg)

Do you think I would be better off with a simple solution like below?

![A graph of a monolith implementation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lffxd2wl5pgys6dl98w3.jpg)

Or do you think something entirely different may be warranted?

Since the question is general, I don't think the tech I want to use is really relevant but I'll mention it, just in case.
I'm planning on using .Net Core (maybe .net MAUI later, for mobile apps). 

Thank you in advance!