teleren/devto huggingface dataset:
Crosspost to DEV community with Typemill
Tags: showdev, webdev, markdown, api
Published: 2020-05-07 07:29:04

This article was originally published on [trendschau.net](https://trendschau.net/blog/crosspost-dev-community-typemill), but you will probably read it on [dev.to](https://dev.to) first. How come?

Some weeks ago a dev-user asked other members how they [crosspost their markdown articles](https://dev.to/rimutaka/dev-to-writers-what-md-tools-do-you-use-1pad) to the dev-platform. Since I develop a small flat-file cms called [Typemill](https://typemill.net) that works with markdown, I asked myself if it is worth to create a little plugin for such crossposts. I checked the [dev-API](https://docs.dev.to/api/), wrote about 200 lines of code and voila: The first crosspost is online.

 This is a screenshot of the Typemill admin-ui for this article:

![Screenshot of crosspost-tab in Typemill](https://trendschau.net/media/live/crosspost-dev.png)

The plugin adds a new tab called "dev.to" to each article and in that tab you can manage the crosspost. You can activate the crosspost, you can choose between draft or publish and you can add tags or series. The plugin will synchronise the articles (and rewrite the image-urls) whenever you publish or update the article on Typemill. It will also store and display the response from dev.to and display a little preview.

It is pretty simple to create a plugin like this with Typemill:

* All you need is a YAML-file, a small vue-component and a php-file with some logic.
* With the YAML-file you can define the forms and fields for your tab.
* With the vue-component you can render the tab and also add the vue-logic that you want.
* With the php-file you can listen to the typemill-events (I wrote about the [event-dispatcher here](https://dev.to/trendschau/how-i-created-my-first-plugin-system--400)) and make the api calls.

Typemill is open source. Don't expect a high level system or a super robust and bug-free software: It is still a side project with a small community and we work hard to improve it with each release. If you have a close look to the [GitHub repository](https://github.com/typemill/typemill): 8 more stars and we have 100 !!!
JavaScript's const keyword
Tags: javascript
Published: 2020-05-07 07:24:17

<sub><sup>Photo by Martin Adams on Unsplash.</sub></sup>

JavaScript's introduction of the const keyword in ES6 is amazing but has some hidden passages that you may not be aware of.

### The `const` keyword

`const` is used to create block-scoped variables that provide a read-only reference to a value.

```js
const name = "John";
name = "Ringo"; 
console.log(name); // John
```

We can see here how we've declared a constant variable called `name` with the value of "John". If we try to reassign that value to "Ringo", the application will throw an error and inform us that the `name` variable is read-only.

### `const` and Objects

Like mentioned above, the `const` keyword will create a read-only variable, however, that does not mean that the actual variable reference is immutable.

```js
const beatle = {
    name: "John",
    surname: "Lennon"
}

beatle.name = "Ringo";
console.log(beatle.name); // Ringo
```

We were able to reassign the property on the constant because we haven't attempted to change the variable's reference but rather the value on a property in that reference. `const` only allows us to not reassign the reference.


### `const` and Arrays

```js
const beatles = ['John', 'Paul', 'George'];
beatles.push('Ringo');
console.log(beatles); // ["John", "Paul", "George", "Ringo"]

beatles.pop();
beatles.pop();
console.log(beatles); // ["John", "Paul"]

beatles = ["Noel", "Liam"]; // TypeError
```

Once again we can see how we can manipulate a `const` variable array by adding and remove elements, however, as soon as we attempt to reassign the variable to a new array an error is thrown.

### Constants and Enums

So if we have a `const` keyword that doesn't allow reassignment to a new reference but still allows you to reassign a property, how could we make that not possible at all for the use case of constants or enumerators?

The answer to that is `Object.freeze()`. This method will "freeze" an object which means that the object can no longer be changed, properties cannot be added and properties cannot be removed. It even prevents the prototype being changed.

```js
const beatle = Object.freeze({
    name: "John",
    surname: "Lennon"
});

beatle.name = "Ringo";
console.log(beatle.name); // John
```

`Object.freeze()` allows us to create constants and enums with the guarantee that the values won't be changed in anyway.

**Note:** Nested objects within a frozen objects need to be frozen as well. Freezing an object only freezes the parent object.

### When to use `const`

`const` should be used when you're wanting to create a block-scoped variable where you know that the value isn't going to change.

```js
// INCORRECT
const beatles = ['John', 'Paul', 'George', 'Ringo'];

for (const i = 0; i < beatles.length; i++) { // TypeError as you're reassigning i
    console.log(beatles[i]);
}

// CORRECT
const beatles = ['John', 'Paul', 'George', 'Ringo'];

for (const member of beatles) {
    console.log(member);
}
```
Electron で gRPC を動かす
Tags: electron, grpc
Published: 2020-05-07 05:46:23

Electron で gRPC を動かしたときのメモです。

- Electron のバージョンは 8.2.5
- Node.js のバージョンは 13.13
- npm のバージョンは 6.14.4

思ってる以上にサクッと動きます。

## インストール

```
yarn add electron electron-rebuild grpc @grpc/proto-loader --dev 
```

## 再ビルドする

gRPC を使うには再ビルドが必要ですが、 electron-rebuild という便利ツールでサクッとできます。

[electron/electron\-rebuild: Package to rebuild native Node\.js modules against the currently installed Electron version](https://github.com/electron/electron-rebuild)

```
./node_modules/.bin/electron-rebuild
```

## 以下動かしたときの主なコード

### echo.proto

```proto
syntax = "proto3";

package echo;

option go_package = ".;echo";

message EchoRequest {
    string message = 1;
}

message EchoReply {
    string message = 1;
}

service Echo {
    rpc Echo(EchoRequest) returns (EchoReply) {}
}
```

### main.js

```javascript
const { app, BrowserWindow } = require("electron");
const path = require("path");

const grpc = require("grpc");
const protoLoader = require("@grpc/proto-loader");

const PROTO_PATH = __dirname + "/echo.proto";

const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
});

const echoProto = grpc.loadPackageDefinition(packageDefinition);

let client = new echoProto.echo.Echo(
  "127.0.0.1:50051",
  grpc.credentials.createInsecure()
);

client.Echo({ message: "hello!!" }, function (error, response) {
  if (!error) {
    console.log(response.message);
  } else {
    console.error(error);
  }
});

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  });

  mainWindow.loadFile("index.html");

  mainWindow.webContents.openDevTools();
}

app.whenReady().then(createWindow);

app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

app.on("activate", function () {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
```
Stretches and Exercises to Relieve Upper, Mid and Lower Back Pain
Tags: watercooler, tips, health, wellness
Published: 2020-05-07 05:08:50

> Originally posted on my [blog](https://emtr0.dev/stretches-exercises-relieve-upper-mid-lower-back-pain/).

I occasionally get back pain for various reasons but for some reason, today it was really bugging me. It was semi-painful and I know it's because I slacked off on being mindful about my posture throughout the day while at the computer. When I got home, I did a bunch of searching for some good stretches to relieve my back pain. I found quite a few but narrowed it down to a list I felt many of you would also benefit from. 

Most of these stretching and exercise "guides" include the same types of stretches but each of them has their own way of presenting them (photos, videos, etc). The stretches (and yoga poses) that really helped me were the cat-cow pose, seated twist, cobra pose and child's pose. By the end of my stretching session, I was just alternating between the child's pose and cobra pose. I felt a lot better after.

As I said before, the following websites include different photos, videos, explanations, and additional resources related to stretching, exercising and wellness, one of which you might find more relevant to your needs for whatever reason.

[Try These Stretches to Relieve Upper Back Pain](https://www.menshealth.com/fitness/a25616194/upper-back-stretches/)

[Programmer Posture Exercises – Three Stretches for Beginners](https://www.minddevelopmentanddesign.com/blog/three-easy-exercises-help-programmers-posture/)

[5 Stretches to Release and Relieve Your Mid Back](https://www.healthline.com/health/fitness-exercise/mid-back-stretches)

[7 Lower Back Stretches to Reduce Pain and Build Strength](https://www.healthline.com/health/lower-back-stretches)

[4 Stretches for the Middle Back](https://www.source1therapy.com/blog/4-stretches-for-the-middle-back)

[5 Best Back Pain Stretches For Immediate Back Pain Relief](https://blog.daveasprey.com/best-back-pain-stretches-pain-relief/)

[10 Best Stretches to Ease Your Lower Back Pain, According to Trainers](https://www.prevention.com/fitness/a20506161/5-stretches-to-ease-your-lower-back-pain/)

[Exercise and Back Pain](https://www.spine-health.com/wellness/exercise/exercise-and-back-pain)

And finally, here's a [mindful stretching guide PDF](https://uhs.berkeley.edu/sites/default/files/wellness-mindfulstretchingguide.pdf) from Berkeley.

I hope you found these resources helpful especially since like me, I'm sure many of you spend a lot of time seated in front of a computer. Maybe I'll invest in one of those adjustable standing desks one day.

Let me know which stretch/exercise helped relieve your back pain. :)
3.2. Compile and run your Java program
Tags: java, beginners, devops, programming
Published: 2020-05-07 05:05:08

Open a shell for command line access.

If you don’t know how to do this, google for "How to open a shell under [your_OS]".
Switch to the javadir directory with the command cd javadir, for example, in the above example via the cd \home\vogella\javastarter command. Use the ls command (dir under Microsoft Windows) to verify that the source file is in the directory.

Compile your Java source file into a class file with the following command.

javac HelloWorld.java
Afterwards list again the content of the directory with the ls or dir command. The directory contains now a file HelloWorld.class. If you see this file, you have successfully compiled your first Java source code into bytecode.

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag.
You can now start your compiled Java program. Ensure that you are still in the jardir directory and enter the following command to start your Java program.

java HelloWorld
The system should write "Hello World" on the command line.

Compiling and running Java programs on the command line
3.3. Using the classpath
You can use the classpath to run the program from another place in your directory.

Switch to the command line, e.g., under Windows Start  Run cmd. Switch to any directory you want. Type:

java HelloWorld
If you are not in the directory in which the compiled class is stored, then the system will show an error message: Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass

To use the class, type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.

java -classpath "mydirectory" HelloWorld
Mental Models: Array Indexing
Tags: programming, javascript, dev, beginners
Published: 2020-05-07 05:00:08

---
title: Mental Models: Array Indexing
published: true
description: Forming a mental model around arrays
tags: [programming,javascript,dev,beginner]
---

Having arrays start at index zero is somewhat confusing at first. Naturally we start counting things from one. We see zero as representing nothing.

The confusion comes from thinking of the index as an ordinal number. An ordinal number defines the position of something in a series i.e. `first`, `second`, `third` e.t.c. This logically means we can't have an item occupying position zero in a series. If we think of the index as an ordinal number, the first element would be at `e[1]`.

Your thinking should shift from thinking of index as an ordinal number. You should be thinking of the index as an offset from a starting point. From this thinking the first element would be a distance of zero from the beginning, hence `e[0]`.
Builder: design pattern
Tags: design, codequality, typescript
Published: 2020-05-07 04:59:28

สวัสดีครับ Devs ถ้าเรื่อง code quality สำคัญสำหรับคุณ เราคือเพื่อนกัน

Devs เรา code กันมา เราน่าจะเคยเห็น class ที่การจะสร้าง instance ของพี่เขาเนี่ย
require parameters เยอะ หรือบาง instance ต้องการการ set runtime config ค่าบางอย่างเพื่อให้เขาทำงานได้ถูกต้อง ดังตัวอย่างง่ายๆ ดังนี้

ClassGenerator มีหน้าที่ gen code ออกมาเป็น string ธรรมดา
ตาม config ที่มีให้อย่างในภาพด้านล่าง

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

จากภาพสังเกตุว่าใน function generate จะมีส่วนที่มีปัญหานิดหน่อย 

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

ตรงนี้
ถ้าเกิดเรา config parentClass แต่ไม่กำหนด isExtends เป็น true
code ที่ gen ออกมาก็จะไม่ มีสวน extends parent class ให้
ซึ่งมันไม่ใช่ expected behavior

ซึ่งสิ่งที่อาจเป็นปัญหาคร่าวๆ คือ 
1. Devs คนอื่นๆ หรือ ตัวเราเอง ที่ใช้ object นี้ต่ออาจลืม setter บางตัวได้
2. จากข้อบน อาจทำให้เกิด unexpected behavior ได้

ทีนี้ Builder pattern จะมาช่วยเราอย่างไรบ้าง
โดยตาม theory บอกว่า 

- builder ทำให้การสร้าง หรือ config object ที่มีความ complex ให้ง่ายขึ้น
- builder นั้นเป็นอิสระจาก object อื่นๆด้วยครับ

Welcome Builder class

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

สังเกตุว่า class Builder นี้ใน function parentClass
ผมกำหนดให้ไปเลยว่า ถ้ามีการ set parent class เข้ามา 
isExtends ต้องเป็น true เลย ซึ่งก็จะลดความซับซ้อน ไปได้ครับ

ซึ่งวิธีการเรียกใช้เป็นแบบนี้

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

code เราที่เขียน เพื่อนมาดูต่อก็ จะรู้สึก มีอารยธรรมครับผม

ทีนี้ด้วยความเป็นคนจุกจิก ไม่พอใจอะไรง่ายๆ ครับ ฮ่าๆ
แล้วมันทำได้ดีกว่านี้อีกไหม ?
คำตอบคือได้ครับ 

ขอแนะนำให้รู้จักสิ่งที่เรียกว่า Fluent Builder pattern
ซึ่งเขาก็คือ builder แหละ แต่เป็น style ที่สวยขึ้น useful มากกว่า
โดยเราจะ implement ได้ดังนี้

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

ซึ่งสิ่งที่เราเพิ่มเติมขึ้น เราให้ class builder นี้ return ตัวเขาเองออกมาทุกครั้ง
เพื่อให้เราสามารถ ทำ chain configuration ได้ เพื่อให้เราเรียกใช้ แบบนี้ได้ครับ

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

เป็นงัยบ้างครับ สำหรับ Builder pattern
ทีนี้เรารู้จักการเขียนแบบนี้ Team เรา หรือเราจาก อนาคต
จะรู้สึกว่าได้ร่วมงานกับ คนที่มีอารธรรมที่สูงส่งกว่าครับ

หวังว่าเพื่อนๆ Devs จะลองเอาไป implement กันดูนะครับ
9 Tricks To Write Less JavaScript.
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-05-07 04:48:17

Hi Dev 👋, Thanks for opening my blog. I hope you are doing well and ready to learn some **Tricks To Write Less JavaScript** 😎.

So, let's start!

*1. Declaring Variables*

```javascript
//Longhand
let x;
let y;
let z = "post";

//Shorthand
let x, y, z = "post";
```

*2. Assignment Operator*

```javascript
//Longhand
x = x + y;
x = x - y;

//Shorthand
x += y;
x -= y;
```

*3. Ternary Operator*

```javascript
let answer, num = 15;

//Longhand
if (num > 10) {
  answer = "greater than 10";
} 
else {
  answer = "less than 10";
}

//Shorthand
const answer = num > 10 ? "greater than 10" : "less than 10";
```

*4. Short for Loop*

```javascript
const languages = ["html", "css", "js"];

//Longhand
for (let i = 0; i < languages.length; i++) {
  const language = languages[i];
  console.log(language);
}

//Shorthand
for (let language of languages) console.log(language);
```

*5. Template Literals*

```javascript
const name = "Dev";
const timeOfDay = "afternoon";

//Longhand
const greeting = "Hello " + name + ", I wish you a good " + timeOfDay + "!";

//Shorthand
const greeting = `Hello ${name}, I wish you a good ${timeOfDay}!`;
```

*6. Arrow Function*

```javascript
//Longhand
function sayHello(name) {
  console.log("Hello", name);
}

list.forEach(function (item) {
  console.log(item);
});

//Shorthand
sayHello = name => console.log("Hello", name);

list.forEach(item => console.log(item));
```

*7. Object Array Notation*

```javascript
//Longhand
let arr = new Array();
arr[0] = "html";
arr[1] = "css";
arr[2] = "js";

//Shorthand
let arr = ["html", "css", "js"];
```

*8. Object Destructuring*

```javascript
const post = {
  data: {
    id: 1,
    title: "9 trick to write less Javascript",
    text: "Hello World!",
    author: "Shoaib Sayyed",
  },
};

//Longhand
const id = post.data.id;
const title = post.data.title;
const text = post.data.text;
const author = post.data.author;

//Shorthand
const { id, title, text, author } = post.data;
```

*9. Object with identical Keys and Values*

```javascript
//Longhand
const userDetails = {
  name: name, // 'name' key = 'name' variable
  email: email,
  age: age,
  location: location,
};

//Shorthand
const userDetails = { name, email, age, location };
```

That's It 😎.

Thanks for reading! My name is Shoaib Sayyed; I love helping people to learn new skills 😊. You can follow me, if you’d like to be notified about new articles and resources.
Build pagination with ES6 async generators and iterables
Tags: javascript, react, beginners, reactnative
Published: 2020-05-07 04:20:17

---
title: Build pagination with ES6 async generators and iterables
published: true
description: Building a simple pagination using the coolest of ES6 features!
tags: #javascript, #react, #beginners, #reactnative
cover_image: https://techcrunch.com/wp-content/uploads/2015/08/safe_image.gif
---

## What the :tropical_fish: is a generator?

Well, according to the definition :

> Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.



## Fancy, what does this bring to the table? :thought_balloon:

argh, definition again..  :zzz:

> Generators in JavaScript -- especially when combined with Promises -- are a very powerful tool for asynchronous programming



## A real world scenario? 

After all that definition reading, let's jump into the core of it. :octocat:

We had an interesting problem on our hands to tackle. It was to enable pagination to one of our mobile app's on swipe right.



### So we use generators for it?

There are other possible solutions, generators are just a cleaner solution.



### How to do it?


> Create a generator 

```javascript
const asyncGetContent = async function* (){
  const limit = 10; /* content per page */
  let offset = 0; /* index of item to start from */
  let totalCount = -1; /* -1 signifies failure */
  while (offset === 0 || offset < totalCount) {
    try {
      const response = await (await fetch(<<url>>)).json();
      offset = offset + limit;
      totalCount = response["total-count"];
      console.log(`offset + totalCount`, offset, totalCount);
      yield response;
    } catch (e) {
      console.warn(`exception during fetch`, e);
      yield {
        done: true,
        value: "error"
      };
    }
  }

}
```

That's a lot to understand, let's go through each line.


:snowman: we've `limit` which defines a variable to set the limit on the results of your choice [need not be a constant]

:snowman: prepare a fetch/ axios/ some API call, shoot it with an `await` such that we will resolve the resulting promise.

:snowman: `yield` the response. The return will be a promise to be consumed by the async caller using `.next()`(we'll get to that in the next section)


:snowman: let's just handle fetch

---


> How do i use this?

All that's left to do is to initiate and call it within an async function as such:

```javascript
const contentGen = await asyncGetContent(); /* initate the generator */
```

after initiation, we can call wherever required (ex: right swipe / click of a button) to yield the result

```javascript
const content = await contentGen.next();
```
use `content` [the response from the api in this case] as necessary

If you have questions, let us know in the comments and we are looking forward for your feedback 🍻
JavaScript tips and tricks to be a better developer
Tags: javascript, angular, typescript
Published: 2020-05-07 03:59:35

These are some of the very basic Javascript methods that will help you get better in Javascript.
Let's straightly jump into coding.. :boom:

## Fill array with data

```js
var myArray = new Array(10).fill('A');
console.log(myArray); 

//Output
[ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A' ] 
```

## Merge Arrays

```js
var bikes = ['TVS', 'BMW', 'Ducati'];
var cars = ['Mercedes', 'Ford', 'Porsche'];
var autoMobiles = [...bikes, ...cars];
console.log(autoMobiles);

//Output
[ 'TVS', 'BMW', 'Ducati', 'Mercedes', 'Ford', 'Porsche' ] 
```

## Intersection of arrays

```js
var setA = [5, 10, 4, 7, 1, 3];
var setB = [3, 11, 1, 10, 2, 6];
var duplicatedValues = [...new Set(setA)].filter(x => setB.includes(x));
console.log(duplicatedValues);

//Output
[ 10, 1, 3 ]
```

## Remove falsy values

```js
var mixedArray = [12, 'web development', '', NaN, undefined, 0, true, false];
var whatIsTrue = mixedArray.filter(Boolean);
console.log(whatIsTrue); 

//Output
[ 12, 'web development', true ] 
```

## Get random value

```js
var numbers = [];
for (let i = 0; i < 10; i++) {
    numbers.push(i);
}

var random = numbers[Math.floor(Math.random() * numbers.length)];
console.log(random); 

//Output
 4
```

## Reverse an Array

```js
var reversedArray = numbers.reverse();
console.log(reversedArray);

//Output
[ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] 
```

## Sum of all values in array

```js
var sumOfAllNumbers = numbers.reduce((x, y) => x + y);
console.log(sumOfAllNumbers);

//Output
45
```

## Remove duplicates from array

```js
var duplicatedArray = ['hello','hello','web developers']
var nonDuplicatedArray = [...new Set(duplicatedArray)];
console.log(nonDuplicatedArray); 

//Output
[ 'hello', 'web developers' ] 
```

Thanks for reading. I hope this gave you an some insights about the JavaScript array methods. Keep following and Stay tuned for more amazing blogs.
Prioritize declarative
Tags: orclapex
Published: 2020-05-07 03:47:57

>When logic is less discoverable it is easier to overlook and become a source of defects.

One beautiful thing about APEX is that everything resides in this relational container. Used correctly everything can be found easily. You can determine all your dependencies and make changes without the risk of not knowing what you missed.

When you look at the builder and the various ways it can be laid out, consider that you can create your own special view of that same data .. as long as you treat it as data. When I open a new application I love that I can easily reason about the easy parts, like how does a page render, what does it render? 

When several Conditions apply to the execution of some code it may be better to create multiple Processes, one for each Condition, than to put the Conditions inside the Process code itself. It can be tempting to put them all in one Process so you have them all in one place. But APEX is “one place” too and you can organize your code inside multiple Processes and achieve something that reads like a boxes and arrows diagram. Add in some verbose naming and the reader can understand what these processes do without digging into code.

Instead of declaring local variables inside an anonymous PL/SQL block, create page items and compute them. It might seem like overkill to do this but then when you need to debug this you get session state and logging for free.