teleren/devto huggingface dataset:
download Windows Store apps with PowerShell over https://store.rg-adguard.net/
Tags: powershell, windows
Published: 2020-12-07 16:34:11

---
title: download Windows Store apps with PowerShell over https://store.rg-adguard.net/
published: true
description: Script automates download files related to a Windows Store app.
tags: #powershell #windows
---

Especially in enterprise environments installing apps from Windows Store is turned off. One workaround is web site https://store.rg-adguard.net/ - courtesy of [@rgadguard](https://twitter.com/rgadguard) & mkuba50 - which can be used to download files related to a particular store app.

## How to find a product URL

- go into store (probably on a machine where store is not locked)
- search for app
- click __Share__
- __Copy Link__
- paste into input field right of __URL Link__

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

## Script

I created this script where I can use the product URL obtained above and download a set of related files for a local install:

```PowerShell
$apiUrl = "https://store.rg-adguard.net/api/GetFiles"

$productUrl = "https://www.microsoft.com/store/productId/9nblggh5r558" # To Do
#$productUrl = "https://www.microsoft.com/store/productId/9MSPC6MP8FM4" # Whiteboard
#$productUrl = "https://www.microsoft.com/store/productId/9WZDNCRFJBB1" # Wireless Display Adapter

$downloadFolder = Join-Path $env:TEMP "StoreDownloads"
if(!(Test-Path $downloadFolder -PathType Container)) {
    New-Item $downloadFolder -ItemType Directory -Force
}

$body = @{
    type = 'url'
    url  = $productUrl
    ring = 'RP'
    lang = 'en-US'
}

$raw = Invoke-RestMethod -Method Post -Uri $apiUrl -ContentType 'application/x-www-form-urlencoded' -Body $body

$raw | Select-String '<tr style.*<a href=\"(?<url>.*)"\s.*>(?<text>.*)<\/a>' -AllMatches|
 % { $_.Matches } |
 % { 
    $url = $_.Groups[1].Value
    $text = $_.Groups[2].Value
    Write-Host $text

    if($text -match "_(x86|x64|neutral).*appx(|bundle)$") {
        $downloadFile = Join-Path $downloadFolder $text
        if(!(Test-Path $downloadFile)) {
            Invoke-WebRequest -Uri $url -OutFile $downloadFile
        }
    }
}

```
Azure Kubernetes Service (AKS) with Go
Tags: go, code, developer, 100daysofcode
Published: 2020-12-07 16:32:44

We're in a pretty weird time for tech where things are constantly changing. Things have always been in a constant state of flux, but it's way more-so now. Now, as a Developer, the role is shifting drastically.

Where-as before you were worried about what code you were writing, Cloud Developers are seeing a merge between cloud services (infrastructure) and the code they're writing.

For example, let's say you want to test out a containerized app in Kubernetes. Chances are you may have to spin up that dev environment, but how do you do it?

A few options are:

Infrastructure-as-code with Terraform

Configuration Management with Ansible

Some other solution using JSON or YAML

The problem is, you may not want to do that. You want an automated way to create a cloud service with a language YOU'RE comfortable with. That's where Infrastructure-as-software comes into play.

Infrastructure-as-software is like Infrastructure-as-code, but instead, you get to write it in a language you're comfortable with and still have a state (metadata) that's stored and can be shared throughout the team.

In the video below, I go into how to work with Infrastructure-as-software with Kubernetes, Go, and Pulumi. Let me know your thoughts :)

https://www.youtube.com/watch?v=JOGNFHEXwyU
JavaScript CPU Emulator Problem
Tags: javascript, assembly, es6, todayilearned
Published: 2020-12-07 16:24:59

I've picked up CodeSignal again and aim to solve something every day (either challenges or casual problems). Recently, we got [a medium challenge](https://app.codesignal.com/challenge/oRAuH7eoH8zuMr9Fg) from hamlet_m1. It is to emulate a CPU assembly language. (Hope I didn't mix up technical terms). 

This time, I'm proud to be one of the JS solvers together with other 8 geeks: 

|User|Level|Country|Chars|
| --- | ---:| --- | ---:|
|[Thomasz](https://app.codesignal.com/profile/thomasz)|70|USA|290|
|[Giang_P_r](https://app.codesignal.com/profile/Giang_P_4)|87|Vietnam|437|
|[kov](https://app.codesignal.com/profile/kov)|93|Hungary|480|
|[hk7math](https://app.codesignal.com/profile/hk7math)|44|Hong Kong|503|
|[danielhong35](https://app.codesignal.com/profile/danielhong35)|86|USA|512|
|[murtaza_m2](https://app.codesignal.com/profile/murtaza_m2)|43|Romania|921|
|[omar-aguilar](https://app.codesignal.com/profile/omar-aguilar)|62|Mexico|1367|
|[linh_pv_9x](https://app.codesignal.com/profile/linh_pv_9x)|82|Vietnam|1490|
|[jonathas_s1](https://app.codesignal.com/profile/jonathas_s1)|24|Brazil|2198|

The best solution by [thomasz](https://app.codesignal.com/profile/thomasz) is an awe to me! Not only is it far shorter than all other solutions, but it is also still highly readable (to people like me who like hacky tricks)

> Disclaimer: the full solution just for reference, please tell me to delete it if I violated any rule...
```javascript
cpuEmulator = s => {
    
    z = 2 ** 32
    r = Array( 43 ).fill( 0 )
    R = x => +x.split`R`[ 1 ]

    for ( d = 0; l = s[ d++ ]; ) {
        
        [ c, a, b ] = l.split(/[\s,]/)
        o = y => r[ R( a ) ] = ( r[ R( a ) ] + y + z ) % z
        
        c == 'MOV' ?
            r[ R( b ) ] = R( a ) + 1 ? r[ R( a ) ] : +a  :            
        c == 'ADD' ?
            o( r[ R( b ) ] ) :
        c == 'DEC' ?
            o( -1 ) :
        c == 'INC' ?
            o( 1 ) :
        c == 'INV' ?
            o( ~r[ R( a ) ] * 2 + 1 ) :
        c == 'JMP' || c == 'JZ' && !r[ 0 ] ?
            d = +a - 1 : 0       
    }

    return r[ 42 ] + ''
}
```

Here are some tricks I discovered in this snippet:
1. `Array(n).fill(x)` to initialize an array of length n with prefilled values `x` (be careful about multi-dimension arrays though)
2. `+'numeric string'` to cast a string as a number or `NaN`
3. Regex `/[xyz]/` to split string by separators `x`, `y`, `z` simultaneously
4. `c == 'case1' ? ... : c == 'case2' ? ... : ...` to well format nested ternary operators as a switch-case 
5. `number + ''` to cast a number as a string

Feel free to drop a comment about your takeaways :D
Http endpoint versioning
Tags: aspnetcore, csharp
Published: 2020-12-05 20:34:50

Are you are developing web apis but not versioning the endpoints?
You really should!
It provides so much freedom to make changes to the api without the risk of breaking consumers.

I'm a big proponent of versioning each endpoint separately.
Mainly because I think the alternative introduces coupling between otherwise potentially unrelated endpoints.
I don't like if a change to one endpoint forces me to bump the version of another unchanged endpoint.

As a side note but kind of related.
If you want to provide an api client for your api, it should include all versions (not just the latest) of all endpoints.
If I'm consuming v1 of endpoint A and B, both for which v2 is available, and need to start using A v2. I should not be forced to switch to B v2 as well.
That scales really badly and only gets worse the more of an api you use.
Ask me how I know... 🙈

They way we've implemented versioning in the products I work on we are using a package called __`Handyman.AspNetCore`__ ([nuget](https://www.nuget.org/packages/Handyman.AspNetCore), [github](https://github.com/JonasSamuelsson/Handyman/blob/master/src/Handyman.AspNetCore/docs/index.md)). It integrates with the asp.net core routing system and lets you define multiple versions of the same `http method` / `path` but with different versions.
By default it uses a `api-version` query parameter with a `{major}.{minor}` format, all of which is configurable.

Its really easy to set up, you just configure the required services in `Startup.cs`.

``` csharp
public void ConfigureServices(IServiceCollection services)
{
   services.AddApiVersioning();
}
```

Now all you have to do is to decorate your action methods (or controller class) with the `ApiVersion` attribute.

``` csharp
[ApiController, Route("api/values")]
public class ValuesController : ControllerBase
{
   [HttpGet, ApiVersion("1.0")]
   public IEnumerable<string> GetValues()
   {
      ...
   }

   [HttpGet, ApiVersion("2.0")]
   public IEnumerable<int> GetValues()
   {
      ...
   }
}
```
How to run Linux-only Python projects on windows using git mingw bash
Tags: python, linux, mingw, bash
Published: 2020-12-07 16:22:07

---
title: How to run Linux-only Python projects on windows using git mingw bash
published: true
description: How to get the make command on windows
tags: python, linux, mingw, bash
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/9v92axko7a6vx5n8ydrv.png
canonical_url: https://www.pythonkitchen.com/python-running-makefile-on-windows/
---

Linux owners configure makefiles so as to have easy commands to perform operations such as `make dependencies` to pip install required packages. Here are the dry simple steps to run makefiles in Python projects on Windows.

- Download [git for windows](https://git-scm.com/download/win). You should get git bash, git gui etc

- Download the [mingw GUI setup](https://sourceforge.net/projects/mingw/files/Installer/mingw-get-setup.exe/download). Install it wherever you want. After running the setup you should get a screen like that:

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

- On continuing you should get under **all packages**. Search for make, class bin. Right click and select mark for installation

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

- Under installation, select apply changes

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

- Confirm by clicking on apply

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

- My git for windows' migw is installed at `C:\Program Files\Git\mingw32` and my mingw get is installed at `C:\MinGW`. We need to merge the contents on the mingw32 folder with the MinGW. Ctrl+a to select all folder in MinGW then right click and copy. Then go to mingw32 folder and click paste. When asking is merge, say yes. If same files skip

- Verify if there is `venv/` in project gitignore. If not add it and reapply gitignore by using the following command [(see accepted answer)](https://stackoverflow.com/questions/19663093/apply-gitignore-on-an-existing-repository-already-tracking-large-number-of-file)

- create a new virtual environent. 

```bash
python -m venv venv
```

- activate the env
```bash
cd venv
cd scripts
. activate
```
note the space between . and activate

- cd back `cd ../..`

now try out any command listed [here](https://github.com/pandas-dev/pandas-blog) for example `make dependencies`

Forgot to say under bin rename `mingw-get.exe` to `make.exe`

Anything mail me `arj.python at gmail dot com`

This is something crazily powerful!

You might want to see the other hacky way:

[How to run a Flask Linux-only app on windows](https://dev.to/abdurrahmaanj/how-to-run-a-flask-linux-only-app-on-windows-1418)
Ecto order_by text field
Tags: ecto, orderby, fragment, elixir
Published: 2020-11-19 22:07:50

---
title: Ecto order_by text field
published: true
description: Order query results with a text field using fragments
tags: ecto, orderby, fragment, elixir
//cover_image: https://direct_url_to_image.jpg
---

This post demonstrates how to order an ecto query by a text field.
by sending the order raw sql query through [Ecto.Query.API.fragment/1](https://hexdocs.pm/ecto/Ecto.Query.API.html#fragment/1)


#### Sample table
Assuming we want to query a table containing a list of scheduled jobs with known statuses. e.g 
`RUNNING`, `PENDING`, `COMPLETED`, `FAILED`

| id        | task_ref  | status    |  last_exec_timestamp |
| --------- |:---------:|:---------:| -------------------: |
| 1         | 2232323    | PENDING    |1605726253|
| 2         | 2232324    | FAILED    |1605726153|
| 4    | 2132326   | RUNNING   |1605726233|
| 5    | 2032326   | RUNNING   |1605726233|
| 6    | 2932326   | FAILED   |1605726233|
| 7    | 2233326   | COMPLETED   |1605726233|
| 8    | 2238326   | FAILED   |1605726233|

Our objective is to:
- Fetch all rows
- Order the rows in the following order
    `RUNNING > PENDING > COMPLETED > FAILED`

Off we go
```ruby
 #SomeModule
 import Ecto.Query

 @statuses_order """
    (case(?)
      when 'RUNNING' then 1
      when 'PENDING' then 2
      when 'COMPLETED' then 3
      else 4
    end)
  """
 def your_function do
    from(j in Jobs)
    |> order_by([j], asc: fragment(@statuses_order, j.status))
    |> Repo.all()
 end

```

Just like that our jobs will be returned in the order which we have specified in the `@statuses_order` module attribute.

More information about this subject from elixir forum can be found [here](https://elixirforum.com/t/error-interpolating-a-variable-as-the-first-argument-of-an-ecto-fragment/6711/2).

Thats it! :)
.then() implicitly returns a promise
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-12-07 16:09:24

```js
new Promise((resolve) => resolve(1))
  .then((value1) => value1 * 10)
  .then((value2) => console.log(value2)); // 10

// is same as,

new Promise((resolve) => resolve(1))
  .then((value1) => {
    const newValue = value1 * 10;
    return Promise.resolve(newValue);
  })
  .then((value2) => console.log(value2)); // 10
```

---

**Thanks for reading 💙**  
Follow **@codedrops.tech** for daily posts.  
[Instagram](https://www.instagram.com/codedrops.tech/) ● [Twitter](https://twitter.com/codedrops_tech) ● [Facebook](https://www.facebook.com/codedrops.tech/)

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript  
**[codedrops.tech](https://www.codedrops.tech/)**
Oooops... errei no git. 
Tags: git
Published: 2020-12-07 16:05:54

Por vezes a gente erra operando os comandos do git. Aqui relaciono algumas situações que passei e estou documentando aqui para eu me lembrar sobre o que fazer quando errar novamente. :P

## Errei a mensagem do commit! 
É o uso do amend. Imagina que você fez um commit e deixou um typo na mensagem. Neste caso a gente manda um novo commit indicando `--amend` e indicando a nova mensagem usando -m. Estrutura do comando:  
  
```
git commit --amend -m "nova mensagem"
```

## Adicionei arquivos errados! 
Aqui imaginando que você fez git add mas acabou adicionando arquivos que não deveria ter adicionado e se ligou só depois de fazer o commit. Você consegue desfazer este commit e deixar os arquivos modificados usando:

```
git reset --soft HEAD~1
```

Este `--soft` é muito importante. Ele que indica que os arquivos ficam localmente modificados.

**DICA/CUIDADO 1:** se você usar `--hard` você não só desfaz o commit como ainda volta os arquivos para o estado original. Este tipo de comando eu utilizo quando estou brincando com baby steps game em um coding dojo, e depois de passar o tempo do ciclo, todo código que não foi feito push precisa voltar para o estado original do início do ciclo.  
  
**DICA/CUIDADO 2:** se ao invés de indicar `HEAD~1` você identificar um ID de commit, exemplo "Commit1", o git vai voltar para este commit no seu tempo e todos os commits a frente (Commit2 e Commit3) vão se perder. Então exige bastante cuidado (e um bom motivo :P) estas voltas na linha do tempo:

``` 
Commit1 -> Commit2 -> Commit3 | main/HEAD
```
  
Quais comandos você já precisou para salvar o seu dia por aí? :P
  
-- Daniel Wildt

P.S.: querendo uma dica de FAQ de git? Olha por exemplo o [git tower](https://www.git-tower.com/learn/git/faq). Se tiver outros, sugere aí! 

P.S.2: imagem do post disponível no [flickr](https://flic.kr/p/5Q1Jxv).
Decorating a Virtual Cookie with Python and Canvas
Tags: python, webdev, canvas
Published: 2020-12-07 15:55:54

This post is part of the [Anvil Advent calendar](https://anvil.works/advent). We're building one web app a day for 24 days, using nothing but Python!
 
For Day 7, I built a web app using the Canvas API to decorate a mess-free, no-bake virtual Christmas cookie. And I didn't need to use any HTML, JavaScript or CSS.

You can check out the app [here](https://decorate-a-christmas-cookie.anvil.app) and decorate your own cookie. 

![Screenshot of app](https://dev-to-uploads.s3.amazonaws.com/i/h9oya21ss4z07vqy5zmo.png)

This was my first attempt at using Canvas. Here's how I built the cookie elements and the web app using [Anvil](https://anvil.works) and Python:

## Making lots of circles

![Virtual cookie with a snowman](https://dev-to-uploads.s3.amazonaws.com/i/jko1oaigztu6m92p5bgs.png)

My simple cookie decorations are built from circles and triangles of different sizes and colors. By building more elements, the app could easily be extended to have more options or be more complicated.

Because my app makes extensive use of circles, I first defined a function to draw a circle. The function takes in the desired x and y coordinates of the circle and its radius as arguments:

``` python
def draw_circle(self, x, y, radius):
    c = self.canvas_1
    c.begin_path()
    c.arc(x, y, radius, 0, 2 * math.pi)
    c.close_path()
```

This function is called when the form opens to create the cookie base. It’s also used to make the frosting, sprinkles and snowman.

## Adding random sprinkles

The x and y coordinates for the sprinkles are chosen randomly each time the sprinkles_button is clicked:

``` python
import random

...

def sprinkles_button_click(self, **event_args):
"""This method is called when the button is clicked"""
    color = self.color_dropdown.selected_value
    if color is None:
    color = "#e62325" #defaults to red
    self.canvas_1.fill_style = color

    x_list = list(range(400, 600))
    x_list = random.sample(x_list, 15)

    y_list = list(range(100, 300))
    y_list = random.sample(y_list, 15)

    for x,y in zip(x_list, y_list):
        self.draw_circle(x, y, 6)
        self.canvas_1.fill()
```

## Christmas tree triangles

For the Christmas tree, I just made three overlapping green triangles that get progressively smaller as they move up the y-axis. The following code draws one triangle:

``` python
c = self.canvas_1

c.fill_style = '#00884b'

c.begin_path()
c.move_to(410,280)     
c.line_to(590,280)
c.line_to(500,170)
c.close_path()
c.fill()
```

P.S. You can check out all of our Advent Calendar apps [here](https://anvil.works/advent).
How to Make Command Aliases in Bash
Tags: linux, tutorial, bash, terminal
Published: 2020-12-07 15:54:25

Originally published on my website, [onyxcode.net](https://onyxcode.net)

Hey all! This is a quick one, but I use command aliases all the time and they make my life *so much easier* when I'm in the terminal. Let's get started!


# 1. Opening the .bashrc file

The .bashrc file is short for "bash run commands". It can be located in your home directory at `~/.bashrc`. It contains a few preset configurations already. For this tutorial, I will be using Nano as my primary text editor. You can install it on Ubuntu and Debian using the command listed below.
```
sudo apt install nano -y
```

We can now cd to our home directory and run the listed below command to open our .bashrc file.

```
nano .bashrc
```

# 2. Adding aliases

I recommend putting aliases at the end of your .bashrc file. To get to the end of a file in Nano, press `Ctrl+V` repeatedly until you reach the end. Let's make a command alias for [asciinema](https://asciinema.org/). asciinema is a terminal recorder that I use often to capture command errors and demonstrate my Python scripts. I will call this alias `asc`, as the provided command, `asciinema` is quite lengthy. I will write the below listed code and explain it.

```
# Command aliases
alias asc='asciinema'
```

`alias` signals to Bash that the next word is a command alias. `asc` is the name of the alias. The `=` means the rest of the line defines the alias. `'asciinema'` defines the action that the alias carries out.

Now that we are done, save and close the file in Nano by typing `Ctrl+X`, `y`, and `Enter`.

# 3. Testing it out

Now let's see if our alias works. First, close your current bash session and open a new one. This reloads the .bashrc file with the new configuration.


```
onx@penguin:~$ asc rec
asciinema: recording asciicast to /tmp/tmpaliz0fko-ascii.cast
asciinema: press <ctrl-d> or type "exit" when you're done
onx@penguin:~$ echo hello world!
hello world!
onx@penguin:~$ echo awesome! it works!
awesome! it works!
onx@penguin:~$ exit
exit
asciinema: recording finished
asciinema: press <enter> to upload to asciinema.org, <ctrl-c> to save locally

View the recording at:

    https://asciinema.org/a/lPYgTBguPVz4g27KnuXO5pLTB
```

You can go view the recording for yourself if you like :)


# 4. You're done!

Congratulations! You've learned how to make command aliases in Bash! Have a great day everyone and let me know what I should write about next in the comments!
VS Code: different color themes for different projects 🌈
Tags: todayilearned, vscode, productivity
Published: 2020-12-07 15:54:17

Hi, have you ever worked with multiple VSCode instances? 🔥

It's sometimes difficult to navigate between the different projects when using the same `colorTheme` ...

# The solution:

Maybe you already know it, but **you can have a different theme per workspace/folder** by adjusting the `workbench.colorTheme` in the workspace settings.

1. Open a new VSCode window.
2. Open the project folder where you would like to have a different color theme.
3. Navigate to `File > Preferences > Settings`
4. Select the `Workspace Settings` tab at the top of the settings screen. Anything you edit in here will now be specific to this workspace.
5. Search for `colorTheme` and select the color theme you would like for this specific workspace.

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

# Alternatively...

You can use a VSCode extension called [Peacock](https://marketplace.visualstudio.com/items?itemName=johnpapa.vscode-peacock) wich subtly change the color of your Visual Studio Code workspace. Ideal when you have multiple VS Code instances, use VS Live Share, or use VS Code's Remote features, and you want to quickly identify your editor.

# In the end...

I hope you’ll find these useful for yourself ! It's a game changer for me to boost my productivity 🎉🦥
***
> And you ? What's your favorite **hack** to boost your productivity ? ❤
Story
Tags: programming, productivity, computerscience, webdev
Published: 2020-12-07 13:49:37

FOUR STORIES TO START:
1. Nokia rejected Android.
2. Yahoo rejected Google.
3. Kodak turned down digital cameras.
4. Blockbuster reject Netflix.

LESSONS:
1. Take risks.
2. Accept the change.
3. If you refuse to change over time, it will become obsolete.

TWO MORE STORIES:
1. Facebook takes over WhatsApp and Instagram.
2. Grab takes over Uber in Southeast Asia.

LESSONS:
1. Become so powerful that your competitors become your allies.
2. Reach top position and work smart with the competition.
3. Keep innovating.

TWO MORE STORIES:
1. Colonel Sanders founded KFC at age 65.
2. Jack Ma, who couldn't get a job at KFC,
He founded Alibaba and retired at age 55

LESSONS:
1. Age is just a number.
2. Only those who keep trying will succeed.

FOR THE LAST BUT NO LAST IMPORTANT:
Lamborghini was founded as a result of the revenge of a tractor owner who was insulted by Enzo Ferrari, the founder of Ferrari.

LESSONS:
Never underestimate anyone, ever!
Just keep working hard.
Invest your time wisely.
Don't be afraid to fail.
Let's go!