teleren/devto huggingface dataset:
Manipulating INTERVALs in Ecto fragments
Tags: ecto, postgres, phoenix, elixir
Published: 2020-04-08 15:16:12


##  Parametarizing INTERVAL units

If you ever had to come across a task of selecting entries for last N  hours/days/month you're probably already familiar with **ERROR 22007 (invalid_datetime_format) invalid input syntax for type interval** coming right your way from PostgreSQL. 

Let's work it out on an example of selecting all emails from users that signed up during the last day or month. 

A rough translation of such SQL query to Ecto can look like this

```elixir
period = "day"

Repo.all(
  from(u in "users",
    select: {u.email, u.inserted_at},,
    where: u.signup_date > fragment("CURRENT_DATE - INTERVAL '1 ?'", ^period)
  )
)
```

As far as I'm acknowledged the reason for `invalid_datetime_format` error to happen is that parameter substitution is not allowed in string literals. Instead, we can rewrite the query to use a very neat trick of string concatenation to combine interval parts into a single string


```elixir
period = "day"

Repo.all(
  from(u in "users",
    select: {u.email, u.inserted_at},,
    where: u.signup_date > fragment("CURRENT_DATE - ('1 ' || ?)::interval", ^period)
  )
)
```

voila 


```elixir
[
  {"text@exampe.com", ~N[2020-04-08 09:31:02.000000]},
  {"test2@example.com", ~N[2020-04-08 09:34:42.000000]}
]
```

##  Parametarizing number of INTERVAL units

Now, let's imagine that we want to parameterize the number of intervals - go from "last day/month" to "last N days/months".

Again, we know that it's impossible to do `fragment("CURRENT_DATE - INTERVAL '? ?'", ^amount, ^period)`. Why not circumvent this limitation with multiplication? 

```elixir
amount = 3
period = "day"

Repo.all(
  from(u in "users",
    select: {u.email, u.inserted_at},
    where: u.signup_date > fragment("CURRENT_DATE - ('1 ' || ?)::interval * ?", ^period, ^amount)
  )
)
```

which gives us 

```elixir
[
  {"test3@example.com", ~N[2020-04-06 12:07:20.000000]},
  {"text@exampe.com", ~N[2020-04-08 09:31:02.000000]},
  {"test2@example.com", ~N[2020-04-08 09:34:42.000000]}
]
```

And that's how good old basic operations can save a day ;) 

Kudos to peeps at #posgresql @ Freenode for explaining how to overcome those problems.
Working with Markdown in VS Code
Tags: vscode, beginners
Published: 2020-04-08 15:04:52

**Update:** [Here's an excellent interactive tutorial](https://commonmark.org/help/tutorial/index.html) to supplement/replace this post.

## About the Video

The video shows up some basic VS Code shortcuts while focusing specifically on getting a 'side by side' preview in VS Code where we can edit Markdown code and get a preview of our changes right next to it.

## About Markdown

Markdown is a **super simple language**...as in super simple...not the 'it's simple b/c I'm some super senior dev' simple, but as in I could have taught my 'hunt and peck' typing dad how to use it...

However, unlike HTML (which is harder than Markdown, FYI) that will automatically be parsed and displayed in a browser, Markdown can only be rendered by a Markdown renderer or engine.

## Why Learn Markdown?

*I am not saying that Markdown replaces HTML.*

But, in the event that I just want to quickly format some text and even work with images and alt tags (the text description that helps your image's SEO, works with screenreaders for visually impaired, or just describes your image in case something is screwed up and your image won't load), Markdown is quick and efficient. 🤓

For one thing, Markdown is the best way to quickly format posts here on dev.to. 

For another thing, if you are on a service like [GitHub](HTTPs://www.github.com), any public-facing repositories should have a specially named file: 'README.md' (yeah, the 'md' extension stands for Markdown). That's what folks will see when they pull up one of your projects on GitHub. [Example](https://github.com/manavm1990/js-starter)

Other than that, there are numerous other platforms that allow you to quickly format some text using Markdown - it beats highlighting and clicking on stuff.

## How Can I Learn It?

Well, if you watched the video above and you have [VS Code](https://code.visualstudio.com/download) then, here's pretty much all you need to know to get started!

```markdown
# This is a Header

## This is a Smaller Header

### This is an Even Smaller Header

Here is some normal text. A paragraph, even!

_This text is in italics._

**This text is in bold.**

**_This text is in both._**

~~This text is rendered with a strikethrough.~~

- Item
- Item
- Another item

1. Item one
2. Item two
3. Item three

1. Item one
2. Item two
3. Item three 
	1. Sub-item 
	2. Sub-item
4. Item four

---

[I'm a link to a web page!](http://www.google.com)
![alt text](https://i.imgur.com/81qyN1y.jpg)`

```
Working from home - How to deal with big PRs? (Day 18)
Tags: remote, webdev, development, watercooler
Published: 2020-04-08 14:26:56

---
title: Working from home - How to deal with big PRs? (Day 18)
published: true
description: Continuous journey of working from home due to COVID-19 outbreak at the world. This is my journey, my challenges in trying to be productive and completely changing my work habits from office first to remote first. 
tags: remote, webdev, development, watercooler
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/uktkpjf8u7m1k5ac8188.jpg
series: working from home
---
## General

Monday kicked in again. The weekend was nice, with usual up's and down's. But I'm emotionally fine with the situation. I still don't know how to handle the whole Covid-19 situation. I've realized I subscribe to NYT and other things to be up-to-date on the issue from sources I trust.


## Work

This is an issue I faced at work (the truth is, I realized some was SVG code, so it was around 2k of pure JS code):

{% twitter 1247089961960079361 %}

How to deal with this? I got some great strategies and feedback from former colleagues. 

Based on that I realized this is how I will tackle it:

- Recommend to do a Pair Review / Programming of this Pull-Request. Show the other co-worker why certain things are an issue. And ask all the clarification questions.
- Share with them the issue of such big PR. Don't hide for months, openly share the PR (use Draft PRs from GH). Please separate this to separate smaller PRs (cherry-pick). I'm sharing that changing to smaller PRs would make it easier for me to review vs. one big. [Paul suggested](https://twitter.com/therealpadams/status/1247108020024336384) at least two branches with "easy to review vs. hard / complex logic". Let's see if this works.
- If we go with one big fat PR, I will share clearly that I won't be able to review easily and knowing the test in detail doesn't change the need for good code quality, naming, structure and other things. 

Another tip was to have expressive commit messages like "a story" so we could go and review commit by commit. But sadly, half of commits are like this:

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



## TIL

Don't hide your features for months. Create WIP Pull Requests and ask for feedback early on.

Also, use the full functionality of Github or other Repository Tools. Share Screenshots, tell possible Reviewers what is connected to what. Especially working from home is changing Reviews. I can't just go to your desk and ask you. I don't know the design of your solution / feature / ab-test.

The learnings for all of us:

- Small Pull Requests over Big Pull Requests
- Start sharing your PR early (use Draft PRs or WIP). Ideas need feedback, so does software solutions.
- Be expressive in your commit messages. Using Squash Merge is not an excuse to have unclear commit histories.



Cheers,

Ferit
Watch Me Code - Adding Ionic Components To Vue JS App
Tags: video, javascript, webdev, vue
Published: 2020-04-08 14:52:33

This video is about integrating [Ionic Framework Web Components](https://ionicframework.com/docs/) into a basic vuejs app to make it look much more professional.

This is the first part where I just make the UI look better; next I will add loading screen, toasts for error messages and a modal window to replace the input form ALL with [Ionic Framework Web Components](https://ionicframework.com/docs/).

This is all to show how integrating UI components even into the most basic project makes it look much more professional to your customers and clients.

**VIDEO:** https://youtu.be/-Hc4tRcdwhI
**CODE:**   https://github.com/aaronksaunders/watch-me-code-vueworkshop-vuex-live

{% youtube -Hc4tRcdwhI %}
This Post has 100 Positive Reactions
Tags: showdev, typescript, javascript, node
Published: 2020-04-08 14:51:33

> The script mentioned in the following blog post has been turned off now. So the script doesn't know when someone gave a positive reaction. But, I do and it delights me when I get a positive reaction 😄

Recently Tom Scott posted a [video](https://www.youtube.com/watch?v=BxV14h0kFs0) on Youtube whose title has the number of views of the video.

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

Here is what's happening behind the scenes. There's a script running which continuously updates the title of the video to match the view count. In the video, he talks about the rise (and kind of fall) of APIs provided by platforms. He talks about creative applications of accessing APIs and making bots.

I was quite amused by the video. Luckily Dev.to has its API in beta stage. Lightbulb! So I wrote a small Typescript Bot that continually updates the total positive reactions to this post in the title. If everything is working alright, the sum of the positive responses to the post should match with the title. If it is not, then I either shut down the script, or it crashed.

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

The fun part is that you can try the code yourself and publish your post like this one! Find the code in this [repo](https://github.com/godcrampy/dev-to-reaction-bot)

🚀 Find me on [Instagram](https://www.instagram.com/godcrampy/) | [Github](github.com/godcrampy) | [Twitter](twitter.com/godcrampy) | [Website](sahil.surge.sh)
😄 Have a wonderful day!
Quarantine Games - Pictionary!
Tags: productivity, watercooler
Published: 2020-04-08 14:04:03

---
title: Quarantine Games - Pictionary!
published: True
description: It is easy to feel demotivated or disconnected from your team when we are all isolating. We have started doing weekly games at work to be more connected in the team. This one is Pictionary
tags: #productivity #watercooler
---

It is easy to feel demotivated or disconnected from your team when we are all isolating. We have started doing weekly games at work to be more connected in the team. First one is Pictionary : 

###You will need: 
*Drawing software (paint) 
*Calling + Screen Share Software (Teams, Zoom, Slack etc) 

###How it runs: 
 
Split into 2 [random](https://www.jamesbaum.co.uk/team-generator/)  teams on the call.
A person from each team will draw for their own team ( I think that’s the easiest). 

Team 1 – a person from team one uses [a random generator](https://randomwordgenerator.com/pictionary.php) to pick a word. I suggest starting with "medium" difficulty. 
Person then shares their screen with paint opened ready to draw.

Team 2 starts 1 min timer and GO ! 
Person from Team 1 draws the picked word
Team 1 guesses the word.

If they guess correctly, team gets a point. If not then :( 
Team 1 and Team 2 swap roles.


Track your score! Do 5 rounds and see how it goes - you can do movie categories or something harder later on. Its quite hard to draw with a mouse - start small and improve over time :)
A 5-minute guide to using tmux
Tags: tmux, ssh, bash, wfh
Published: 2020-04-08 13:52:18

What if we `ssh` to a machine and hope that even when we lose the `ssh` connection, we can come back to it as if nothing has happened?

For example, if we start up a Rails or Django server and hope to keep it running.

It is really simple with `tmux`.

Just create some aliases first and add to your `.bashrc`:

```bash
alias tmuxls='tmux ls'      # see all the sessions
alias tmuxn='tmux new -s'   # start a new session
alias tmuxa='tmux a -t'     # attach back to a session
```

That's it.  Next time after you `ssh`, you can start a session:

```bash
tmuxn foo
```

or
```bash
tmuxn server
```
and now you have a session called "foo" or "server".  If your `ssh` got disconnected, simply `ssh` back, and do a

```bash
tmuxa foo
```
and you will be able to go back to that session.

Inside, you can press <kbd>Ctrl</kbd><kbd>c</kbd> to stop the command (such as the Rails server), and press <kbd>Ctrl</kbd><kbd>d</kbd> to end the session if you want.

You can have multiple terminals or `bash` attach to the same session. Simply use
```bash
tmuxa foo
```
in that shell.

And to "detach", simply press <kbd>Ctrl</kbd><kbd>b</kbd>, and then <kbd>d</kbd>. The session will still be there, and you can attach back to it any time you want. 

To end that session, stop anything you are running in that session by <kbd>Ctrl</kbd><kbd>c</kbd>, and press <kbd>Ctrl</kbd><kbd>d</kbd>.

That's it.  That's all is needed to start using `tmux`. The basic idea is:

1. To create a new session
2. To attach back to it
3. To detach from it if you want to (usually we don't have to)
4. To see all the sessions

We can `ssh` once to start a tmux session and run the Rails server, and `ssh` in another terminal to do the usual tasks. Scrolling up and down is easier inside a normal shell.

If you need to turn off your local machine, simply "detach" your session, and exit from the `ssh`, and now you can shut down your machine. Next time after you turn on your machine, simply `ssh` back to the remote machine, and `tmuxa foo` and get back to that session.

If you want, you can make these shorter aliases:
```bash
alias tls='tmux ls'      # see all the sessions
alias tn='tmux new -s'   # start a new session
alias ta='tmux a -t'     # attach back to a session
```
UI component libraries are awesome!
Tags: frontend
Published: 2020-04-08 13:50:29

---
title: UI component libraries are awesome!
published: true
description: There are lots about UI libraries that fascinate me. It's like laying the foundation for the whole thing! 
tags: Frontend
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/slysrxkudld89266je46.png
---
Hey devs from all over the world 😊

We all know what UI component libraries are, There are tons of great ones out there. I am more interested in building them though. It's like laying a foundation that will be used in every project to come! To me, That's both super scary and super cool!

### Its impact

I love the idea of writing code that will be used and maintained by every developer in every project. I mean you are not just building a boring `contact-us` page or anything, you are writing components for every future project.

Of course, it is not a one-time project kinda thing. UI libraries should always be `In development`. That being said, maintaining an already mature UI library is one thing but "laying the foundation" sounds way cooler to me.

### It is sophisticated

A couple of years ago, The only way frontend code gets used over and over again is by making CSS classes. That's it! A couple of CSS rules that get applied to multiple elements. It was a big thing! I remember how changing a small value in those famous classes impacted the whole project. 

Now, UI component libraries are much more sophisticated! First off, These components contain both the HTML & the CSS, They render differently depending on the props (input) you give them, They should also be able to handle as much use cases as possible. Of course, They won't be able to handle all of them out there! This is more of a utopia kinda thing. But still, UI libraries are not just about your use cases, They are built for everyone!

### Its a bridge between design and dev

Designers usually have lots of systems in place. They have systems for colors, typography, sizes. They even build components like buttons and input fields. Then they use those systems and components all over their designs.

UI components libraries are the closest thing to a design system in the dev world. They should be built upon the design system. That will ensure those systems are more of rules not just guidelines and make sure the look & feel is consistent across all projects that use the same UI library. 

### It speeds up development

I am sure UI libraries do speed up development if they are mature enough. But, they still take a big investment upfront. Also, they should be maintained all the time to handle new use cases and business logic. 

I think they are an investment that only bears its fruit in the long term. I was never involved in the process of building a UI library from scratch before. I would love to someday!

That's basically it! Now it's your turn, tell me how you feel about UI libraries? Have you ever been involved in building one from the start? Do you have any tips and tricks that you learned while building one?

As always,
**Happy coding 🔥🔥**
**“كود بسعادة”**
Getting Null values for CPUInfo
Published: 2020-04-08 13:26:22

I am trying to fetch the CPU metrics & it is returning output like this for cpuinfo. Why it is not returning any value? 
    [[user, kernel], [0, 0]]
    
This is my code : 

    package demo.demo;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;ient.AppiumDriver;
    import io.appium.java_client.MobileElement;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import io.appium.java_client.android.AndroidDriver;
    import io.appium.java_client.remote.MobileCapabilityType;
    import io.appium.java_client.android.HasSupportedPerformanceDataType;
    public class Performancee {
    	static AndroidDriver<MobileElement> oDriver;
    	  public static void main(String[] args) {
    		  try {
    	          setUp();
    	          List<String> supportedPerformanceDataTypes = oDriver.getSupportedPerformanceDataTypes();
    	          System.out.println(supportedPerformanceDataTypes);
    	          for (String dataType : supportedPerformanceDataTypes) {
    	        	  List<List<Object>> valueTable = oDriver.getPerformanceData("com.instagram.android", dataType, 60000);
    	        	  System.out.println("\nThe Performance Data is : "+ valueTable);
    	          }
    	          tearDown();
    	      }catch(Exception e) {
    	          e.printStackTrace();
    	      }
    	  }
    	public static void setUp() throws MalformedURLException 
    	{
    		try {
    			DesiredCapabilities dcap = new DesiredCapabilities();
    			dcap.setCapability("appPackage", "com.instagram.android");
    			dcap.setCapability("appActivity","com.instagram.android.activity.MainTabActivity"); 
    			dcap.setCapability("app","C:\\Users\\mabhishek\\Downloads\\Instagram.apk"); 
    			dcap.setCapability("autoGrantPermissions", true); 
    			dcap.setCapability("deviceName", "Abhishek");
    			dcap.setCapability("udid", "23aaa9a4");
    			dcap.setCapability("automationName","UiAutomator2");
    			dcap.setCapability("platformVersion", "9");
    			dcap.setCapability("platformName", "Android");
    			URL remoteUrl = new URL("http://localhost:4723/wd/hub");
    			oDriver = new AndroidDriver(remoteUrl, dcap);
    			System.out.println("Successfull connection!!");
    			oDriver.launchApp();
    		  }
    	 catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    		}
    	  
    	  public static void tearDown() {
    		 oDriver.quit();
    	  }
    }






Following is the OUTPUT : 
[cpuinfo, memoryinfo, batteryinfo, networkinfo]

The Performance Data is : [[user, kernel], [0, 0]]

& rest everything is printing properly. I didn't print as output was very huge. Problem is only with CPUinfo..
Django check SEO - A cool django/django-cms plugin
Tags: seo, django, djangocms
Published: 2020-04-08 13:22:41

Hello dev.to, today I will present you a Django/django-cms application!

![Screenshot of django check seo](https://up.l3m.in/file/1583523465.png)

Django has a very cool and complete ecosystem, but when we wanted to allow our clients (the users of the websites we create) to check the SEO of their pages, we used to rely on a third party service.

It's in the perspective of solving this little flaw that I've been asked to create [**Django Check SEO**](https://github.com/kapt-labs/django-check-seo/)!

![separator](https://user-images.githubusercontent.com/45763865/78788551-465c2080-79ac-11ea-9828-997011272432.png)

# What does this tool do?

Django Check SEO will check the SEO aspects of your website for you, and then will make a cool report of the different problems and warnings.

![COOL A NICE LITTLE GIF](https://up.l3m.in/file/1586350493-django-check-seo-demo-light.gif)
<figcaption><i>(webm video is available <a href="https://up.l3m.in/file/1586350624-django-check-seo-demo.webm">here</a>)</i></figcaption>

![separator](https://user-images.githubusercontent.com/45763865/78788551-465c2080-79ac-11ea-9828-997011272432.png)

# How does it do that? 

It's a simple webpage with a Python backend that fetches the code of the current page (using `requests`), parses the HTML (using `beautifulsoup4`), and then performs some custom tests to make sure the page is SEO friendly.

Each test will populate a list (problems, warnings or success) based on the content of the html "soup".

![schema](https://user-images.githubusercontent.com/45763865/78782300-190a7500-79a2-11ea-96f7-b1384c015518.png)

![separator](https://user-images.githubusercontent.com/45763865/78788551-465c2080-79ac-11ea-9828-997011272432.png)

# [Insert some concluding comment here]

To finish my first post, I will write some notes:

* This is my first "big" Python project/package.
* You can install it using pip (`python3 -m pip install django-check-seo`).
* It's compatible with `python2` & `python3` (*but please use Python 3*). 
* We have made this tool for our personal use, but decided to make it open source so that everyone who needs it can use it.
* The project have [a wiki](https://github.com/kapt-labs/django-check-seo/wiki) (*english is not my first language, so sorry for the mistakes*).
* We heavily use `django-cms` to build websites, so Django Check SEO is available in one click from the top bar of django-cms.
* I wrote [unit tests](https://github.com/kapt-labs/django-check-seo/tree/master/tests) (*[video](https://up.l3m.in//file/1586351795-django-check-seo-tests.webm)*) !
* We choose to extract non-essential content with `css selectors`, [here's a cool example](https://github.com/kapt-labs/django-check-seo/issues/35#issuecomment-593429870).

![separator](https://user-images.githubusercontent.com/45763865/78788551-465c2080-79ac-11ea-9828-997011272432.png)

I have hundreds of questions for you, but I'm only going to ask these:

Do you have any comments about this project? Have you ever created a Python project? If so, what was it like?

Feel free to comment this post :)
Corona Pandemic: How to use this time to get practice in JavaScript?
Tags: javascript
Published: 2020-04-08 13:19:48

Due to Corona virus, My country (Sri Lanka) is on lockdown/curfew like many otger countries.
Because of this lockdown, I am so bored. So I decided to get some practice in JavaScript. BUT, My brain is so bad at giving ideas. So, I posting a new post to get ideas from other devs.

Please tell your ideas. And help me.

**Note** : I am a intermediate level JavaScript developer. I am good at Frontend development too.