teleren/devto huggingface dataset:
IoT Edge module twin reported properties C# 
 
Tags: iotedge, azure, iot
Published: 2020-01-28 02:01:49

 This is a small guide that builds on top of existing IoT edge C# sample. You might have across [IoT Edge C# sample](https://docs.microsoft.com/en-us/azure/iot-edge/tutorial-csharp-module).  The IoT Edge module that you create in that tutorial filters the temperature data that's generated by your device. It only sends messages upstream if the temperature is above a specified threshold. This type of analysis at the edge is useful for reducing the amount of data that's communicated to and stored in the cloud. :smiley:

You can control/change the temperature from the cloud using module twins. Module twin's desired and reported properties are used to synchronize module configuration or conditions. Check [this](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-module-twins) out to understand how to use module twins for IoT Hub.

The function **OnDesiredPropertiesUpdate()** from the sample is invoked when there is a change to the desired properties, however, it does not update the reported properties.

To update the reported properties we will make a few changes to the sample.

Declare **ioTHubModuleClient** as a global variable to the Program class. 

       // Declare ModuleClient 
       private static ModuleClient ioTHubModuleClient = null;

Find the **Init** function. This function creates and configures a **ModuleClient** object, which allows the module to connect to the local Azure IoT Edge runtime to send and receive messages. Make the following changes: 


       // Open a connection to the Edge runtime
            ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
            await ioTHubModuleClient.OpenAsync();
            Console.WriteLine("IoT Hub module client initialized.");


Navigate to **onDesiredPropertiesUpdate** method to the Program class and make the following changes to try-catch: 

            try
            {
                Console.WriteLine("Desired property change:");
                Console.WriteLine(JsonConvert.SerializeObject(desiredProperties));
                
                var reportedProperties = new TwinCollection();

                if (desiredProperties["TemperatureThreshold"]!=null) {

                    temperatureThreshold = desiredProperties["TemperatureThreshold"];
                    reportedProperties["TemperatureThreshold"] = temperatureThreshold;
                }

                if (reportedProperties.Count > 0)
                {
                    ioTHubModuleClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false);
                }

            }

Here we use [ModuleClient.UpdateReportedPropertiesAsync Method](https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.devices.client.moduleclient.updatereportedpropertiesasync?view=azure-dotnet) to update the repoted properties.
Turn your URL into Short Link using Netlify Redirects
Tags: redirects, netlify, tutorial, github
Published: 2020-01-28 01:41:42

I don't like those short links URL, why?
Bitly, Tinycc, Cutly URL Shortner

Because i want to have my own domain name with it.
You should buy a short domain name or 2 words domain name.
Mine is fajarsiddiq.com and so i start using netlify redirects.
Is very useful, i use this to share like a short links with my domain.
I use this to put on my youtube description links of my playlist videos.
So to learn how to make this, you follow this simple steps below.


✅1. Create a plain text file on your github
✅2. Create the syntax "/coffee" "https://buymeacoffee.com/fajarsiddiq" 
✅3. Deploy on netlify, done! 
👉 For reference, read this doc for full guideline:
https://docs.netlify.com/routing/redirects/#syntax-for-the-redirects-file
👉 Share this Redirects Tutorial Video:
https://fajarsiddiq.com/redirects
👉Why i don't use short link websites
https://twitter.com/fajarsiddiqFS/status/1222455656822652928
I feel safe with my Bookmarks on Chrome 
Published: 2020-01-28 01:35:41

---
title: I feel safe with my Bookmarks on Chrome 
published: true
description: 
tags: 
---

Last year I started using my bookmarks on google chrome more often and in an organized way.
The bookmarks on google turns to a vital part of my daily life. As a developer big part of my day pass by sitting in front of a computer, this is the reason most things on my routine are by my computer. For a long time I had problems forgetting passwords and important links.
Therefore, I decided organizing my day using the bookmarks on my google account and from that day, I got one more way to help my brain remember important things.
The possibilities are interesting for who are in love with organization or are just a forgetful person.
To create a bookmark is simple. You first need to create an account on google or login to one you already have. When it is done access a website where you want to add on your bookmarks. Click on the star to bookmark the page.
![](https://thepracticaldev.s3.amazonaws.com/i/o2zzod3he372k0sjzwu0.png)
After click on the star will appear a tab asking if you want to edit the dame of the bookmark and choose the folder where it goes.
![](https://thepracticaldev.s3.amazonaws.com/i/h0rvjtq8ftpaf7ljsxnp.png)
If you want to add the link into a new folder you only need do click on choose another folder and after that click on new New Folder and then Save.
![](https://thepracticaldev.s3.amazonaws.com/i/37uul9xxe584q2ol15ck.png)
![](https://thepracticaldev.s3.amazonaws.com/i/gf3zjn07nzgadslm71c6.png)
![](https://thepracticaldev.s3.amazonaws.com/i/7toyx2nfa08qjwz4efu5.png)
![](https://thepracticaldev.s3.amazonaws.com/i/spgv67e6wodhkdl70ivu.png)
If you need to migrate your bookmarks to a new computer it simple and just need to login into your same google account that you used before, access Setting and click on the option that says “Import bookmarks and settings”. Thereby you feel at home in any other computer.
Other possibility is that you can have two users login into chrome.
For example, by this way you are able to organize bookmarks for your personal account and for your professional account at the same time.
Simple linear regression (SLR) - simplified
Tags: machinelearning, datascience, linearregression, simplelinearregression
Published: 2020-01-28 00:58:35



Most of learning materials on machine learning are overly complex and use too much math from start in my opinion. In this post, I will try to simply explain what simple linear regression is. This will require few mathematical terms, but I will keep it as just one simple formula. Mathematical details behind it, I will explain in some other post. So, lets first start with definition.

Definition: Linear regression is model in which we assume linear relationship between input variables and output. 

Unless you at least took some college level linear algebra, that definition might be confusing. So, let’s try to simplify it. And lets use simple linear regression for that.

In simple linear regression we are predicting value based on one input, for example, price of house based on size. Because it is linear regression, we are expecting to get following equation which we could use for our prediction:

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

In this equation y would be price we are trying to predict, x would be size of house we are using as input value, and A and B are coefficients which define our model. There is mathematical process to define values for those coefficients and there are libraries that do that for us, but once again, that is not goal of this post, and will be explained in next one.

Now, for the reason why it is called linear regression. If we would generate chart visualizing this function, we would get straight line like in the chart below.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n0yc41a6o7bdwlxhlgit.PNG)
 
In the chart above, orange points are actual values, while blue ones are predicted ones. As we can see, some are better fitting than others, but that is fine. We are trying to get model that would fit our data best, but not perfect. If we would try to fit every point, function would be much more complex than this, not a straight line, and it would perform poorly on new and unseen data.

Question is what line would describe it best. There actually is definition for that. For every value of training data that we used to generate model, we sum differences of predicted and actual values. Function where this sum is smallest, is one that gives best model.

Hopefully, this gives simple view of what simple linear regression is. It is simple model that can be used wherever data could be approximated with a line.  In next post I will explain how to use python and different libraries to make predictions and mathematical background behind generating models.
Intro to GraphQL With Apollo Server
Tags: beginners, graphql, tutorial
Published: 2020-01-28 00:46:49

This is a basic introduction to GraphQL with Apollo Server, originally posted on my Youtube Channel.

Please show some love and subscribe to my channel [Subscribe](https://www.youtube.com/channel/UCBRX8VfhAp7FJ_13uzpI_pQ?sub_confirmation=1).
[pt-BR] ES2020: Nullish coalescing operator (??)
Tags: javascript, es2020
Published: 2020-01-28 00:39:31

O [operador de coalescência nula (`??`)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) é um operador lógico que retorna o operando do lado direito caso o valor do operando do lado esquerdo seja `null` ou `undefined`. Caso contrário, retorna o operando do lando esquerdo.

Diferente do [operador lógico OR (`||`)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_2), o operando do lado esquerdo é retornado caso seja um valor [falsy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description) que não seja `null` ou `undefined`.

## Atribuindo valor padrão à uma variável

Antes, quando você queria atribuir um valor padrão à uma variável, era comum se deparar com algum código como esse:

```javascript
let foo = 0;

...

const defaultNumber = 42;
console.log(output || defaultNumber); // expected output: 42
```

O problema com essa abordagem é que caso você considere zero (`0`) ou uma string vazia (`''`) como válidos, você terminaria com um comportamento indesejado aqui.

Utilizando o operador de coalescência nula, a história muda.

```javascript
let foo = 0;
let bar;

...
const defaultNumber = 42;

console.log(foo ?? defaultNumber); // expected output: 0
console.log(bar ?? defaultNumber); // expected output: 42
```

## Encadeando com os operadores OR (`||`) e AND (`&&`)

O operador `??` não pode ser encadeado diretamente com os operadores `||` e `&&`. Caso isso aconteça, você vai terminar com um `SyntaxError` sendo lançado:

```javascript
null || undefined ?? 'default'; // lança um SyntaxError
```

Para corrigir isso você deve envolver a expressão em parênteses para explicitamente indicar a precedência:

```javascript
(null || undefined) ?? 'default'; // 'default'
```

## Relação com o operador de encadeamento opcional (`?.`)

O operador `??` trata os especificamente os valores `null` e `undefined`, assim como o [operador de encadeamento opcional (`?.`)](https://dev.to/mesaquen/pt-br-es2020-optional-chaining-operator-4i3f), que é usado para acessar propriedades de um objeto que podem ser `null` ou `undefined`.
How I got the Github username of my dreams
Tags: github, switch, username
Published: 2020-01-28 00:35:24

**TL;DR:** If the user with the username you want **is inactive**, report it to Github on his profile. It's part of their [name squatting policy](https://help.github.com/articles/name-squatting-policy), and you'll probably receive feedback.

It's been a long time since I've wanted to change my Github username, and I had the perfect candidate: 5 letters, exactly my nickname, and easy to say it (well, at least in portuguese...). But, unfortunately, _it was already taken._

After reading about Github policies, I found [this one](https://help.github.com/articles/name-squatting-policy) telling that my long-desired username _might be possible_ to get, since the user that had it previously **was not active** and his displayed e-mail address didn't exist (as I tried to contact him).

So, with a bit of hope, I've **reported him** explaining that the user was not active (didn't have any repositories nor activity in the last 5 years). One day later, I received this:

![Github Support responded positive to my solicitation](https://i.imgur.com/eAm4sTA.png)

Instantly I've made the switch! I was already aware of the [downsides](https://help.github.com/en/enterprise/2.13/user/articles/what-happens-when-i-change-my-username) (gists and mentions to you are not updated), but I've decided that it was worth it.

## And, now, you can reach me on [@lucis](https://github.com/lucis)
[pt-BR] ES2020: Optional chaining operator
Tags: javascript, es2020, optionalchaining
Published: 2020-01-28 00:34:49

Muitas novidades são esperadas com a chegada do ES2020. Uma delas que veio para simplificar a vida e diminuir a quantidade de código que temos que escrever é o [operador de encadeamento opcional][optional chaining operator] `?.` - Optional chaining em inglês.

O funcionamento dele é similar ao do operador de encadeamento `.`, exceto que ao invés de causar um erro ao tentar acessar uma propriedade de uma referência vazia (`null` ou `undefined`), a expressão irá retornar undefined.

Isso pode ser muito util ao explorar conteúdo de um objeto onde não se tem garantia de que as propriedades são obrigatórias.

## Exemplo

```javascript
const player = {
  name: 'John',
  weapon: {
    name: 'sword',
  },
};

// Correto, porém verboso
let clothingName;
if (player != null && player.clothing != null) {
  clothingName = player.clothing.name;
}
console.log(cloathingName);

// Usando optional chaining
const clothingName = player.clothing?.name;
console.log(cloathingName); // expected output: undefined

// Correto, porém verboso
let value;
if (player != null && typeof player.someNonExistentMethod === 'function') {
  value = player.someNonExistentMethod();
}
console.log(value);

// Usando optional chaining
console.log(player.someNonExistentMethod?.()); // expected output: undefined
```

## Sintaxe

```javascript
object?.prop;
object?.[expression];
arr?.[index];
func?.(args);
```

O novo operador de encadeamento opcional ajuda reduzir a quantidade de código escrita, simplificando a leitura e manutenção.

Junto com o optional chaining operator receberemos o [Nullish coalescing operator][nullish coalescing operator], mas isso é assunto para um post futuro.

[optional chaining operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
[nullish coalescing operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_Coalescing_Operator
zeit node express redirect example Q&A
Tags: node, express, redirect, zeit
Published: 2020-01-28 00:27:24

or how a SIMPLE project snowballed into a major headache that kept me up past midnight 

i just wanted to write a single line of node to redirect a URL to URL/a-random-sub-page

first i read these docs
* https://expressjs.com/en/starter/basic-routing.html
* https://expressjs.com/en/guide/routing.html
* https://expressjs.com/en/api.html#res.redirect
* https://github.com/ForbesLindesay/deviate

Q1 
why would i even need deviate ?
A1 
HACK lets just forget about deviate

Q2 
why does ZEIT NOW display server.js instead of running it ?
A2 
HACK lets just redirect the redirect to ZEIT NOW URL/server.js ie
https://rfugcoinorg.osde8info.now.sh/server.js 

would love to have better / correct answers to A1 and A2 

code is here

{% github osde8info/rfugcoin.org %}
Navigate into a newly created directory
Tags: bash, shell, terminal, mkdir
Published: 2020-01-29 11:51:28

---
title: Navigate into a newly created directory
published: true
date: 2020-01-28 00:00:00 UTC
tags: bash, shell,terminal,mkdir
canonical_url: 
---

Today I came across a fantastic command line trick.

Normally when I want to create a directory in the command line it takes multiple commands to start working in that directory.

For example:

```powershell 
mkdir tempy
cd tempy
```

Well, that can be shortened to a one-liner!

```powershell 
mkdir tempy && cd $_
```

🤯

This is why I love software development. 

It does not matter how long you have been doing it you are always learning something new!

Success 🎉
Timers in .NET Part 2
Tags: dotnet, csharp, dotnetcore, timers
Published: 2020-01-29 11:58:02

---
title: Timers in .NET Part 2
published: true
date: 2020-01-28 00:00:00 UTC
tags: dotnet,csharp,dotnetcore,timers
canonical_url: 
---

I have started to cross-post to the [Dev Community](https://dev.to/) website as well as on my [solrevdev blog](https://solrevdev.com).

A previous post about [Timers in .NET](https://dev.to/solrevdev/timers-in-net-omd) received an interesting reply from [Katie Nelson](https://dev.to/katnel20) who asked about what do do with [Cancellation Tokens](https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netcore-3.1).

**TimerCallBack**

The [System.Threading.Timer](https://docs.microsoft.com/en-us/dotnet/api/system.threading.timer?view=netcore-3.1) class has been in the original .NET Framework almost from the very beginning and the [TimerCallback](https://docs.microsoft.com/en-us/dotnet/api/system.threading.timercallback?view=netcore-3.1) delegate has a method signature that does not handle CancellationTokens natively.

**Trial and error**

So, I span up a new `dotnet new worker` project which has StartAsync and StopAsync methods that take in a CancellationToken in their method signatures and seemed like a good place to start.

After some tinkering with my original class and some research on StackOverflow, I came across [this post](https://stackoverflow.com/a/56666084/2041) which I used as the basis as a new improved Timer.

**Improvements**

Firstly I was able to improve on my [original TimerTest class](https://gist.github.com/solrevdev/60f58cc72b3576617486162470c50280) by replacing the field level locking object combined with its’s calls to `Monitor.TryEnter(_locker)` by using the Timer’s built-in [Change](https://docs.microsoft.com/en-us/dotnet/api/system.threading.timer.change?view=netcore-3.1) method.

Next up I modified the original TimerCallback DoWork method so that it called my new `DoWorkAsync(CancellationToken token)` method that with a CancellationToken as a parameter does check for `IsCancellationRequested` before doing my long-running work.

The class is a little more complicated than the original but it does handle <kbd>ctrl</kbd><kbd>c</kbd> gracefully.

**Source**

So, here is the new and improved Timer in a new dotnet core background worker class alongside all of its project files.

{% gist https://gist.github.com/solrevdev/f28ab81363e9875d25b3f3453339a556 %}

Success 🎉
Neovim Tip - GitLens
Tags: vim, productivity, lua
Published: 2020-01-29 06:39:46

---
title: Neovim Tip - GitLens
published: true
date: 2020-01-28 00:00:00 UTC
tags: [vim, productivity, lua]
canonical_url: https://teukka.tech/vimtip-gitlens.html
---

## Intro
[GitLens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) is a VSCode plugin that, among other things, allows you to see the time, commit author, and commit message of the current line. With a little help from to the neovim api and our shell, it we can recreate this functionality in a few lines of lua code.

## The Code

```lua
-- in utils.lua
local M = {}
local api = vim.api
function M.blameVirtText()
  local ft = vim.fn.expand('%:h:t') -- get the current file extension
  if ft == '' then -- if we are in a scratch buffer or unknown filetype
    return
  end
  if ft == 'bin' then -- if we are in nvim's terminal window
    return
  end
  api.nvim_buf_clear_namespace(0, 2, 0, -1) -- clear out virtual text from namespace 2 (the namespace we will set later)
  local currFile = vim.fn.expand('%')
  local line = api.nvim_win_get_cursor(0)
  local blame = vim.fn.system(string.format('git blame -c -L %d,%d %s', line[1], line[1], currFile))
  local hash = vim.split(blame, '%s')[1]
  local cmd = string.format("git show %s ", hash).."--format='%an | %ar | %s'"
  if hash == '00000000' then
    text = 'Not Committed Yet'
  else
    text = vim.fn.system(cmd)
    text = vim.split(text, '\n')[1]
    if text:find("fatal") then -- if the call to git show fails
      text = 'Not Committed Yet'
    end
  end
  api.nvim_buf_set_virtual_text(0, 2, line[1] - 1, , {}) -- set virtual text for namespace 2 with the content from git and assign it to the higlight group 'GitLens'
end

function M.clearBlameVirtText() -- important for clearing out the text when our cursor moves
  api.nvim_buf_clear_namespace(0, 2, 0, -1)
end

return M
```

```vim
" in init.vim
lua vim.api.nvim_command [[autocmd CursorHold * lua require'utils'.blameVirtText()]]
lua vim.api.nvim_command [[autocmd CursorMoved * lua require'utils'.clearBlameVirtText()]]
lua vim.api.nvim_command [[autocmd CursorMovedI * lua require'utils'.clearBlameVirtText()]]

hi! link GitLens Comment

```
Rename Local and Remote Git Branch
Tags: git, vsc, linux, unix
Published: 2020-05-01 13:18:36

---
title: Rename Local and Remote Git Branch
published: true
date: 2020-01-28 00:00:00 UTC
tags: git, vsc, linux, unix
canonical_url: https://tech.serhatteker.com/post/2020-01/rename-local-and-remote-git-branch/
---

If you mistyped or want to change a branch name, here is the steps you should follow:

1. Rename the local branch to the new name:

    ```bash
    $ git branch --move <old_branch_name> <new_branch_name>
    ```
2. Delete the old branch on the remote:

    ```bash
    $ git push <remote> --delete <old_branch_name>
    ```
3. Push the new branch to remote:

    ```bash
    $ git push <remote> <new_branch_name>
    ```
4. Reset the upstream branch for the new_branch_name local branch

    ```bash
    $ git push <remote> -u <new_branch_name>
    ```

### Example
If you would like to see all in action:

```bash
$ git branch -m bug feature
$ git push origin --delete bug
$ git push origin feature
$ git push origin -u feature
```

We renamed our bug branch to feature. Since you know all bugs are features in some way.

### As Function
You may want to use it as a function like me:

```bash
#!/bin/bash
# $HOME/.functions

rename-git-branch() {
	OLD_NAME="$1"
	NEW_NAME="$2"

	git branch -m $OLD_NAME $NEW_NAME && \
	git push origin -d $OLD_NAME && \
	git push origin $NEW_NAME && \
	git push origin -u $NEW_NAME
}
```

__Usage__:

```bash
$ rename-git-branch bug feature
```


All done!