teleren/devto huggingface dataset:
How file descriptors can bring your service down. 
Tags: java, linux, devops, showdev
Published: 2018-10-25 20:12:45

---
title: How file descriptors can bring your service down. 
published: true
description: a journey from the linux OS to your app and keeping your app up in the long run. 
tags: java, linux, devops, showdev
---

Over the past year I've completed the Linux Foundation's Essentials of Linux Administration course. Today I'm going to focus on file descriptors and how your app creates them, and **should** close them.

Let's start with a very high level definition of how a linux OS sees its world. 

> Everything in a running linux system is a file. 

A file descriptor is a file which the linux kernel creates and deletes for every file opened and closed by a process. 

> The linux kernel allows for a finite number of file descriptors!

Let's see this in action. Start your app and get the PID.

```bash
java -jar app.jar
ps -ef | grep app.jar
```

Now cd into processes directory and do an ls. 

```bash
cd /proc/3535
ls -al
```

This is all the information about your running app that the kernel needs. 

Let's focus on the file descriptors directory

```bash
ls -al /proc/3535/fd
ls -al /proc/3535/fd | wc -l
```

You'll see there are number of open file descriptors.

Use your app for a bit and come back to this directory and execute the above command again. 

How many descriptors are there now?

Go back to your app again and use it some more. 

How many are there now?

**If this number keeps going up you're heading for trouble!**

Eventually you're app won't be able to do anything as it can't open anymore file descriptors. 

From my experience the main culprits are **i/o streams**. 

So, how do we solve this?

Easy!

Close your streams. 

# Java

[Try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) to the rescue. Open all you're streams in a try-with-resources block and the jvm will handle closing the steam for you

```java 
//...

    try (InputStream data = new InputStream()){
        // ...
    }
```

# Python

Python has a similar concept

```python
# ...

    with open('mine.txt', r) as f:
        # ...
```

I'm sure other languages have the same concept so feel free to comment with it and I'll update the post. 

So, **always close your streams so that your app doesn't eventually fall over.**
Why Does The C Programming Language Refuse to Die (link) 
Tags: c
Published: 2018-10-25 20:12:32

---
title: Why Does The C Programming Language Refuse to Die (link) 
published: true
description: 
tags: C, 
---

Cool article I came across. 

https://hub.packtpub.com/why-does-the-c-programming-language-refuse-to-die/
TIL: Query Dash.app from the CLI
Tags: dash, todayilearned, macos
Published: 2018-10-25 18:47:23

---
title: TIL: Query Dash.app from the CLI
published: true
description: Integrate with the Dash.app from the command line
tags: dash, todayilearned, macos
---

**[Dash](https://kapeli.com/dash)** the documentation browser for MacOS and iOS is a nifty tool.

It can integrate with a lot of tools like editors etc. but you can also integrate with the CLI.

This example is for **Bash**, where I have added the following function to my `.bash_profile`

```bash
function dash {
    open "dash://$1"
}
```

This lets me do:

```bash
$ dash «query»
```

Which open the **Dash** application and lists the results.

```bash
$ dash chmod
```

Lists all pages mentioning `chmod`

![Ruby result for chmod](https://jonasbn.github.io/til/dashapp/dash-chmod.png)

You can even use the configurable search profiles to limit your results set, like so:

```bash
$ dash ruby:chmod
```

Lists all the **Ruby** pages mentioning `chmod`, well pages a part of the **Ruby** search profile, but you get the picture.

![Ruby result for chmod](https://jonasbn.github.io/til/dashapp/dash-ruby-chmod.png)

## References

- [Dash Website](https://kapeli.com/dash)

[This TIL](http://jonasbn.github.io/til/dashapp/query_dash_from_the_cli.html) was curated, seasoned and hand-picked tonight from [my TIL collection](http://jonasbn.github.io/til/).

Let me know if you have problems or improvements
A dummy blockchain implementation in C (II)
Tags: blockchain, c
Published: 2018-10-25 18:22:07

---
title: A dummy blockchain implementation in C (II)
published: true
description: A dummy blockchain implementation in C
tags: blockchain, c
---
*[A dummy blockchain implementation in C (I)](https://dev.to/devmarchan/a-dummy-blockchain-implementation-in-c-i-3m97)*

##1. Parties

All the ingredients are ready, so now it is time to code the main function. As I already said, it is going to be a voting system. For that, I have created the next enum with all the parties available in the electoral system:

```c
typedef enum party_code_t {
GOOD_PARTY, MEDIOCRE_PARTY, EVIL_PARTY, MAX_PARTIES
} party_code;
```
And a function which randomly gets a vote:

```c
static party_code get_vote()
{
    int r = rand();
    return r%MAX_PARTIES;
}
```

##2. First block: genesis

```c
NODE *head;
    DATA genesis_element;
    init(&head);

    transaction genesis_transactions = get_vote()};
    block_t genesis_block = {0, string_hash(genesis_transactions), genesis_transactions};
    genesis_element.info = genesis_block;
    head = add(head, genesis_element);
```
In order to create a new element are necessary three steps:

    1. To create the transaction. We create a transaction getting the name of the party.
    2. To create the block with its three fields: previous hash, current hash and a transaction.
    3. To create the node element of the list (the block) and to insert it to the list.

It is common to call the first block in a blockchain as genesis. As there is no previous block, we set the previous block hash to zero.

##3. Adding votes

```c
  int previous_hash = genesis_element.info.previous_block_hash;
    for(i=0;i<nvotes;i++) {
 
        DATA *el
        block_t *b;
        transaction t = {get_vote()};
 
        b->block_hash = string_hash(t);
        b->transactions = t;
        el->info = *b;
        previous_hash = b->block_hash;
        head = add(head, *el);
    }
```
Once the first element has been inserted, it is possible to create a loop to create as many blocks as wanted. It follows the three steps from above.

That is all. After compiling and executing we can read the output in the terminal. Each vote (or block) is displayed below the previous one, and it is formed by the hash of the previous vote, the current hash and the name of the voted party. Its current hash it is formed by all the votes previously submitted.

You can see the final [code here](https://github.com/jmarchanloro/1-blockchain). The core is the snippets showed in the post, but more auxiliary code has been added, mainly to print the linked list.


![Ten votes stored in a blockchain](https://i2.wp.com/myram.xyz/wp-content/uploads/2018/09/output.jpg?w=454&ssl=1)


[Original post in myram](https://myram.xyz/c-blockchain-implementation-2/)

_*Disclaimer*: This article is full of simplifications and abstractions in order to get the fundamental. Although one of the key points of blockchain is that database isn’t stored in any single location but it is shared and transactions are spreading to a P2P network of nodes, here is obviated all the network part._
Building Ambitious Apps with MDX
Tags: mdx, react, javascript, markdown
Published: 2018-10-25 17:35:26

---
title: Building Ambitious Apps with MDX
published: true
description: Learn how MDX works and create a blazing fast app in no time.
tags: #mdx #react #javascript #markdown
canonical_url: https://auth0.com/blog/how-to-build-an-app-with-react-and-mdx/
---

MDX is used to load, parse and render JSX in Markdown documents. In this tutorial, you'll learn how to use MDX with React to build a project documentation app.

[Read on 🤸🏿‍♂️](https://auth0.com/blog/how-to-build-an-app-with-react-and-mdx/?utm_source=dev&utm_medium=sc&utm_campaign=mdx_react)

![Building Ambitious Apps with MDX](https://thepracticaldev.s3.amazonaws.com/i/x8qepjaijw2ftxys3x0l.png)
The React Hook Proposal
Tags: react, discuss
Published: 2018-10-25 17:10:49

---
title: The React Hook Proposal
published: true
description: 
tags: react, discuss
---

What do you think about React's new hook proposal?

You can read about it [here](https://reactjs.org/docs/hooks-intro.html)

The [RFC](https://github.com/reactjs/rfcs/pull/68) is also online.

I like how it composes much nicer than classes and seems like a clean solution to the main problems React faces.

But does it replace the current API with something more complicated?
Trucos con AWS Lambda. (Parte 1)
Tags: aws, awslambda
Published: 2018-10-25 18:57:09

---
title: Trucos con AWS Lambda. (Parte 1)
published: true
tags: aws, aws lambda
canonical_url: https://yorodm.github.io/blog/aws-lambda-tricks/
series: lambda tricks
---

## Truco 1: Recursividad asíncrona.

A veces queremos garantizar que una lambda se ejecute siempre de formaasíncrona.

```
def lambda_handler(event, context):
    if not event.get('async'):
        invoke_self_async(event, context)
        return

def invoke_self_async(event, context):
    new_event = {
        'async': True,
        'data': event
    }
    boto3.client('lambda').invoke_async(
        FunctionName=context.invoked_function_arn,
        InvokeArgs=json.dumps(new_event)
    )
```

Este truco es muy útil cuando no nos interesa el resultado de la ejecución o elmismo es enviado por vías alternativas (ej. usando **SNS** )

## Truco 2: Planificación dinámica.

A veces la planificación de un servicio debe ser alterada en dependencia de ciertas condiciones.

```
def lambda_handler(event, context):
    reschedule_event()
    keep_working()

REGULAR_SCHEDULE = 'rate(20 minutes)'
WEEKEND_SHEDULE = 'rate(1 hour)'
RULE_NAME = 'My Rule'

def reschedule_event():
    """
    Cambia la planificación de la lambda, para que descanse los findes :D
    """
    sched = boto3.client('events')
    current = sched.describe_rule(Name=RULE_NAME)
    if is_weekend() and 'minutes' in current['ScheduleExpression']:
        sched.put_rule(
            Name=RULE_NAME,
            ScheduleExpression=WEEKEND_SCHEDULE,
        )
    if not is_weekend and 'hour' in current['ScheduleExpression']:
        sched.put_rule(
            Name=RULE_NAME,
            ScheduleExpression=REGULAR_SCHEDULE,
        )
```

## Truco 3: Flujos de negocio

Cuando vayas a usar **StepFunctions** recuerda:

> Nunca uses un cañón para matar un mosquito

```
def lambda_handler(event, context):
    return dispatch_workflow(event)

def dispatch_workflow(activity):
    workflow_id = event.get('workflow_id'):
    if workflow_id:
        # Retrieve the state from Dynamo
        state = get_saved_state(event['workflow_id'])
    else:
        workflow_id = create_workflow_id() # uuid maybe
        state = None
    workflow = Workflow(workflow_id)
    return workflow(state,events) # Workflow is a callable
```
React Conf Live Stream is on
Tags: react, video, discuss
Published: 2018-10-25 16:21:13

---
title: React Conf Live Stream is on
published: true
description: 
tags: react, video, discuss
---

{% youtube kz3nVya45uQ %}

[Here](https://reactjs.org/docs/hooks-intro.html) are the docs for the new hooks API.
Reminder to follow the code of conduct
Tags: meta
Published: 2018-10-25 16:10:09

Hey folks, we just want to remind you of the importance of following the community [Code of Conduct](https://dev.to/code-of-conduct).  It’s very important that we all work to maintain an inclusive and constructive environment.

As the DEV Community grows, we need to uphold our standards of professionalism and courtesy. Nobody’s perfect, and on the Internet it’s easy to be misconstrued, but we expect everyone to make a good faith effort.

Thanks to everyone in the community who helps mods and admins do their jobs by reporting abuse and violations. And an additional thanks to everyone who proactively uplifts other DEV members through supportive comments.

Happy coding.
GitHub-style contribution graph for your blog
Tags: javascript, showdev, discuss, dataviz
Published: 2018-10-25 15:52:21

Here's my latest project:

[accountableblogging.com/post-frequency](https://accountableblogging.com/post-frequency).

I'm working on tools to help budding bloggers and content creators take the leap

dev.to has short feeds (15 items) but you should be able to see something like this:

![](https://thepracticaldev.s3.amazonaws.com/i/wgdlk06kvlvr0md9yovx.png)

I've also launched on [Indie Hackers here](https://www.indiehackers.com/forum/show-ih-a-github-style-graph-for-your-blog-da74a24d42), let me know what you think.
Javascript and JSON.stringify: It Almost Comes Correct
Tags: json
Published: 2018-10-27 23:26:59

---
title: Javascript and JSON.stringify: It Almost Comes Correct
published: true
tags: "json"
canonical_url: https://jacoby.github.io//javascript/2018/10/25/javascript-and-jsonstringify-it-almost-comes-correct.html
---

JavaScript has [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON), a built-in that allows you do good and wonderful things with objects.

Assume we create an object:

```
let obj = {};
obj.a = 1;
obj.b = ["foo", "bar"];
console.log(JSON.stringify(obj));

```

And we get

```
{ "a": 1, "b": ["foo", "bar"] }

```

That’s tight, but we _might_ want to expand it out for readability. So, we go to `JSON.stringify(obj,null,2)`.

```
{
  "a": 1,
  "b": ["foo", "bar"]
}

```

And `JSON.parse` would take that text back into an object form. Win-win! I love it!

But … why is that `null` up in there?

Because that’s the [Replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).

```
> console.log(JSON.stringify(obj,['b'],2));
{
  "b": [
    "foo",
    "bar"
  ]
}

```

Man, that’s simple. Just put in an array basically saying “cut things down to just this.

Gotta say, I kinda love it.

Consider every war movie you’ve heard. When captured, you give the opponent name, rank and serial number, so with `JSON.stringify(prisoners,["name","rank","serial_number"])`

You get a version of the array that looks like

```
[{"name":"James Buchanan Barnes","rank":"Sergeant","serial_number":"999-99-9999"},...]

```

With all the mess like birthplace or activation codes messing up your pretty data structure. I could really see my server-side Node code doing this with the data sent to the client.

Except, I don’t have any of that. All my back-end stuff is Perl. When I’m creating objects to send back to the server, I control what I stick into it, so I don’t need that last catch.

The problem is something I consider a big anti-pattern, **Positional Parameters**. stringify, as written, brings in `(value,replacer,space)`, where **value** is the thing to be stringified, **replacer** limits what will be placed and **space** tells us how it will indented. And, by convention, you _must_ have value (you _don’t_, but without it, it’s kinda a no-op), but you _can_ add a replacer without a space, but you _cannot_ add a space without a replacer, even if the replacer is `null`.

The other option is **Named Parameters** , where we might start with `stringify(obj)` or `stringify(value:obj)`, to lean more on JS formatting, which might allow us `stringify(value:obj,space:2)` so we need no replacer if we don’t want it.

If I was writing this now, I would want to reverse the order of the positional parameters, because, hey, I want readable JSON a lot more than I want filtered JSON. But because it already exists as is, that would break things.

If you have any questions or comments, I would be glad to hear it. Ask me on [Twitter](https://twitter.com/jacobydave) or [make an issue on my blog repo](https://github.com/jacoby/jacoby.github.io).
To Keep Progressing
Tags: career, life, mentalhealth
Published: 2018-10-25 13:13:34

---
title: To Keep Progressing
published: true
description: What must we do to keep progressing?
tags: #career, #life, #mental health
---

To keep progressing, we must 

1. **learn**
2. **commit**
3. **do**

(Repeat)

STEVEN COVEY
You want HOW MANY years experience?!
Tags: showdev, javascript, react
Published: 2018-10-25 12:29:42

---
title: You want HOW MANY years experience?!
published: true
description: A handy tool for tech recruiters who ask for fifteen years experience in technologies that have only existed for three months.
tags: showdev, javascript, react
---

This is something I whipped up last night and today at lunch, inspired by some recent complaints here on dev.to about recruiters.

It's a tool for those recruiters who demand years of experience in skills that have only just come out.

![A list of technologies and their ages](https://thepracticaldev.s3.amazonaws.com/i/gtinolks1m5gka0w1bzf.PNG)

Other than throwing some light-hearted shade, my objective was to have a go at using [create-react-app](https://github.com/facebook/create-react-app) after hearing about it so many times on [Syntax.fm](https://syntax.fm/) and WOW. WOW.

Site: https://howoldisit.glitch.me/
Code: https://github.com/jsrn/howoldisit
Deployed on [Glitch](https://glitch.com/) ❤
Introduction to Rx (Swift & Kotlin) - Part 3
Tags: rx, functionalreactive, swift, kotlin
Published: 2018-10-25 12:29:42

---
title: Introduction to Rx (Swift & Kotlin) - Part 3
published: true
description: Part 3 of the Rx tutorial series
tags: Rx, Functional Reactive, Swift, Kotlin
---

The next entry on my ongoing Rx tutorials. Choose the one you are most comfortable with. Have a nice day!

https://blog.testfairy.com/rx-for-the-ultimate-beginner-part-3-swift/
https://blog.testfairy.com/rx-for-the-ultimate-beginner-part-3-kotlin/
Simple Auto Wiring Container
Tags: php, showdev
Published: 2018-10-25 12:12:55

---
title: Simple Auto Wiring Container
published: true
description: I did not need a DI container but needed auto wiring container. Originally, I divided the container class I used with my own framework.
tags: php,showdev
---

I did not need a DI container but needed auto wiring container.
Originally, I divided the container class I used with my own framework.

{% github nishimura/simple-container %}

This container class has only the basic methods that I actually use in the project.

The implementation of the interface is registered by the `set` method, and the dependency is written PHP code to the `setFactory` method.
However, most dependencies will be solved with the Auto Wiring.

```php
class Foo
{
    private $obj;
    public function __construct(stdClass $obj)
    {
        $this->obj = $obj;
    }
}

$c = Container::getInstance();
$foo = $c->get(Foo::class); // constructor injection, no config


// set implements
interface Uri {}
class MyUri implements Uri {}

$c->set(Uri::class, new MyUri);
$uri = $c->get(Uri::class);

// or
$c->setFactory(Uri::class, function($c){
    return new MyUri();
});

// singleton
$c->setFactory(Uri::class, function($c){
    $myUri = new MyUri();
    $c->set(Uri::class, $myUri);
    return $myUri;
});
```

When using Auto Wiring in a method call, you need to call the `call` method manually.

```php
class MyIndexAction
{
    public static function index(Request $req, Response $res, MyForm $myForm)
    {
        // ...
    }

    public function __construct(MyForm $myForm) { $this->myForm = $myForm; }
    public function index2(Request $req, Response $res)
    {
        // ...
    }
}

$c->call(MyIndexAction::class, 'index');

// or
$action = $c->get(MyIndexAction::class);
$c->call($action, 'index2');
```

Most of the functions of this container are explained in these samples.
Simple but when combined with `FastRoute`, session libraries, etc., a simple micro framework is completed without a moment.


NOTE: I do not know if this program can be used in actual projects. I am trying it.
4 Incredible Benefits Of Using OpenCart To Make An Online Store
Tags: opencartdeveloper, opencartmalaysia, opencartdevelopment
Published: 2018-10-25 12:12:46

---
title: 4 Incredible Benefits Of Using OpenCart To Make An Online Store
published: True
description: Here are 4 features it offers, that makes it absolutely stellar 
tags: opencart developer, opencart malaysia, opencart development,
---
In the world of rising online businesses, having top-notch quality has become a necessity. Since customers today have a plethora of ventures to choose from, to make sure you're on top, your online store has to be phenomenal. This can only be achieved with the help of an amazing ecommerce platform! OpenCart is one of the many, in the ecommerce race, and this platform is leading it! Catering to thousands of businesses today, this platform can be an amazing choice for yours too.

![Opencart Development Malaysia] ( https://thepracticaldev.s3.amazonaws.com/i/uy7tyimnx4yitc2c867w.jpg)

Here are 4 features it offers, that makes it absolutely stellar:
 
**1) Cost-Efficient**

Initially, not every business has the capital to spend on making a website, additionally, this process is costly! However, OpenCart eCommerce development offers affordable solutions to businesses, since it is module based. It is easy to set up and use, and demands no more than what an individual can manage!

**2) SEO-Optimized**

Without SEO, your online store will never reach the audience you seek. To rank at the top in Google needs your website to have a healthy SEO ranking, one which OpenCart provides with ease. Being optimized, it ensures your pages make it to Google searches and reach necessary customers without any hindrance.

**3) Multi-Management**

One of the most attractive features OpenCart offers! With this, you have the provision to make and manage multiple online stores. Additionally, you can operate stores in different languages without knowing them. OpenCart eCommerce Development allows you to have multi-lingual stores, and cater to your audience no matter which corner of the globe they are in!

**4) Plethora of Payment Options**

Not everyone has a PayPal account, and not everyone has a debit card. Different people prefer different methods of payment. OpenCart facilitates easy payment, by equipping businesses with multiple payment portals to enhance user experience.
 
E-commerce can singlehandedly take your venture to the skies if you can implement it well. Get yourself experienced professionals today, and watch as your business births a massive boom. Call Openwave - the [Best OpenCart Development Company] (https://www.openwavecomp.com.my/ecommerce-website-development.html) in Malaysia!