teleren/devto huggingface dataset:
5 string methods in JavaScript.
Tags: javascript, node
Published: 2020-11-29 20:22:20

---
title: 5 string methods in JavaScript.
published: true
date: 2020-11-27 11:00:00 UTC
tags: javascript, nodejs
canonical_url: https://blog.murtajaziad.xyz/5-string-methods-in-javascript/
---

Strings are useful for holding data that can be represented in text form, and here’s 5 methods for them.

* * *

### 1. includes()

includes() method determines whether one string may be found within another string, returning `true` or `false`.

```js
const sentence = "The quick brown fox jumps over the lazy dog.";

const word = "fox";

console.log(
  `The word "${word}" ${
    sentence.includes(word) ? "is" : "is not"
  } in the sentence.`
); // The word "fox" is in the sentence.
```

### 2. replace()

replace() method returns a new string with some or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. If `pattern` is a string, only the first occurrence will be replaced.

```js
const p =
  "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
const regex = /dog/gi;

console.log(p.replace(regex, "ferret")); // The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?

console.log(p.replace("dog", "monkey")); // The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?
```

### 3. split()

split() method divides a `String` into an ordered list of substrings, puts these substrings into an array, and returns the array.

```js
const str = "The quick brown fox jumps over the lazy dog.";

const words = str.split(" ");
console.log(words[3]); // fox

const chars = str.split("");
console.log(chars[8]); // k
```

### 4. startsWith()

startsWith() method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate.

```js
const str = "Saturday night plans";

console.log(str.startsWith("Sat")); // true
```

### 5. trim()

trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

```js
const greeting = " Hello world! ";

console.log(greeting); // " Hello world! "
console.log(greeting.trim()); // "Hello world!"
```
Stacky REST API #2 - Babel Setup
Tags: node, tutorial, javascript, babel
Published: 2020-11-27 10:58:26

Welcome to part two of building a REST API with Node.js. In the previous part, we covered the initial setup and in this part, we'll be adding babel to our project.

**Babel** is a tool used to convert ECMAScript 2015+ code not included in the recent Node.js versions, into a backwards-compatible version that older environment will understand. 

Open up the **app.js**  file and use javascript import statement instead of `require`.
```jsx
import express from 'express';
```
Run the application and sadly it breaks 😟! 

To fix this let's set up our hero 🦸‍♂️ Babel by installing the following dev-dependencies;
```bash
$ yarn add @babel/core @babel/preset-env @babel/node -D
```
- **@babel/core** - the core functionality of Babel.
- **@babel/preset-env** - common bundles of plugins needed to transpile new and upcoming features.
- **@babel/node** - works exactly the same as the Node.js CLI, with the added benefit of compiling with Babel presets and plugins before running it.

Edit the start script in the **package.json** file;
```json
"start": "nodemon --exec babel-node src/app"
```
In the project's root folder, create a **.babelrc**;
```json
{
    "presets": [
        "@babel/preset-env"
    ]
}
```
Run the application again and it works!


What babel is simply doing is transpiling our code to vanilla JavaScript under the hood. Anytime you use a JavaScript feature, which hasn't been introduced in Node.js, Babel makes sure that Node.js understands it so our application doesn't break.

One more important step we have to do is to build our application. In reality, we won't be using nodemon and transpiling our code at runtime when we move our application to production. Rather, we push the transpiled codes to our production server.

Install the @babel/cli module which allows us to use babel from the terminal.
```bash
$ yarn add @babel/cli -D
```
Let's add a build script to our **package.json** file. This executes babel on the javascript files in the **src** folder and outputs the transpiled code to a **dist** folder which we can then upload to our production server.
```json
"build": "babel src/ -d dist/"
```
Build the application and we should see a **dist** folder in our project. You can take a look at the **app.js** file to see the output.
```bash
$ yarn build
```
Lastly, we need to modify the scripts section in the **package.json** file.
```json
"scripts": {
    "build": "babel src/ -d dist/",
    "dev": "nodemon --exec babel-node src/app",
    "start": "node dist/app"
},
```
In the next article, we’ll be setting up a database for our application.
structure synth [Fractal Frame]
Tags: codepen
Published: 2020-11-27 10:46:50

---
title: structure synth [Fractal Frame]
published: true
tags: codepen
---

<p>Structure adapted from 
 <a href="https://github.com/ankurpawar/StructureSynth/blob/master/FrameFractal/framefractal1.es" target="_blank">https://github.com/ankurpawar/StructureSynth/blob/master/FrameFractal/framefractal1.es</a></p>

<p><a href="http://structuresynth.sourceforge.net/index.php" target="_blank">http://structuresynth.sourceforge.net/index.php</a></p>

{% codepen https://codepen.io/ge1doot/pen/vYXYjbZ %}
Do you prefer Fetch or Axios?
Tags: webdev, discuss, http, api
Published: 2020-11-27 10:30:39

---
title: Do you prefer Fetch or Axios?
published: true
description: 
tags: webdev, discuss, HTTP, api
cover_image: https://i.morioh.com/201028/78bb1d3b.webp
---
One of the fundamental tasks of any web application is to communicate with servers through the HTTP protocol. This can be easily achieved using Fetch or Axios.

The Fetch API is built-in most modern browsers and provides a fetch() method defined on the window object, while Axios is a specific 3rd party Javascript library you must install manually.

Which method do you usually use and do you think adding a library (around 4.4KB gzip) is worth it for the extra features it brings?
Turkey detector: awful answers only
Tags: challenge, programming, jokes, turkeys
Published: 2020-11-27 10:28:31

---
title: Turkey detector: awful answers only
published: true
description: Challenge to write code to detect when someone has achieved three strikes in a row, but badly
tags: challenge, programming, jokes, turkeys
series: awful answers only
//cover_image: https://direct_url_to_image.jpg
---

It's turkey season in many places, especially for those of you in the United States of America.

And we all know what a turkey is, right? Yes, that's right. In ten pin bowling a turkey is when you get three strikes in a row. 

I'm not sure why this time of year is dedicated to that, but there you have it. Traditions don't always make sense.

So, today's challenge is to find turkeys in people's bowling scores.

The function you write will need to take an array of arrays. The array will hold up to ten sub arrays. The first 9 sub arrays will always have 2 integers, from 0 to 10, and the 10th sub array will hold either 2 or 3 integers, from 0 to 10. 

A strike for the first 9 sub arrays a strike is this sub array: `[10,0]`.

For the 10th frame there can be up to 3 strikes:

- single strikes: `[10, 0, x]`, `[x, 10-x, 10]` 
- double strikes: `[10, 10, x]`
- turkey: `[10, 10, 10]`

Where `x` is any integer from 0 to 9.

Examples:

``` javascript
hasTurkey([[0,10],[1,5]]) //false
hasTurkey([[10,0],[10,0],[10,0]]) //true
hasTurkey([[10,0],[10,0],[0,10]]) //false
hasTurkey([[10,0],[10,0],[0,10],[9,1],[10,0]]) //false
hasTurkey([[0,10],[1,5],[2,1],[0,4],[8,1],[8,0],[10,0],[10,0],[10,0],[0,10,4]]) //true
hasTurkey([[0,10],[1,5],[2,1],[0,4],[8,1],[8,0],[10,0],[10,0],[9,1],[0,10,4]]) //false
hasTurkey([[0,10],[1,5],[2,1],[0,4],[8,1],[8,0],[1,0],[1,0],[10,0],[10,10,4]]) //true
```
I want to see your worst implementations. Exponential time. Exponential space. Convoluted code. All of it. Roast the CPU like a turkey.
Fullstack GraphQL starter kit November update
Tags: javascript, typescript, react, node
Published: 2020-11-27 10:09:57

Hi Dev.to community, I am excited to share the November update which adds exciting things to the starter kit.

<b>Changes:<b/>

- [Full overview of the project](https://www.youtube.com/watch?v=TgtUhEnW8O4), in this video I go over getting started with this starterkit as well as things like code organization, testing, e2e codegen etc. Hopefully, this was helpful to the community
- [Cypress](https://www.cypress.io/) as an E2E testing framework with sample test!
- [Prisma](https://www.prisma.io/) has been updated to version `2.12.1` with tons of exciting [new features](https://github.com/prisma/prisma/releases/tag/2.12.1)
- Dependency updates and minor refactors

<i>Full changelog/PR is available [here](https://github.com/karanpratapsingh/fullstack-starterkit/pull/25)


Github: https://github.com/karanpratapsingh/fullstack-starterkit

What do you think? as always feel free to reach out if you face any issues.

Happy coding :tada:
#PureCSS - Responsive PHP 8 Logo
Tags: codepen, purecss, css, php
Published: 2020-11-27 10:09:10

---
title: #PureCSS - Responsive PHP 8 Logo
published: true
tags: codepen, purecss, css,php
---

<p>Pure CSS PHP 8 Logo</p>

{% codepen https://codepen.io/AsyrafHussin/pen/GRjRdqr %}
Ember Table custom sorting indicator
Tags: ember, tailwindcss
Published: 2020-11-27 10:04:54

[EmberTable](https://opensource.addepar.com/ember-table/docs) is a very powerful addon for [EmberJS](https://emberjs.com/) that allows great degree of flexibility.

Since I'm using [tailwindcss](https://tailwindcss.com/) for styling and [FontAwesome](https://github.com/FortAwesome/ember-fontawesome) for icons, I really wanted to be able to make a custom component for _sorting indicator_. 

From [the docs](https://opensource.addepar.com/ember-table/docs/api/components/ember-th/sort-indicator) it was not directly obvious what to do, so I decided to make this little write-up.

## The code

First we need to tell `EmberTable` to use the component we are going to create later on:

```hbs
{{!-- app/application/template.hbs --}} 

<EmberTable as |t| >
  <t.head @columns={{@columns}} as |h| >
    <h.row as |r| >
      <r.cell as |columnValue columnMeta| >
        {{!-- Our new component --}}
        <CustomSorter @columnMeta={{columnMeta}} />

        {{columnValue.name}}
      </r.cell>
    </h.row>
  </t.head>

  <t.body @rows={{rows}} />
</EmberTable>
```

Now to our new component:

```hbs
{{!-- app/components/custom-sorter.hbs --}}

{{#if @columnMeta.isSorted}}
  {{#if @columnMeta.isSortedAsc}}
    <FaIcon @icon="sort-up" class="text-gray-500" />
  {{else}}
    <FaIcon @icon="sort-down" class="text-gray-500" />
  {{/if}}
{{/if}}
```

The output with some additional table styling might look something like this:

![CustomSorter (1)](https://dev-to-uploads.s3.amazonaws.com/i/uuh1wh1ynwlo4xwispqy.gif)
 
### Edits
#### 2021-01-07

Found out that there is a _cough_ not great [code in ember-table](https://github.com/Addepar/ember-table/blob/v2.2.3/addon/-private/column-tree.js#L115-L128) for calculating `sortIndex` that freaks out when you want to consume `isSortedAsc` even though `isSorted===false`. Updated the code here to work even with that.

-----
Image by <a href="https://pixabay.com/users/blickpixel-52945/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=447480">Michael Schwarzenberger</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=447480">Pixabay</a>
❎❓Quiz: Web Performance #27
Tags: challenge, webperf, webdev, quiz
Published: 2020-11-27 09:53:38

Check out the web performance question of the day!

What is the Critical Rendering Path?


- A critical request chain of the website.
- A circular reference in JavaScript files.
- A wrong path to an image.
- A sequence of steps the browser has du complete to display the website.

---
<center>[Answer the question](https://marcradziwill.com/web-performance-quiz/what-is-the-critical-rendering-path/)</center>
---
What times are reasonable to post a technical blog post/ tutorial ?
Tags: discuss, writing
Published: 2020-11-27 09:44:51

I have been wondering for a while now what the most reasonable time is to post either on dev.to or other channels.

Just been wondering this as most people are busy with stuff, so either they could just be browsing and not reading. So just wondering what sort of timeframe people are sitting down to look for something to read.

Or maybe it is an engagement issue from my end 🤷‍♂️ 😅 as it would be great to post at a time, or improve the posts that would encourage feedback on things that can be improved or even are decent points.

Please share your thoughts or experiences on this if you have had the same thing :)

Have a good day too
Exporting a sql database from phpmyadmin and copying it to your local machine when you have lots of foreign key constraints
Tags: phpmyadmin, sql, mysql
Published: 2020-11-27 09:37:54

Export sql file from phpmyadmin

Use the below to set the session foreign key checks to 0 temporarily.

```mysql --init-command="SET SESSION FOREIGN_KEY_CHECKS=0;" -u root -p landstack < landstack.sql```

Then log into your mysql and run the following to set the checks to back on:
```SET FOREIGN_KEY_CHECKS=1;```

Or

You can replace the first command with ```mysql -u root -p landstack < landstack.sql``` and do a custom export for phpmyadmin with the 'Disable Foreign Keys' button selected.

This is necessary otherwise you may receive a foreign key constraint error when importing the database.
Protect Online Images & Documents With Image Protect Software !!
Tags: software, imageprotection, security
Published: 2020-11-27 09:37:46

Copy protecting images is most recommended when livelihoods are at stake. Otherwise art and intellectual property can be stolen, plagiarized and used in unrelated projects. ArtistScope has provided the most effective copy protection and most secure image protection software for more than 20 years. See our online demos at artistscope.com to see just how securely images can be protected !!

More Details : https://bit.ly/36bdr9O
Beginner-friendly python project ideas (with implementation)
Tags: python, codenewbie, beginners, webdev
Published: 2020-11-27 09:33:55

---
title: Beginner-friendly python project ideas (with implementation)
published: true
description: Beginner-friendly python project ideas
tags: python, codenewbie, beginner, webdev  
cover_image: https://analyticsindiamag.com/wp-content/uploads/2020/07/python-logo.png
---

👋 devs, 

I recently came across this [blog](https://www.dataquest.io/blog/python-projects-for-beginners/) with some very good project ideas targeted at beginners. If you feel like a noob in python programming, you can try and build one of these projects. 

Some of the project ideas are - 

* Fun Python projects for **game dev**:
 * Rock, Paper, Scissors 
 * Guessing Game 
 * Hangman 
 * Snake

* Fun Python project ideas for **building data skills**:
 * Find out How Much Money You've Spent on Amazon
 * Analyze Survey Data 

* Fun Python projects for beginner **web devs**:
 * URL shortener
 * Build a Simple Web Page with Django 

* Fun Python projects for aspiring **app developers**:
 * Password generator
 * Use Tweepy to create a Twitter bot
 * Create a Crypto App with Python

All the code is included, just try to read through it and follow the explanations to understand the code. There will definitely be few new keywords which you have not seen before which you can look up and learn them on the go.

Once you understand the code, try to implement it yourself on your machine. You can also add them to your GitHub account and show them here on dev.

When you learn more things, you can re-visit these projects and improve them and/or add new features to them.

Thanks for reading! If you found this useful, you can also checkout python projects at [DevProjects](https://www.codementor.io/python-projects), where you can improve your programming skills by working on real-world projects.

P.S. I am not affiliated with Dataquest or CodeMentor in any way. :)
Boost Angular’s performance by Lazy Loading your Modules 🚀
Tags: angular, typescript, javascript, es6
Published: 2020-11-27 09:22:28

Building a large scale application involves meticulous details that should not be ignored. These applications usually contain a large number of feature modules. However, all these feature modules are not required to be loaded all at once.

Loading only the necessary modules at the initial load not only reduces the bundle size but also decreases load time. This design pattern is called lazy loading, and, as said, it loads the app modules only when it is necessary. Ideally, for an application to be successful, the initial load time should be short. For that, it is recommended to lazy load the components that are not necessary at first.

#### 1. Generate some new modules inside your /app:
```javascript
ng g m home --routing
ng g m auth --routing
```
#### 2. Generate root components for your modules inside newly created modules directories /homepage, /auth:
```javascript
ng g c home // (inside homepage newly created module)
ng g c auth // (inside auth newly created module)
```
#### 3. take out component files from components directory to root of the module directory, so that your module directory will look like this:
![module directory](https://i.ibb.co/xCcBf2S/Untitled.png)

#### 4. update you path in "homepage.module.ts" file
```javascript
// from
import { HomeComponent } from './home/home.component';
// to
import { HomeComponent } from './home.component';
```
#### 5. Add initial route of your module so that the redirection call of your module with directed to the root component of your module:
```javascript
// home-routing.module.ts
import { HomeComponent } from './home.component';

const routes: Routes = [
  { 
    path: '', 
    component: HomeComponent
  }
];
```
👉 Note: repeat steps 4, 5 for the **auth module** as well.
#### 6. Now add the lazy-loaded route of your module inside the app module:
```javascript
// app-routing.module.ts
const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./pages/home/home.module').then((m) => m.HomeModule)
  },
  {
    path: 'home',
    loadChildren: () => import('./pages/home/home.module').then((m) => m.HomeModule)
  },
  {
    path: 'auth',
    loadChildren: () => import('./pages/auth/auth.module').then((m) => m.AuthModule)
  },
];
```

## That's it, now run your app in the browser and see the difference in your network tab of dev tools 😃

💻 Source Code: {% github https://github.com/muhammadawaisshaikh/angular-lazy-loading %}
JavaScript Code Daily Challenge #7
Tags: javascript, challenge, codenewbie, beginners
Published: 2020-11-27 09:12:15

# **About**

This is a series of JavaScript Code Daily Challenge. Each day I show a few solutions written in JavaScript. The questions are from coding practice/contest sites such as HackerRank, LeetCode, Codeforces, Atcoder and etc.

> Let and Const
> [https://www.hackerrank.com/challenges/js10-let-and-const/problem](https://www.hackerrank.com/challenges/js10-let-and-const/problem)
```javascript
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    
    main();    
});

function readLine() {
    return inputString[currentLine++];
}
```
> Complete the 'main' function in comment.
> Print area and perimeter of the circle
```javascript
function main() {



    try {    
        PI = 0;
        console.log(PI);
    } catch(error) {
        console.error("You correctly declared 'PI' as a constant.");
    }
}
```
Merging images/PDF to create a new wholesome PDF file
Tags: pdf, imagemagick, poppler
Published: 2020-11-27 02:28:07

I came across that I have to fix a lot of images, and sometimes multiple of PDF files each has only one page.

Tools here are in Ubuntu Linux; in Windows, it should be accessible via WSL; not sure about macOS.

```sh
sudo apt install imagemagick poppler-utils
```

Then you now have two important commands - `convert` and `pdfunite`.

Now, I have another important problem - [ImageMagick security policy 'PDF' blocking conversion
](https://stackoverflow.com/questions/52998331/imagemagick-security-policy-pdf-blocking-conversion)

Though, my solution is

```sh
sudo nano /etc/ImageMagick-6/policy.xml
```

To issue commands, for some reasons, `convert` supports wildcards, but not `pdfunite`.

```sh
convert "$FOLDER_NAME/*.GIF" "$FOLDER_NAME.pdf"
pdfunite x/x1.pdf x/x2.pdf x/x3.pdf x.pdf
```

Lastly, this post is possible because of

```sh
code ~/.zsh_history
```
Alternatives to commerical software
Tags: code, codenewbie, software
Published: 2020-11-27 09:08:53

When looking for different websites or different software productions the search engine will in most cases deliver the same results. For example : How to crop an image in Photoshop.

But since not all of us can afford all the commercial software alternatives are always welcome.

A site that is dedicated to finding alternatives for software is described in the below 2 min video.

https://www.youtube.com/watch?v=fxl9Kx1XMrw&feature=youtu.be