teleren/devto huggingface dataset:
MIT's Premier Programming Competition, Battlecode, open to all, registration is now open
Published: 2022-12-05 23:22:03

## It's Battlecode Season, open to all

Battlecode 2023 begins on January 9th, 2023!

Register Now  https://play.battlecode.org/register/

## About

MIT's Premier Programming Competition

https://battlecode.org/

See the schedule  https://battlecode.org/schedule.html

## What is Battlecode?

Battlecode is a real-time strategy game, for which you will write an autonomous player. Your player will need to strategically manage a robot army and control how your robots work together to defeat the enemy team. As a contestant, you will learn to use artificial intelligence, pathfinding, distributed algorithms, and communications to make your player as competitive as possible.

Teams are given the Battlecode software and a specification of the game rules in early January. Throughout the month, you will refine your player, and compete in scrimmages and tournaments against other teams. During these tournaments, the autonomous players are pitted against each other in a dramatic head-to-head fashion. At the end of the month, the Final Tournament is played out in front of a live audience at MIT, with the top teams receiving cash prizes. The total prize pool is over $20,000.

## Video of example Battlecode Gameplay

<video width="320" height="240" controls>
  <source src="https://user-images.githubusercontent.com/3156358/205838112-baf40343-8380-4a4c-9018-769b880b4806.mp4" type="video/mp4">
</video>

## MIT Class
Our official MIT course number is 6.9610. Register for the class by IAP to receive 6 units of credit for participating in Battlecode!

## Eligibility
Anyone can write a bot, create a team, and participate in scrimmage matches/rankings. The Sprint Tournaments are open to everyone, but the other tournaments have stricter eligibility rules.

Your team must meet all three conditions by a tournament’s submission deadline to be eligible for it:

- Have uploaded a bot
- Have correctly indicated your eligibility on your Team Profile page
- Have all members upload a resume, at your personal profile page.

Tournament specific eligibility is listed below:

- Sprint Tournaments: All teams are eligible.
- US Qualifier: Teams must consist entirely of US students studying full-time, or in a transition phase.
- International Qualifier: Teams must consist entirely of college students studying full-time, or in a transition phase, where at least one team member is not a US student.
- MIT Newbie Tournament: Teams must consist entirely of MIT students who have never competed in Battlecode before.
- High School Tournament: Teams must consist entirely of US high school students.
- Final Tournament: Teams must have qualified via the US or International Qualifier. The final match of the Newbie and High School tournaments will also be played at the final tournament.

Contact us on Discord or at battlecode@mit.edu if you are unsure of your eligibility.
The Art of Code Generator
Tags: productivity, javascript, openapi, mongodb
Published: 2022-12-05 23:16:48

Write your code by hand, use a an AI, compile it, whatever it was your keys bottom out as they slam ferociously to the switch, your sweaty now as 5’ok approaches your energy is gone and so is your mind… tick tick tick your out of time, the release is out and your just hitting the push button.

If you had maybe saved 5 seconds you could have made the deadline! On top of this, how could you avoid this situation again?

I’ve been here as many years ago, it was close but it was gutting, I have spent much time working out where I went wrong and the key way to overcome it. Automate everything that is worth investing the time in and does not take longer to produce than the task you aim to speed up. A time budget, also helps, triple it!

Now then we come to the crux of this, when you start a project, drop your “I’m so smart pride” grab off the shelf tools and frameworks and create a lean but strong base to build off of.

But what’s the development sinkhole for most applications? I think it’s sticking together the front end to the backend and getting the data!

We discussed in my recent post about using OpenAPI to generate the server mock, the client Rest client and the documentation! That’s a lot of time saved and value added from one single file! 

We have our rest API mocked and connected to our application, that’s now 2 days of development, yes just 2 days, now what about the database? For what I’m doing I will use mongoose because a relational DB doesn’t fit. Mongoose uses schemas to connect to Mongo, although the schemas I already have are in a totally (sensible format) different format, we should have a look around on npm for “openapi-to-mongoose” sadly this didn’t turn up much, just older libs that either connected a long time ago but are now out of date, or the lib has been deleted…
Option two, openAPI to JSON schema to mongoose code, it should be my plan B, it’s not as easy to control this code and the result still would not be generated JavaScript/ typescript files.

I have to write my own, so that’s what I must do. I started wiring up npm script and added my dev-ops code gen script, always horrid to name this type of script… Anyway after Parsing the YAML I loop it, push a template literal with my generated mongoose Model into an array then write each to its own file ready for consumption.


I now have mongoose, documentation, client and mock generated from a single file, what else can I shortcut?
Easy use of multiple environment variables - Cypress 10+ edition
Tags: cypress, environment, typescript, automation
Published: 2022-12-05 23:14:16

A couple of years back (which seemed like an eternity), I wrote this [piece](https://dev.to/poponuts/using-config-files-for-multiple-environment-variables-in-cypress-hn3) where we can use environment json files to easily switch between environment variables in Cypress.

However, since the use of `plugin/index.ts` / `plugin/index.js` is [deprecated](https://docs.cypress.io/guides/references/changelog#10-0-0) (or highly discouraged) now with Cypress 10+, a little tweaking is required to utilise `cypress.config.js` / `cypress.config.ts` without impacting much of the codebase (considering my rusty Cypress skills now). _News flash:_ the legacy `index` file can still be used so read til the end of this 😉.

Though I'm still not a fan but we are using Typescript now 🫢 in my new company so if you are using Javascript, just do some refactoring.

Here's my new code all in `cypress.config.ts` file:
```typescript
const localEnv = {
  "domain": "localhost:8080",
  "description": "This is my local machine!",
  "protocol": "http://",
  "subDirectory": "helloworld"
};

const testEnv = {
  "domain": "test1.domain.com",
  "description": "This is the awesome stage environment",
  "protocol": "https://",
  "subDirectory": "/helloworld"
};

const envConfig = (environment) => {
    switch(environment) {
        case 'local': return localEnv;
        case 'test':
        default: return testEnv;
    }
};

    e2e: {
        env: {
            ...envConfig(process.env.ENVIRONMENT?.toString()), // override with the environment configuration based on the value passed in CI (e.g. ENVIRONMENT=test)
            grepFilterSpecs: true,
        },
    },

```
Note that we can still add other environment variables that is generic to all environments like `grepFilterSpecs` so we don't need to include it in each of the configs. 

Basically, the premise is we can only use `Cypress.env` on the test specs but since `config.config.ts` runs in node as part of the setup process, then we can't use it yet. It can be reached using `process.env`. So, when you use something like `ENVIRONMENT=test npx cypress run` on your CLI, the following will appear on the _Project settings_ of your Cypress runner:
![Image Cypress env variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6174nz342fv5ymqpiip.png)

**BONUS:** The legacy `index` file can still be used with the following lines on `cypress.config` file:
```typescript
const legacyConfig = require('./cypress/plugins/index');
...
    e2e: {
        setupNodeEvents(on, config) {
            return legacyConfig(on, config); // since we still use the old plugin file to override configs
        }

```
10 ideas for SaaS startups in 2023 - by ChatGPT
Tags: openai, ai, gpt3, saas
Published: 2022-12-05 22:49:04

I was just testing out ChatGPT today and here are the 10 ideas for SaaS startups in 2023 that it suggested:

- A cloud-based project management and collaboration platform, with features such as task management, team communication, and file sharing.
- A virtual event platform, enabling organizations to host conferences, workshops, and other events online, with features such as live streaming, networking, and interactive sessions.
- A marketplace for online courses and learning resources, connecting students with educators and subject experts, and providing tools for content creation and delivery.
- A platform for personal finance management, providing tools for budgeting, expense tracking, investment planning, and credit score optimization.
- A platform for remote work and team productivity, with features such as virtual meetings, team task management, and shared workspace tools.
- A platform for social impact and charitable giving, connecting donors with organizations and causes, and providing tools for impact measurement and reporting.
- A platform for content creation and distribution, enabling organizations to create and share videos, images, and other multimedia content across multiple channels.
- A platform for customer feedback and support, providing tools for tracking and managing customer inquiries, complaints, and feedback, and for analyzing customer sentiment.
- A platform for online marketplaces and e-commerce, providing tools for creating, managing, and promoting online storefronts and product listings.
- A platform for health and wellness tracking, providing tools for tracking fitness, nutrition, sleep, and other health metrics, and for providing personalized recommendations and coaching.

What do you think? Some of those are quite spot-on!
Supporting USB C to C Charging and Data Transfer
Tags: hardware, usb, beginners, tutorial
Published: 2022-12-05 22:31:09

Have you ever had a device that has a USB Type C port on it, but it doesn't seem to charge using USB C to C cables? This seems to be a common problem to us. Just the other day, we were filming and attempting to recharge one of our microphones, and we were unable to use the USB type C Power Delivery brick that was sitting right in front of us. This is truly infuriating, especially once you know the answer. Today, we're going to dive into the USB Type C Legacy Device specification.

## The Physical Connectors

The most barebones physical USB C connection, USB 2.0, has twelve pins. MicroUSB has five. 
This could be a point of confusion for new or inexperienced designers using USB Type C for the first time. One may simply assume that you can connect the pins straight through, as you would for MicroUSB, and that it will work just fine. And, if they haven't tested thoroughly, they may find this to be the case. To support USB A to C, you need only connect Voltage, Ground, and USB Data. However, upon connecting a USB C to C cable, you'll find exactly zero volts at the output. This is because the USB C controller has no idea that anything was just plugged in at all, so it won't provide power, even if the device has it's USB Data lines connected.

## The CC Lines

This is where the CC lines come in. The UCB C controller uses the CC lines to establish the protocol with which to communicate with the connected device. For our purposes, this will be a power delivery request for 5v, 9v, 12v, or 20v [with 48v soon to come]. This requires an extra integrated circuit, or microcontroller to establish this communication though. For legacy devices where a simple 5v is needed however, you can simply stick two 5.1k Ohm pull-down resistors on the CC lines. Each line needs it's own resistor, as the specification uses these lines to determine the 'direction' the plug was inserted. This tells the controller that it's communicating to a legacy device and that it needs to provide 5v up to 1.5A or 3A depending on the source's capabilities.  
  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spwkn116nwl880deq5hl.png)

## The Bottom Line

And of course, what does this cost? Literally nothing. For a mere 100 5.1k Ohm resistors, we pay the unit price of **$0.0004**. That's $0.04 for the entire order. Each device needs two of these resistors, so we've spent less than a ***single cent*** to support the proper USB C legacy specification. This allows both USB A to C cables, and USB C to C cables to charge our connected device. If there's one thing you take away from this, PLEASE include those two tiny resistors in any of your designs that use USB C for charging. And Please, Let's get rid of MicroUSB entirely. We want one cable to rule them all.
Elixir and SMS tutorial
Tags: elixir, sms, textbelt, genserver
Published: 2022-12-05 22:30:42

This tutorial will use the [TextBelt](https://textbelt.com/) SMS service. Sign up and get an API key in order to make this fully work.

Create Project and go into that directory

```
mix phx.new sms_demo --no-ecto
cd sms_demo
```

Add HTTPoison and Poison dependencies to the project
```
#Path mix.exs

defp deps do
	[
		...
		{:poison, "~> 4.0"},
		{:httpoison, "~> 1.8"},
		...
```


Get dependencies again
```
mix deps.get
```


Create Handler for SMS sending / receiving

```
# Path: lib/sms_demo/sms_handler.ex

defmodule SmsDemo.SmsHandler do
	use GenServer

	def send_message(to_phone, message) do
		GenServer.cast(SmsDemo.SmsHandler, {:send, {to_phone, message}})
	end

	def receive_message(from_phone, message) do
		GenServer.cast(SmsDemo.SmsHandler, {:receive, {from_phone, message}})
	end

	def start_link(_) do
		GenServer.start_link(__MODULE__, [], name: __MODULE__)
	end

	def init([]) do
		{:ok, %{}}
	end

	def handle_cast({:send, {phone, message}}, state) do
		textbelt_url = "https://textbelt.com/text"
		textbelt_key = Application.get_env(:sms_demo, :textbelt_key)
		replyWebhookUrl = Application.get_env(:sms_demo, :webhook_url)

		params = %{
			phone: phone,
			message: message,
			key: textbelt_key,
			replyWebhookUrl: replyWebhookUrl
		}

		HTTPoison.post(textbelt_url,
			Poison.encode!(params),
			[{"Content-type", "application/json"}])

		{:noreply, state}
	end

	def handle_cast({:receive, {phone, message}}, state) do
		# TODO: Do something with the message

		{:noreply, state}
	end
end
```

Update Application defintion to spawn the above Handler

```
# Path: lib/sms_demo/application.ex

def start(_type, _args) do
	children = [
		...
		SmsDemo.SmsHandler,
		... 
```


Add WebHook Controller
```
# Path: lib/sms_demo_web/controllers/webhook_controller.ex
defmodule SmsDemoWeb.WebhookController do
  alias SmsDemo.SmsHandler
  use SmsDemoWeb, :controller

  def hook(conn, params) do
    SmsHandler.receive_message(params["fromNumber"], params["text"])

    json(conn, %{status: "ok"})
  end
end

```

Uncomment the `/api` scope in Router and add our hook
```
# Path: lib/sms_demo_web/router.ex
scope "/api", SmsDemoWeb do
	pipe_through :api

	post "/hook", WebhookController, :hook
end
```


Test Webhook locally

```
$ mix phx.server

$ curl -X POST http://localhost:4000/api/hook \
       -H 'Content-Type: application/json' \
       -d '{"fromNumber": "+1555123456", "text": "Here is my reply"}'
       
```

That's all the plumbing. Now we can make a little joke telling interaction in which we want to:
```
1. Hit a web endpoint api and pass in a phone number to tell a joke to
2. Send via SMS the first part of the joke
3. Expect an SMS response of "Why?"
4. Send via SMS the second part of the joke
```

Check out the finished project on github at 
`https://github.com/byronsalty/sms_demo`
Implement IAM Auth to RDS PostgreSQL in AWS
Tags: aws, cloud, devops, tutorial
Published: 2022-12-05 22:11:25

## **From Secrets Manager to IAM**

Recently I was tasked with removing all of our secrets from secret manager that were in our 300+ lambdas and switch to using IAM auth by generating tokes instead of having secrets in our lambdas.

## **A few simple steps to get you going**

### To implement Identity and Access Management (IAM) authentication to Amazon RDS for PostgreSQL, you can follow these steps:

1. Sign in to the AWS Management Console and open the Amazon RDS console.

2. Select the PostgreSQL instance you want to enable IAM authentication for.

3. Under the Configuration tab, select the IAM DB authentication option.

4. Select the Enable IAM DB authentication option and choose the IAM role that you want to use for authentication.

5. Click the Apply changes button to save the changes.

6. To connect to your PostgreSQL instance using IAM authentication, you will need to use the IAM credentials (access key and secret key) of the IAM user or role that you specified in step 4.

7. You can use the following connection string to connect to your PostgreSQL instance using IAM authentication:

Copy code

```
postgresql://<IAM_USER>:<IAM_SECRET_KEY>@<RDS_ENDPOINT>:<RDS_PORT>/<DB_NAME>
Replace <IAM_USER>, <IAM_SECRET_KEY>, <RDS_ENDPOINT>, <RDS_PORT>, and <DB_NAME> with the appropriate values for your setup.
```

With these steps, you should be able to enable and use IAM authentication for your Amazon RDS for PostgreSQL instance. Keep in mind that you will need to have the appropriate IAM permissions to perform these steps. You can find more detailed instructions in the Amazon RDS for PostgreSQL documentation. This is a very basic intro to the steps but should get you started. If you have any questions please just ask me!
Simple Stock System In PHP With Source Code
Tags: webdev, php, programming, beginners
Published: 2022-12-05 21:44:02

To use this system first of you need to create an account. For that, you can simply sign up to the system and later use the login credentials to use the system. Since most of this is from the user perspective, there is nothing much functionality to this system. The user can simply add stock and also can keep their record. Not only this the users can join in the chat room for more productivity.

Design of this project is pretty simple so that the user won’t find any difficulties while working on it. This System in PHP helps in easy management of inventories and stocks. To run this project you must have installed virtual server i.e XAMPP on your PC (for Windows). Use for educational [satta matka](https://sattamatkaji.net) purposes only! For the project demo, have a look at the image slider below.

How To Run??
After Starting Apache and MySQL in XAMPP, follow the following steps

1st Step: Extract file
2nd Step: Copy the main project folder
3rd Step: Paste in xampp/htdocs/

Now Connecting Database

4th Step: Open a browser and go to URL “http://localhost/phpmyadmin/”
5th Step: Then, click on the databases tab
6th Step: Create a database naming “nockbase” and then click on the import tab
7th Step: Click on browse file and select “nockbase.sql” file which is inside “DATABASE” folder
8th Step: Click on go.

9th Step: Open a browser and go to URL “http://localhost/market/”
Analytics with Next.js 13
Tags: nextjs, analytics, fathom, react
Published: 2022-12-05 21:42:04

---
title: Analytics with Next.js 13
published: true
tags: nextjs,analytics,fathom,react
canonical_url: https://sdorra.dev/posts/2022-11-11-next-with-fathom
cover_image: https://images.unsplash.com/photo-1551288049-bebda4e38f71?fit=crop&w=1000&h=420
---

We will explore how to integrate analytic tools such as [Google Analytics](https://analytics.google.com), [Matomo](https://matomo.org) or [Fathom](https://usefathom.com/) with the Next.js 13 app directory. In this article we will use [Fathom](https://usefathom.com/), but the same principles could be applied to [Google Analytics](https://analytics.google.com), [Matomo](https://matomo.org) or similar tools.

The new app directory of Next.js 13 comes with a lot of exiting new features, but the new router (`next/navigation`) unfortunately does not support events.

So we have to track route changes by ourselves. My first idea was to use the history api, but the history api does not send events for route changes!

The last option we have now is to override the pushState method and send an custom event:

```javascript
var pushState = history.pushState;
history.pushState = function (state) {
  var result = pushState.apply(history, arguments);
  window.dispatchEvent(new Event("routeChange", state));
  return result;
};
```

The snippet above overrides the `pushState`, calls the original function and sends a `routeChange` event afterwards.

## Next.js

In Next.js we could use our method with the `Script` tag:

```tsx
import { FC, PropsWithChildren } from "react";
import Script from "next/script";
import Analytics from "./Analytics";

const RootLayout: FC<PropsWithChildren> = ({ children }) => (
  <html>
    <body>
      <main>{children}</main>
      <Analytics />
      <Script id="onRouteChange">{`
        (function (history) {
          var pushState = history.pushState;
          history.pushState = function(state){
            var result = pushState.apply(history, arguments);
            window.dispatchEvent(new Event("routeChange", state));
            return result;
          };
        })(window.history);
      `}</Script>
    </body>
  </html>
);

export default RootLayout;
```

And now we are able to notify fathom about the route changes. We do this with a custom component (`Analytics`), which is used in our root layout (see snippet above).

```tsx
"use client";

import { useEffect } from "react";
import * as Fathom from "fathom-client";

const Analytics = () => {
  useEffect(() => {
    Fathom.load("YOUR_FATHOM_TRACKING_CODE", {
      includedDomains: ["yourdomain.com"],
    });

    const onRouteChange = () => Fathom.trackPageview();

    window.addEventListener("routeChange", onRouteChange);
    return () => window.removeEventListener("routeChange", onRouteChange);
  }, []);

  return null;
};

export default Analytics;
```

We have to use a custom component instead of a hook in order to annotate the component with [use client](https://beta.nextjs.org/docs/rendering/server-and-client-components#client-components).
github action para deploy de app vuejs 3
Tags: vue, github
Published: 2022-12-05 21:36:06

El push en un repositorio github de una aplicación vuejs puede perfectamente disparar una acciòn que produzca un build y deje el directorio listo para descargar y "deployar" en otro servidor. 

Esta [aplicación](https://bibliotecas.uncuyo.edu.ar/cdi) simple de buscador utilizando una api de #vufind es "compilada" por github en forma automática cuando se hace un push en la rama main.

Con la siguiente "action" de github se realiza un build en base a una maquina virtual ubuntu y se utilizan tres actions más: 
- una que realiza el checkout de la rama main.
- una que instala node 
- y https://github.com/actions/upload-artifact  que toma el directorio cdi y lo arma como un "artifact" en un zip descargable. 

Todo esto en forma automática y con un log qque permite ver los posibles errores. 

```yaml
name: DEPLOY TO cdi

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node: [ 18 ]
    name: Node ${{ matrix.node }} sample
    steps:
      - uses: actions/checkout@v3
      - name: Setup node
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node }}
      - run: npm i @vue/cli-service
      - run: npm run build
      - uses: actions/upload-artifact@v3
        with:
           name: my-dist
           path: cdi # or path/to/artifact      

```
[Github repo](https://github.com/SIDUNCUYO/buscadorCDI)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a58u3nd2wrdli0fltbne.png)