teleren/devto huggingface dataset:
How I got two computers to update one contribution graph under one github user
Tags: github, git, beginners, tutorial
Published: 2022-07-23 03:33:15

Here's what I did to hook up my work computer to attribute commits to my personal Github account.

## Assumptions:

If you're following along I'm going to assume you've set up an SSH key to enable pushing / pulling from your second computer.


## Dependencies:
A suitable test repo — I cloned my sadiejay/sadiejay repo to test commit and preview the author field.


## Documentation:
I then used [this blog post](https://poanchen.github.io/blog/2018/03/23/how-to-set-up-gpg-key-on-github) to set up my GPG Key. 

[Github documentation](https://docs.github.com/en/authentication/managing-commit-signature-verification/checking-for-existing-gpg-keys) for additional reference.


## Steps: 
Once I installed the GPG command line tool I followed the prompts.

For macOS, or at least my GPG cli, prompted to input your "Real Name"

I believe "Real Name" corresponds to your Github name NOT username. 
For example, my `name` is `Sadie`. However, `username` is `sadiejay`.


![Screenshot of Github name and username](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c781q4geh8frn6qgckzv.png)


For email use whatever is by your name in your commit history. I made sure to use my `no-reply` address provided by Githbub. [Check note under step 8](https://docs.github.com/en/authentication/managing-commit-signature-verification/generating-a-new-gpg-key)

And that should work once you generate and input your key into Github.


## Help I messed up I didn't change the automatically configured committer info


![Incorrectly setup gitconfig](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdxh07xnsnpf023vcysl.png)

You can edit your gitconfig file with `git config --global --edit` after you've made a commit on your local computer. 

From there you can either
- `git rebase -i` and cherry pick which commits needs changing, then `git commit --amend --reset` if you've pushed to remote

- `git commit --amend --reset author` if you haven't pushed to remote.


![Updated author -note new commit hash because of rebase](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ux9a7dszxgc7vwbcet0u.png)


##Conclusion + Note
In addition to having the GPG key, having the `git config` file match the github name and email is the main takeaway, email alone DID NOT work for me on the M1 pro.

I don't know what would happen if I need to change my email to make work email domain.

If I'm missing something or someone can explain what the GPG key is I'm all ears.

This could be all wrong and I just got lucky, but hopefully my lucky instructions help you too 😅

###Acknowledgements
- WIT community members for illuminating the connection of the GPG Key to the contribution graph
- Virtual Coffee community members for helping me through vi, git rebase, and cluing me to the config file set up discrepancy
I'm new here...
Tags: watercooler, codenewbie, beginners, wecoded
Published: 2022-07-23 03:30:00

This is my first post. I just wanted to say hello to all and introduce myself. My nickname is Omi. I'm a mother of three kids, the two youngest of whom are grade-schoolers (10 & 13) with Autism. I'm back in school to finish my BS degree in Computer Science after spending the last decade a stay-at-home mother, musician, and self-taught freelance eCommerce and website developer.

I want to pursue my Masters as well, life willing, now that my kids are older and more independent. I consider myself a beginner despite having over a decade of experience making websites because I never went beyond the tools I used freelancing— primarily, HTML, CSS, Javascript, PHP and MySQL. Most of my coding was for sales funnels (and optimization), Shopify Development, and Woocommerce. Although I also became (by nature of the game) a "jack of all trades" eCommerce sales and technology consultant.

Alas, this is not what I WANT to do. It's what I COULD do (at the time) and HAD to do (all the time) to put food on the table. My relationships, schedule, family demands, and finances have kept me deadlocked for two decades. And as a minority middle aged female, without a degree or much experience, at the peak of COVID amidst inflation hell with handicapped children- I had a decision to make: Go back to school... or go on welfare.

I found the Dev dot To site while browsing through tutorial websites. I have a new [LinkedIn](https://www.linkedin.com/in/sshunamon/) but no connections. Enrolled officially in my program, I now have access to LinkedIn learning, and free vouchers from Microsoft which I'm pursuing on the side. I've yet to decide my career focus but I'm leaning toward Data Science since I genuinely loved problem solving with eCommerce clients using sales and customer data.

My interests are still very broad however. I enjoy amateur game dev, AI, ML, VR (shiny object syndrome), blockchain and generative art. My family and friends consider me a geek, but I'm just nowhere and completely blown away by the talents so many of you hold— it's inspiring and amazing. I only wish I could be half as good as some of you someday.

I've started reaching out online to be part of tech communities because my school is mostly online and my lifestyle doesn't offer me many opportunities to mix and meet anyone offline. Because of remote school, I don't even get to off-topic chit chat or socialize with my peers in class.

Anyhow, that's "About Me" enough. I hope to follow a few people I can learn from here.
Dự án Da Naur Villas & Homestay - LandUp
Published: 2022-07-23 03:16:03


Chào mừng đến với https://landup.net/du-an/da-naur-villas-homestay/ tại LandUp.net có thông tin vị trí, chiết khấu, pháp lý, tiện ích, giá bán dự án Dự án Da Naur Villas & Homestay - LandUp Phú Quốc mới nhất. Nhờ đó có được khoản đầu tư sinh lời hấp dẫn.
Địa chỉ: 3 Nguyễn Văn Đậu, Phường 5, Quận Phú Nhuận, Thành phố Hồ Chí Minh
Số điện thoại: 0928.0168.69
Website: https://landup.net/du-an/da-naur-villas-homestay/
Email hiển thị: hotro-pvdbinhchuan@gmail.com
Youtube/ Blog Google: https://www.youtube.com/channel/UC8fFTLg5rzNPGaxrZJ7wkOw/about
https://sites.google.com/view/motorcycleclick/
Tags: Dự án Da Naur Villas & Homestay, Da Naur Villas & Homestay Lâm Đồng, bất động sản Lâm Đồng, bất động sản Bảo Lộc, LandUp.net
Hashtag: #danaurvillashomestay #danaurvillashomestaylamdong #danaurvillashomestaybaoloc #landup

https://www.facebook.com/D%E1%BB%B1-%C3%A1n-Da-Naur-Villas-Homestay-LandUp-103263465805096
https://www.pinterest.com/danaurvillashomestaypq/
https://www.linkedin.com/in/kim-ng%C3%A2n-b84a66245/
https://about.me/danaurvillashomestay-landup
https://www.behance.net/danaurvillas-landup
https://danaurvillashomestay-landup.tumblr.com/
https://www.tumblr.com/blog/danaurvillashomestay-landup
https://www.youtube.com/channel/UC8fFTLg5rzNPGaxrZJ7wkOw/about
https://myspace.com/danaurvillashomestay1
https://soundcloud.com/danaurvillashomestay1
Número mayor de un Array
Tags: csharp
Published: 2022-07-23 03:04:00

**Ejercicio #1**
Definición: Desarrollaré un programa con C# para obtener el valor mayor de un array.

Nota: el código compartido es una de las maneras de como encontrar la solución, si tienes otra manera de como solucionarlo, nos lo puedes compartir en los comentarios.


```
static void Main(string[] args)
{
    //Invocamos nuestro Método
    Array1();
}
```

```
public static void Array1()
{
     //Declaramos nuestra variable array
     int[,,,] Array = new int[9, 5, 15, 2];

     //Declaramos valiable para obtener la longitud de nuestro array
     int Valor = Array.Rank;

     //Inicializamos nuestra variable
     int ValorMaximo = 0;

     //Recorremos la cantidade de veces de longitud de nuestro array
     for(int i=0; i<Valor; i++)
     {
         //Validamos el valor obtenido de nuestro array en cada ciclo
         if (Array.GetLength(i) > ValorMaximo)
         {
             //Si el valor es mayor del valor que tiene nuestra 
             variable, entonces le asignamos el nuevo valor
             ValorMaximo = Array.GetLength(i);
          }
      }

      //Imprimimos el valor maximo
      Console.WriteLine(ValorMaximo);
}
```

`Resultado: `**15**
Sliding Window Technique
Tags: leetcode, algorithms, java
Published: 2022-07-23 02:29:00

**When to use:** Aims to reduce the use of nested loop and replace it with a single loop. Reduces the time complexity from O(n^2) to O(n).

**Two types of sliding window:**

**Fixed window length k:** the length of the window is fixed and you will be asked to find something in the window. For example, the maximum sum or maximum average of each window. 
First we start by getting the sum of the k sized window and keep track of the max value then sliding it by removing from the left and adding to the right.

```java
class Solution {
    public double findMaxAverage(int[] nums, int k) {
        
        double maxAverage = 0;
        int sum = 0;
        
        for(int i = 0; i < k; i++){
            sum += nums[i];
        }
        
        maxAverage = sum;
        
        for(int i = k; i < nums.length; i++){
            sum += nums[i] - nums[i - k];
            maxAverage = Math.max(maxAverage, sum);
        }
        
        return maxAverage/k;
    }
}
```

**Dynamic-size sliding window**: The window size is not fixed and is also known as the [two-pointers technique](https://dev.to/tammyvocs/two-pointer-technique-39no). 
However, in a dynamic sliding window problem, the right pointer will be continuously changing unlike a traditional two pointer problem where the right pointer is initialized as the end of the list/array. Usually you will be asked to find the subarray that meets the criteria.
A simple guessing game in python
Published: 2022-07-23 01:50:00

```
def game_new():
    guess = input('Enter the guess word')
    word = 'love'
    while guess != word:
        guess = input('try again')

        while guess == word:
            print('You gorit!')
            ans = input('Want to try again')
            if ans == 'no':
                print('bye')
            else:
                game_new()
game_new()

:)
```
Bugfix: Figma Icon Clipped Off
Tags: figma, webdev, reactnative, productivity
Published: 2022-07-23 01:38:00

This one's for you frontend devs boggled by 0.5px weird icon cropped off.

| Figma Design | Your App |
|--------------|----------|
| ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7f8mwkm8lxd8buoaete3.png) | ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sffax4hrltl00yqpkvtb.png) |

> Well, crap... (Icon on flaticon.com by freePik)  

## Why icon gets cropped?
Figma designs have high precision, to pixels' decimal places. Below discussions are quite detailed, so I summarize:
- **Figma Export PNG** will crop / extend icon if pixel is on non-integer value coordinate. See below example on icon width.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ignkand9vvzqyljccbnc.png)
 
> When **actual** icon has non-integer pixel, it may expand to **possibility1** or shrink to **possibility2**
 

Reference Links:
[Figma Discussion: Unwanted cropping when exporting to PNG](https://forum.figma.com/t/unwanted-cropping-when-exporting-to-png/2160)
[Figma Discussion: SVG exports at a different size to W & H values in editor](https://forum.figma.com/t/svg-exports-at-a-different-size-to-w-h-values-in-editor/1941/9)

## Figma: Export SVG vs PNG
- SVG precise in size to decimal places, PNG is less precise.

## How to obtain uncropped icon?
- Export as SVG, then use a SVG to PNG converter.
- **[ezgif.com/svg-to-png](https://ezgif.com/svg-to-png) preserves the quality**
- can either (1) fix neither width nor height to get original size PNG, (2) fix longer side to match defined maximum side length in code (eg set 32 for `<Image style{{height:32, width: 32}} ... />`)
- Option 2 is good in times when the icon is really off-integer-pixels, where a ezgif default export becomes 32x33 px. Idea is to make the longer side of icon fit the view box (in this case maybe 31x32 px). Then only the shorter side will remain uncropped.

## Alternatives
**1. Export PNG in Figma with size 1.06x instead of 1x**
Supposedly, if you find the right multiplier, you could hit an integer pixel (instead of decimal), and that could work. But it requires plenty of trial and error, and a flooded Downloads folder.

**2. Use resizeMode: contain**
A colleague recommended this, it was quite an interesting alternative.
https://mehrankhandev.medium.com/understanding-resizemode-in-react-native-dd0e455ce63
How to extract the first set of numbers in a string using PHP
Tags: php, html, webdev, laravel
Published: 2022-07-23 00:26:16

[How to extract the first set of numbers in a string using PHP](https://allgoodsfree.com/how-to-extract-the-first-set-of-numbers-in-a-string-using-php/)
 
<?php
    $str='acc123nmnm4545';
    if(preg_match('/\d+/',$str,$arr)){
       echo $arr[0];
    }
?>
 
Other ways to extract numbers from strings in PHP
 
The first method, using regular expressions:
 
function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$reg='/(\d{3}(\.\d+)?)/is';//Regular expression matching numbers
preg_match_all($reg,$str,$result);
if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){
return $result[1][0];
}
return '';
}
 
The second method, using the in_array method:
 
function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$temp=array('1','2','3','4','5','6','7','8','9','0');
$result='';
for($i=0;$i<strlen($str);$i++){
if(in_array($str[$i],$temp)){
$result.=$str[$i];
}
}
return $result;
}
 
 
The third method, using the is_numeric function:
 
function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$result='';
for($i=0;$i<strlen($str);$i++){
if(is_numeric($str[$i])){
$result.=$str[$i];
}
}
return $result;
}

E.g:

//Intercept the number 2 in the string
    $str = 'Q coins 2';
    $result='';
    for($i=0;$i<strlen($str);$i++){
        if(is_numeric($str[$i])){
            $result.=$str[$i];
        }
    }
    print_r($result);die;
    // output result 2
#JulyOT 23: Azure cost monitor
Tags: julyot, iot, embedded, azure
Published: 2022-07-25 02:22:49

---
title: #JulyOT 23: Azure cost monitor
published: true
date: 2022-07-23 00:00:00 UTC
tags: julyot,iot,embedded,azure
canonical_url: https://JulyOT.dev/blog/23-azure-cost-monitor
series: JulyOT 2022
cover_image: https://JulyOT.dev/assets/images/JulyOT-banner-23-azure-cost-monitor-24b9ea63ff0b5aacd79268630ca4c75f.png
---

_Monitor your cloud costs using this e-paper Azure cost monitor._

## Azure cost monitor[​](#azure-cost-monitor "Direct link to heading")

When using Microsoft Azure services, it's helpful to know how much you're spending on a day-to-day basis. This Azure cost monitor uses the low-power, wireless Adafruit MagTag board to display a daily cost forecast for your Azure subscription.

![Azure cost monitor hardware](https://JulyOT.dev/assets/images/cost_monitor-2500dfa91ecd7f248cc01f58703db744.jpg)

This project is intended to show you how to use the Azure cost management API. Take a look at this project and adapt it to fit your needs!

_Please note that it's only possible to get a cost forecast - actual costs are only available once you're billed._

[Check out the project on Hackster](https://www.hackster.io/jenfoxbot/azure-cost-monitor-31811a)
Should I switch to Linux?
Tags: linux, windows, ubuntu, webdev
Published: 2022-07-22 23:41:00

The Linux kernel, which Linus Torvalds first made accessible on September 17, 1991, is the foundation of the Linux operating system family, a group of free and open-source Unix-like operating systems. Usually, Linux is distributed in the form of a package. Here are some reasons to choose Linux. If you care about your privacy, switch…

The Linux kernel, which Linus Torvalds first made accessible on September 17, 1991, is the foundation of the Linux operating system family, a group of free and open-source Unix-like operating systems. Usually, Linux is distributed in the form of a package.

## Here are some reasons to choose Linux.
If you care about your privacy, switch to Linux instead of Windows.

## Linux is completely free!
Yes, the glorious cost of Linux is exactly $0.00.

While purchasing a license for Windows can be extremely expensive.

## Linux is safe.

On Windows, you frequently need to install anti-virus software that requires a subscription, but Linux asks, “Anti-what?”

## You can change anything!

If there is something in Linux that you don’t like, you can change it or remove it.

## Pre-installed Powerful Tools

Linux already has a tone of useful programming and hacking tools installed.

## Privacy
Windows always gather user information. nearly everything

Linux doesn’t have a hide-and-seek game because its source code is always accessible.

## Portability
A portable OS is Linux. It works with many different computer architectures.

Portability means you can move your code from one system architecture to another easily.

You should use Linux for a number of additional reasons, about which we’ll talk in a later post.
Servlets en Java
Tags: tutorial, webdev, java
Published: 2022-07-22 23:11:00

Los **servlets** son módulos escritos en java que se utilizan en un servidor que puede ser o no ser servidor web, para extender sus capacidades de respuesta a los clientes al utilizar las potencialidades de Java.
**Propiedades:**
_**Manejo de Sesiones:**_ Se puede hacer seguimiento de usuarios a través de distintos servlets a través de la creación de sesiones.
_**Utilizacion de Cookies:**_ Las cookies son pequeños datos en texto plano que pueden ser guardados en el cliente. La API de servlets permite un manejo fácil y limpio de ellas.
_**Multi-thread:**_ Los servets soportan el acceso concurrente de los clientes, aunque hay que tener especial cuidado con las variables compartidas a menos que se utilize la interfaz _SingleThreadModel_.
_**Programación en Java:**_ Se obtienen las características de multiplataforma o acceso a APIs como JDBC, RMI, etc.
**El ciclo de vida de un Servlet**
Cada servlet tiene el mismo ciclo de vida:

-  Un servidor carga e inicializa el servlet
-  El servlet maneja cero o mas peticiones de cliente.
-  El servidor elimina el servlet.
Introducción a React Context con los Hooks de React
Tags: javascript, webdev, programming, react
Published: 2022-07-22 22:48:46

Qué es la Context API de React
La Context API de React es una forma de crear variables globales que podrás compartir fácilmente con otros componentes de tu aplicación. La alternativa consiste en pasar las propiedades de un componente padre a un componente hijo o nieto, y así sucesivamente en este orden descendente.

También podrías usar una librería de gestión de estado como Redux. Sin embargo, el uso de contextos mediante la Context API es una solución más ligera y sencilla que no está mal para aplicaciones que no son excesivamente grandes.

Cómo crear un contexto
En ocasiones puede ser deseable que ciertos datos se compartan en toda la aplicación, de modo que puedas usarlos en todos los componentes React. Por ejemplo, este es el caso de ciertas variables que definen los etilos generales de los componentes, que podrían cambiar en base al tema seleccionado o a varias opciones de visualización. Otro ejemplo es el modo noche, que quizás cambie ciertos elementos de los componentes en base a algún parámetro. También podrías obtener ciertos datos de una API que quieres compartir entre diferentes componentes. Para lograr estas cosas puedes usar un contexto.

En el siguiente ejemplo vamos a crear un contexto al que llamaremos ContextoUsuario, que dará lugar a los componentes ContextoUsuario.Provider y ContextoUsuario.Consumer. Un Provider no es otra que el componente que proporciona el valor, mientras un Consumer es el componente que utiliza o consume el valor.

Para crear el contexto vamos a usar el método React.createContext(), que usaremos en un archivo de ejemplo al que llamaremos ContextoUsuario.js:

import React from 'react';

const ContextoUsuario = React.createContext();

export const ProviderUsuario = ContextoUsuario.Provider;
export const ConsumerUsuario = ContextoUsuario.Consumer;

export default ContextoUsuario;
El método React.createContext() acepta un objeto opcional como valor, pero en este caso lo representamos como vacío, ya que siempre podremos establecer su valor más tarde, caso que se daría de obtener los datos desde una API. Sin embargo, podemos establecer cualquier valor inicial, como por ejemplo React.createContext(true).

Proporciona un contexto con un Provider
El Provider de un contexto siempre debe envolver a modo de wrapper a los Consumers del contexto. En el siguiente ejemplo envolvemos todo el componente App de la aplicación en el Provider que hemos creado. Creamos un objeto llamado usuario y se lo pasamos a los componentes que descienden del Provider ProviderUsuario como un valor de una propiedad del mismo:

import React from 'react';
import PaginaInicio from './PaginaInicio';
import { ProviderUsuario } from './ContextoUsuario';

function App() {
  const usuario = { nombre: 'Edu', modoOscuro: true };

  return (
    <ProviderUsuario value={usuario}>
      <PaginaInicio />
    </ProviderUsuario>
  );
}
Kotlin Smart Cast is Awesome!
Tags: kotlin, beginners, android, programming
Published: 2022-07-22 21:57:18

**I don't know Kotlin can do smart cast like this. It is smart enough to cast it for you automatically, so you don't need to explicitly cast anymore.**

I totally missed this Kotlin awesome feature in my previous post - [Complete C# to Kotlin Syntax Comparisons](https://vtsen.hashnode.dev/complete-c-to-kotlin-syntax-comparisons).

I came to be aware of this smart cast only after 8 months of Kotlin development, and I might have been using it without knowing it. The Android Studio IDE takes care of it!

Let's say you have `BaseClass` and `ChildClass` like this.

```
open class BaseClass
class ChildClass(val value: Int): BaseClass()
```
and, you create the `ChildClass` object and being referenced by the `BaseClass`
```
val obj: BaseClass = ChildClass(value = 7)
```

To access the data in `ChildClass`, you do explicit cast below.
```
val childObj = obj as ChildClass
childObj.value
```
But the Kotlin compiler can smart cast automatically for you in the following scenario:

## Example 1
```
fun smartCastExample1() {
    val obj: BaseClass = ChildClass(value = 7)
    //Calling obj.value here is not allowed
    //because obj belongs to BaseClass

    if (obj is ChildClass) {
        //obj in this scope is smart cast to ChildClass.
        //Thus, accessing the obj.value is allowed here
        println("Child value is ${obj.value}")

        //You don't need to explicit cast like this
        val childObj = obj as ChildClass
        println("Child value is ${childObj.value}")
    }
}

```
> `obj` in this `if` scope must be `ChildClass`, thus Kotlin compiler smart casts it

## Example 2
```
fun smartCastExample2() {
    val obj: BaseClass = ChildClass(value = 7)
    if (obj !is ChildClass) return

    // obj is smart cast to ChildClass
    println("Child value is ${obj.value}")
}
```
> `obj` here must be `ChildClass` since it has been returned if it is not.


## Example 3
```
fun smartCastExample3() {
    val obj: BaseClass = ChildClass(value = 7)

    // obj at right side of || is smart cast to ChildClass
    if (obj !is ChildClass || obj.value == 7) return

}
```
> This `obj.value` only gets evaluated when `obj` is `ChildClass`. If you change `obj !is ChildClass` to `obj is ChildClass`, the smart cast won't work.


## Example 4
```
fun smartCastExample3() {
    val obj: BaseClass = ChildClass(value = 7)

    // obj at right side of && is smart cast to ChildClass
    if (obj is ChildClass && obj.value == 7) return
}
```
> Similar to example above, the second check is only evaluated when `obj` is `ChildClass`. If you change `obj is ChildClass` to `obj !is ChildClass`, the smart cast won't work.

The example here is cast from super type to subtype. It also works for nullable type to non-nullable type. See more example [here](https://play.kotlinlang.org/byExample/08_productivity_boosters/04_Smart%20Casts). 

---

*Originally published at [https://vtsen.hashnode.dev](https://vtsen.hashnode.dev/kotlin-smart-cast-is-awesome)*.