DEV Community

Cover image for Share a code snippet in any programming language and describe what's going on

Share a code snippet in any programming language and describe what's going on

Ben Halpern on April 11, 2022

Collapse
 
ben profile image
Ben Halpern

I'll go first with Ruby

class String
  def like_a_cow
   "Moo #{self} mooooo"
  end
end

"Hello".like_a_cow
=> "Moo Hello mooooo"
Enter fullscreen mode Exit fullscreen mode

Classes in Ruby can be easily modified. The above code adds the like_a_cow method to String... So now the whole program can make a string "moo", like above.

Collapse
 
maxart2501 profile image
Massimo Artizzu

In JavaScript it's:

String.prototype.like_a_cow = function() {
  return `Moo ${this} mooooo`;
};
"Hello".like_a_cow()
> "Moo Hello mooooo"
Enter fullscreen mode Exit fullscreen mode

I wonder how many languages allow this?

Collapse
 
ryencode profile image
Ryan Brown • Edited

C# allows this,


    public static class StringExtension
    {
        public static string LikeACow(this string self)
        {
            return $"Moo {self} mooooo";
        }
    }
Enter fullscreen mode Exit fullscreen mode

you can now use this as

Console.WriteLine("Hello".LikeACow());
Enter fullscreen mode Exit fullscreen mode

I use extensions a lot on sealed library classes to add Quality Of Life things. One example is creating cleaner methods for adding parameters to SQLClient ClientCommand objects as one liners instead of multi-command monstrosities. (ok, they aren't that big, but do look unclean)

Thread Thread
 
lionelrowe profile image
lionel-rowe

I think it's different (safer) in C# though, right? Like you need to add using <namespace> for the new methods to be accessible. So it's not true monkey patching, which is generally dangerous and best avoided.

Thread Thread
 
ryencode profile image
Ryan Brown

Indeed you would need to use the containing namespace. And are likely safer as it would be pretty hard to modify the behaviour of code outside of your intended changes. (I think you would have to try very hard to have any affect outside of your explicit calls to the extension methods)

I won't claim to know much about TRUE monkey patching, but wikipedia's Extension Methods and Monkey Patching articles do reference each other in suggestive ways. ;)

Collapse
 
arjunsahlot profile image
Arjun

Python:

class str(str):
    def like_a_cow(self):
        return f"Moo {self} mooooo"

str("Hello").like_a_cow()
> "Moo Hello mooooo"
Enter fullscreen mode Exit fullscreen mode

I should add that this is not good practice. str is a built in function and you should not override it.

Collapse
 
kenbellows profile image
Ken Bellows

I'll do you one better: if you define a dynamic getter using Object.defineProperty, you can make it look exactly like the Ruby example:

Object.defineProperty(String.prototype, 'likeACow', {
    get() {
        return `Moo ${this} mooooo`
    }
})

'Hello'.likeACow
> 'Moo Hello mooooo'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jmfayard profile image
Jean-Michel πŸ•΅πŸ»β€β™‚οΈ Fayard • Edited
fun String.likeACow() = "Moo $this mooo"
Enter fullscreen mode Exit fullscreen mode

Same thing in Kotlin, super handy.

EDIT: A big advantage with for example the JavaScript version monkey-patching String.prototype, is that the String class is not modified everywhere in your codebase.

It works like a normal function, you import the new function only if and where you need it. See kotlinlang.org/docs/extensions.htm...

Collapse
 
silverhairs profile image
Boris Kayi • Edited

In Dart it's

extension on String{
 String get like_a_cow => 'Moo $this mooooo';
}

"Hello".like_a_cow;
=> "Moo Hello mooooo"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leopfeiffer profile image
Leo Pfeiffer

Similar in Scala:

extension(str: String) {
  def like_a_cow = s"Moo ${str} mooooo"
}

scala> "Hello".like_a_cow
val res0: String = Moo Hello mooooo
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maowtm profile image
maowtm

In Rust you can add functions to other types with traits. This actually adds the like_a_cow function for all types that are printable, including strings. You have to use the trait though.

pub trait LikeACow {
    fn like_a_cow(&self) -> String;
}

impl<T: std::fmt::Display> LikeACow for T {
    fn like_a_cow(&self) -> String {
        format!("Moo {} mooooo", &self)
    }
}

fn main() {
    // need to `use LikeACow;` if used in other modules, but not here.
    let s = "hello";
    println!("{}", s.like_a_cow());
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sanzstez profile image
Alexandr Stets

It is bad practice to do such things. Better use

module Extensions
  refine String do
    def like_a_cow
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

and add in you class

use Extensions
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ

Nice example, but I think it could be refined somewhat

using (Module.new do
  refine String do
    def like_a_duck
      "#{self} quack quack"
    end
  end
end)

puts "Hello".like_a_duck
Enter fullscreen mode Exit fullscreen mode
Collapse
 
auroratide profile image
Timothy Foster

Some regex I wrote in 2018:

/^(?:\*|\d\.)\s(.*)\r?\n([ \t]+(?:\*|\d\.)\s(?:.|\r?\n[ \t]+(?:\*|\d\.))*)/
Enter fullscreen mode Exit fullscreen mode

I've stared at it for 5 minutes and still can't tell you what's happening πŸ™ƒ

Collapse
 
chrisgreening profile image
Chris Greening

Dear programmer: When I wrote this code, only god and I knew how it worked. Now only god knows it! Therefore, if you are trying to optimize this routine and it fails (most surely), please increase this counter as a warning for the next person: total hours wasted here= 254

Collapse
 
tracygjg profile image
Tracy Gilmore

If you throw the expression into something like Debuggex it can map out the routes through the expression, as follows.

RegExp diagram

However, whilst this shows what is happening it does not indicate why.

Collapse
 
auroratide profile image
Timothy Foster

Now that I'm staring at this chart, I'm recalling that at some point I was trying to parse markdown. Pretty sure this is looking for nested lists:

* Hello!
  1. A nested ordered list
Enter fullscreen mode Exit fullscreen mode

Though, it is interesting to me that the initial * or \d\. is not captured; one would think it'd be important to distinguish between an unordered and ordered list...

Thread Thread
 
tracygjg profile image
Tracy Gilmore

I studied the screenshot I attached to my comment and came to the same conclusion but it looks to me the expression might be more complicated than it needs to be - without fully understanding the context of course.

Collapse
 
bbrtj profile image
bbrtj

It searches for indented sublists, like:

1. abc
  * def
  * ghi
Enter fullscreen mode Exit fullscreen mode

You're welcome.

Collapse
 
jamesthomson profile image
James Thomson

Anyone that can read this and know exactly what's going on is clearly not human

Collapse
 
jeremyf profile image
Jeremy Friesen

Lots of (?:\*|\d\.) repeated: non-capture region of either * or (any numeral followed by any character).

Collapse
 
3kiruthick profile image
3Kiruthick

Which purpose u wrote this regex

Collapse
 
lionelrowe profile image
lionel-rowe

PHP

function lets_do_some_math($n) {
    return ($n / 2) / ($n / 2);
}

$a = lets_do_some_math(10);
$b = lets_do_some_math(11);

printf('%d %d %s', $a, $b, $a === $b ? 'yes' : 'no');
Enter fullscreen mode Exit fullscreen mode

Prints 1 1 no.

In PHP, the division operator / returns an integer if the two operands are both integers and divide exactly, and a float in all other cases. (10 / 2) thus gives int(5), while (11 / 2) gives float(5.5). Then, in the next division step, 5 / 5 gives int(1), while 5.5 / 5.5 gives float(1).

PHP's language design is truly astounding.

Collapse
 
rajarshi profile image
Rajarshi Bandopadhyay • Edited

All right, let's see if you guys have a clue about this:

docker commit `docker ps -a |\
    head -n2 |\
    tail -n1 |\
    cut -d" " -f1` $1:$2
Enter fullscreen mode Exit fullscreen mode

This is a single line of shellscript code written over three lines for readability. Notice that it employs backticks inside the code.

A lot is happening here, obviously. FIrst of all, the $1 and $2 will be replaced by the first and second command line argument respectively. So if you are invoking this script with the command line arguments repo and tag, this will translate to:

docker commit `docker ps -a |\
    head -n2 |\
    tail -n1 |\
    cut -d" " -f1` repo:tag
Enter fullscreen mode Exit fullscreen mode

Next, note the backticks inside the command. The portion between the backticks - will first be evaluated. The result of this evaluation will then replace the entire thing inside the backticks.

Now, what does the portion inside the backtick do? Well, it has four parts:

Part 1 is docker ps -a, which yields a list of Docker images and their details:

CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS                     PORTS     NAMES
20d03205fe06   ubuntu:20.04   "bash"                   3 seconds ago   Exited (0) 2 seconds ago             bold_feynman
dcf460b2c4ff   07cd54330caf   "/bin/sh -c 'tar xzf…"   4 minutes ago   Up 4 minutes                         blissful_liskov
Enter fullscreen mode Exit fullscreen mode

This output is then piped into part 2. Piping is a special construct in Shellscript, which takes the string output of one command and puts it into the string input of the next command. So if command-1 prints 2+2+2 into the output, and command-2 evaluates mathematical expressions from keyboard and prints the output, then command-1 | command-2 will basically make the 2+2+2 from the first command become the input of the second, and we will only see the final output - 6.

The output of the first command is being piped into the second command, which is head -n2. The head command snipes out the first n lines from a file (or text input), and prints it. When fed the lines of details of different classes at the input, the head command will print the first n lines and then ignore the rest. We specify n with the -n2 flag, and its value is set to 2.

So the head command will print the first two lines from the table:

CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS                     PORTS     NAMES
20d03205fe06   ubuntu:20.04   "bash"                   3 seconds ago   Exited (0) 2 seconds ago             bold_feynman
Enter fullscreen mode Exit fullscreen mode

Notice that this includes the heading row and the details of the latest image - in this case, one which was created just three seconds before this command was run (I admit to having created it just to demonstrate this snippet).

The next command in the pipe is tail, and this command will ignore all but the last n lines from the input, and print those last n lines. In this case, we invoke it with tail -n1, thereby setting n to 1. The last one line will be printed.

20d03205fe06   ubuntu:20.04   "bash"                   3 seconds ago   Exited (0) 2 seconds ago             bold_feynman
Enter fullscreen mode Exit fullscreen mode

Or at least, tail will try to print it. But its own printed output has been further piped into the cut command. This command does something quite whacky: it takes two arguments, known as the delimiter and the selected columns. The delimiter has to be a char and the selected columns is a comma-separated sequence of numbers. In case a single number is provided, that single number is interpreted as a single-length sequence of numbers.

What cut does is that it splits each line of its input into parts, separated by the delimiter. It then takes the specific values which correspond to the selected columns, and then prints only those values which have been selected.

For instance, in this case, it will split the input string (which is a single line) by the " " space character, and then take out the first member of the resulting array of substrings. Of course, this effectively means that it will only pick the first word of the line. And in this case, that word is the container ID of the most recently run container:

20d03205fe06
Enter fullscreen mode Exit fullscreen mode

This ID is the final output of the entire portion inside the backticks, and given the way Shellscript works, the entire portion inside backticks will simply be replaced by this one container ID number:

docker commit 20d03205fe06 repo:tag
Enter fullscreen mode Exit fullscreen mode

Which is the final form of the command, and it is executed. So the command does this:

It commits the most recently run container as an image with the name and tag provided as command line arguments to the script

Collapse
 
pandademic profile image
Pandademic

Wow.... That's actually quite useful

Collapse
 
rajarshi profile image
Rajarshi Bandopadhyay

Thank you. I use this one a lot, though I typically write it out in just one line.

Collapse
 
sm0ke profile image
Sm0ke • Edited

Nothing in c++

int main() { return 0; }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dhravya profile image
Dhravya

Here's a Rust moment, I tweeted it today lol

Collapse
 
jroes profile image
Jon Roes

Is your text editor or some plugin showing the return types of the functions in the chain? That's pretty cool. What's the plugin/editor?

Collapse
 
dhravya profile image
Dhravya

I'm using VScode with rust-analyzer extension

Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez • Edited

This is an F# script that posts a Post like object to the json placeholder API and deserializes the json response to a Post.

you can copy into a file and run it like this:

  • dotnet fsi ./filename.fsx
#r "nuget: FsHttp" // specify the http library

// open the required namespaces
open FsHttp
open FsHttp.DslCE
open System.Text.Json

// define the shape of the data
// these are known as Records in F#
type Post =
    { userId: int
      id: int
      title: string
      body: string }

// In F# records can't have null values for most types
// so we use an anonymous record (`{| |}` instead of `{}`)
// because we don't have an id value yet
let payload =
    JsonSerializer.Serialize(
        {| userId = 1
           title = "Sample"
           body = "Content" |}
    )

let response =
    // declare the request
    http {
        POST "https://jsonplaceholder.typicode.com/posts"
        body
        json payload
    }
    // send the request, it can also be done asynchronously
    |> Request.send
    // get the stream back (rather than downloading the response in bytes/string
    |> Response.toStream
    // deserialize it using .NET base class library classes like JsonSerializer
    |> JsonSerializer.Deserialize<Post>

// you can now check the response in the console
printfn "%A" response
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ
private["_min", "_max", "_mid", "_target", "_kit"];
_target = random(_sum);
_min = 0; _max = count _array -1;

while { _min != _max-1 } do {
   _mid = floor (_min + (_max - _min) / 2);
   if ( (_array select _mid select 0) <= _target )
      then { _min = _mid }
      else { _max = _mid };
};
Enter fullscreen mode Exit fullscreen mode

Does a binary search through an array and finds the first element with a value greater than a random target at index 0.

This is a part of a script that chooses a random set of items to put in a supply box where each item set can have a weight assigned to it based on how valuable the items are (higher weight means more common)

Collapse
 
pandademic profile image
Pandademic

what language is that?

Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ

SQF :D

Collapse
 
yassineldeeb profile image
Yassin Eldeeb πŸ¦€

I'm gonna bet on Brainf*ck, so here's mine.

>+++++[>+++++++<-]>.<<++[>+++++[>+++++++<-]<-]>>.+++++.<++[>-----<-]>-.<++
[>++++<-]>+.<++[>++++<-]>+.[>+>+>+<<<-]>>>[<<<+>>>-]<<<<<++[>+++[>---<-]<-
]>>+.+.<+++++++[>----------<-]>+.<++++[>+++++++<-]>.>.-------.-----.<<++[>
>+++++<<-]>>.+.----------------.<<++[>-------<-]>.>++++.<<++[>++++++++<-]>
.<++++++++++[>>>-----------<<<-]>>>+++.<-----.+++++.-------.<<++[>>+++++++
+<<-]>>+.<<+++[>----------<-]>.<++[>>--------<<-]>>-.------.<<++[>++++++++
<-]>+++.---....>++.<----.--.<++[>>+++++++++<<-]>>+.<<++[>+++++++++<-]>+.<+
+[>>-------<<-]>>-.<--.>>.<<<+++[>>++++<<-]>>.<<+++[>>----<<-]>>.++++++++.
+++++.<<++[>---------<-]>-.+.>>.<<<++[>>+++++++<<-]>>-.>.>>>[-]>>[-]<+[<<[
-],[>>>>>>>>>>>>>+>+<<<<<<<<<<<<<<-]>>>>>>>>>>>>>>[<<<<<<<<<<<<<<+>>>>>>>>
>>>>>>-]<<+>[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-
[-[-[-[-[-[-[-[-[-[-[-[<->[-]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]<[
<<<<<<<<<<<<[-]>>>>>>>>>>>>[-]]<<<<<<<<<<<<[<+++++[>---------<-]>++[>]>>[>
+++++[>+++++++++<-]>--..-.<+++++++[>++++++++++<-]>.<+++++++++++[>-----<-]>
++.<<<<<<.>>>>>>[-]<]<<<[-[>]>>[>++++++[>+++[>++++++<-]<-]>>++++++.-------
------.----.+++.<++++++[>----------<-]>.++++++++.----.<++++[>+++++++++++++
++++<-]>.<++++[>-----------------<-]>.+++++.--------.<++[>+++++++++<-]>.[-
]<<<<<<<.>>>>>]<<<[-[>]>>[>+++++[>+++++++++<-]>..---.<+++++++[>++++++++++<
-]>.<+++++++++++[>-----<-]>++.<<<<<<.>>>>>>[-]<]<<<[-[>]>>[>+++[>++++[>+++
+++++++<-]<-]>>-.-----.---------.<++[>++++++<-]>-.<+++[>-----<-]>.<++++++[
>----------<-]>-.<+++[>+++<-]>.-----.<++++[>+++++++++++++++++<-]>.<++++[>-
----------------<-]>.+++++.--------.<++[>+++++++++<-]>.[-]<<<<<<<.>>>>>]<<
<[<+++[>-----<-]>+[>]>>[>+++++[>+++++++++<-]>..<+++++++[>++++++++++<-]>---
.<+++++[>----------<-]>---.<<<<<<.>>>>>>[-]<]<<<[--[>]>>[>+++++[>+++++++++
<-]>--..<+++++++[>++++++++++<-]>-.<+++++[>----------<-]>---.[-]<<<<<<.>>>>
>]<<<[<+++[>----------<-]>+[>]>>[>+++[>++++[>++++++++++<-]<-]>>-.<+++[>---
--<-]>.+.+++.-------.<++++++[>----------<-]>-.++.<+++++++[>++++++++++<-]>.
<+++++++[>----------<-]>-.<++++++++[>++++++++++<-]>++.[-]<<<<<<<.>>>>>]<<<
[--[>]>>[>+++++[>+++++[>+++++<-]<-]>>.[-]<<<<<<<.>>>>>]<<<[<++++++++++[>--
--------------<-]>--[>]>>[<<<<[-]]]]]]]]]]]>>]<++[>+++++[>++++++++++<-]<-]
>>+.<+++[>++++++<-]>+.<+++[>-----<-]>.+++++++++++.<+++++++[>----------<-]>
------.++++++++.-------.<+++[>++++++<-]>.<++++++[>+++++++++++<-]>.<+++++++
+++
Enter fullscreen mode Exit fullscreen mode

Please don't ask what it does, cause I've no idea, it just looks cool..I guess.

Collapse
 
ashleyjsheridan profile image
Ashley Sheridan • Edited
10 PRINT "You been hacked!"
20 GOTO 10
Enter fullscreen mode Exit fullscreen mode

BASIC hacking

Collapse
 
ben profile image
Ben Halpern

whoa

Collapse
 
crowdozer profile image
crowdozer
// javascript 

{
  const x = 1
  {
    const x = 2 // no error
    {
      console.log(x) // 2
      const x = 3 
      console.log(x) // 3
    }
  }
}

console.log(x) // undefined
Enter fullscreen mode Exit fullscreen mode

In javascript, const denotes a read-only variable. If you try to reassign it, you'll get a "SyntaxError: Identifier has already been declared"

However, each braced segment is treated as a new scope. This is most obvious with functions and control structures like if (true) { ... }, but it's not immediately obvious to people that you can arbitrarily create new scopes anywhere. Switch statements are a good place to use them.

Collapse
 
moopet profile image
Ben Sinclair

Const doesn't denote read-only, it only means you can't reassign it in the same scope. You can mutate it all you want (provided it's a type that's mutable in the first place)

const x = [1, 2, 3];

x.push(4);
delete x[0];

// [ <empty slot>, 2, 3, 4 ]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
crowdozer profile image
crowdozer • Edited

I worded it a bit slopy, a "read-only reference to a value" according to MDN, but it's all semantics as long as we understand how it works =]

Collapse
 
pothieug profile image
Gilles Pothieu

Wow, thanks for the hint !

Collapse
 
gajananpp profile image
Gajanan Patil

Custom characters on 16x2 LCD Display using LiquidCrystal library of Arduino

byte heart[8] = {
0b00000,
0b01010,
0b11111,
0b11111,
0b01110,
0b00100,
0b00000,
0b00000
};

lcd.createChar(0, heart);
lcd.setCursor(0, 1);
lcd.write(byte(0));
Enter fullscreen mode Exit fullscreen mode

displays on lcd as
LCD Character

used to spend whole day creating different custom chars and animations

Collapse
 
warwait profile image
Parker Waiters

JavaScript

parseInt("fuck", 16);
πŸ‘‰ 15
parseInt("fart", 16);
πŸ‘‰ 250
parseInt("shit", 16);
πŸ‘‰ NaN
Enter fullscreen mode Exit fullscreen mode

JavaScript will parse a string until it gets to an character it can't parse and then return the value. In this example, by parsing hexadecimal, we get f in the first example, fa in the second, but nothing in the third because s isn't a valid hex character.

Collapse
 
w3ndo profile image
Patrick Wendo

Classic FizzBuzz, but in a language a friend and I worked on called Swahili-lang. Uses Swahili semantics with a JS-lik syntax,

You can find out more about it here

shughuli fizzBuzz(nambari){
  kwa i = 1 mpaka (nambari+1){
    kama (i % 15 == 0){
      andika (Jina(i) + ": Fizz Buzz")
    } au (i % 5 == 0){
      andika (Jina(i) + ": Buzz")
    } au (i % 3 == 0){
      andika (Jina(i) + ": Fizz ")
    } sivyo {
      andika (i)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
saptakbhoumik profile image
SaptakBhoumik
def fib(n:int) -> int :
    if n <= 0:
        return 1
    return fib(n-1) + fib(n-2)

def main():
    count:int = 0
    res:int = 0

    while count < 40:
        res = fib(count)
        count++
Enter fullscreen mode Exit fullscreen mode

Recursive fib in peregrine which is a python like language I have been working on:). Check it out :- github.com/peregrine-lang/Peregrine

Collapse
 
pandademic profile image
Pandademic

nice ! look's great!

Collapse
 
saptakbhoumik profile image
SaptakBhoumik

Thanks:)

Collapse
 
maxart2501 profile image
Massimo Artizzu

This is messed up and you shouldn't do it, but we can sort-of have pattern matching in JavaScript:

switch (true) {
  case 200 <= status && status < 300: {
    console.log('Success!');
    break;
  }
  case status === 418: {
    console.log("I'm a πŸ«–");
    break;
  }
  default:
    throw Error('Something went wrong!');
}
Enter fullscreen mode Exit fullscreen mode

The trick here is that the first case that equals the argument of the switch statement is executed. So, since the argument is true, only the first case that have an argument that evaluates to true is executed. Boom!

Also, no. Don't do this. Nobody expects this.

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability.

Collapse
 
booleanhunter profile image
Ashwin Hariharan • Edited

A snippet that I use in my projects:

function convertArrayToObject (array, key) {
    return array.reduce((accumulator, current) => {
        accumulator[current[key]] = current;
        return accumulator;
    }, {});
}
Enter fullscreen mode Exit fullscreen mode

What does this do?

As the name suggests, it converts an array into an object.

When should I use this

Often when you have a big list of objects and you need to look up a value in one of those objects very often, it is useful to transform the list into a object beforehand. It's more efficient that way, than having to do a find element operation by iterating over an array every single time.

Example

// Suppose I have an array of objects, like this:
const tweets = [
    { id: "01", text: "What's your hobby"},
    { id: "02", text: "What are you doing during COVID-19" },
    { id: "03", text: "Share some good fiction books" },
];

const tweetsById = convertArrayToObject(tweets, "id");

// Now I can do this:
console.log(tweetsById["01"].name); // prints "What's your hobby"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
infowesley profile image
Wesley Reis

dev.to formatting messes up the code, but...

Perl:




# author: ???
                                          $==$';
                                         $;||$.| $|;$_
             ='*$ (                  ^@(%_+&~~;# ~~/.~~
         ;_);;.);;#)               ;~~~~;_,.~~,.* +,./|~
    ~;_);@-,  .;.); ~             ~,./@@-__);@-);~~,.*+,.
  /|);;;~~@-~~~~;;(),.           ;.,./@,./@,.;_~~@-););,.
  ;_);~~,./@,.;;;./@,./        |~~~~;#-(@-__@-__&$#%^';$__
   ='`'&'&';$___="```

`"  |"$[`$["|'`%",';$~=("$___$__-$[``$__"|
              "$___"|       ("$___$__-$[.%")).("'`"|"'$["|"'#").
        '/.*?&([^&]*)&.*/$'.++$=.("/``"|"/$[`"|"/#'").(";`/[\\`\\`$__]//`;"
        |";$[/[\\$[\\`$__]//`;"|";#/[\\\$\\.$__]//'").'@:=("@-","/.",
       "~~",";#",";;",";.",",.",");","()","*+","__","-(","/@",".%","/|",
        ";_");@:{@:}=$%..$#:;'.('`'|"$["|'#')."/(..)(..)/".("```"|"``$["|
        '#("').'(($:{$'.$=.'}<<'.(++$=+$=).')|($:{$'.$=.'}))/'.("```;"|
        "``$[;"|"%'#;").("

````'$__"|"%$[``"|"%&!,").${$[};`$~$__>&$=`;$_=
       '*$(^@(%_+&@-__~~;#~~@-;.;;,.(),./.,./|,.-();;#~~@-);;;,.;_~~@-,./.,
        ./@,./@~~@-);;;,.(),.;.~~@-,.,.,.;_,./@,.-();;#~~@-,.;_,./|~~@-,.
          ,.);););@-@-__~~;#~~@-,.,.,.;_);~~~~@-);;;,.(),.*+);;# ~~@-,
           ./|,.*+,.,.);;;);*+~~@-,.*+,.;;,.;.,./.~~@-,.,.,.;_)   ;~~~
             ~@-,.;;,.;.,./@,./.);*+,.;.,.;;@-__~~;#~~@-,.;;,.*   +);;
               #);@-,./@,./.);*+~~@-~~.%~~.%~~@-;;__,. /.);;#@-   __@-
                 __   ~~;;);/@;#.%;#/.;#-(@-__~~;;;.;_ ;#.%~~~~  ;;()
                      ,.;.,./@,.  /@,.;_~~@- ););,.;_   );~~,./  @,.
                      ;;;./@,./|  ~~~~;#-(@- __,.,.,.    ;_);~~~ ~@
                       -~~());;   #);@-,./@,  .*+);;;     ~~@-~~
                       );~~);~~  *+~~@-);-(   ~~@-@-_      _~~@-
                       ~~@-);;   #,./@,.;.,    .;.);@      -~~@-;
                       #/.;#-(   ~~@-@-__      ~~@-~~       @-);@
                       -);~~,    .*+,./       |);;;~        ~@-~~
                        ;;;.;     _~~@-@     -__);.         %;#-(
                        @-__@      -__~~;#  ~~@-;;          ;#,.
                        ;_,..         %);@-,./@,            .*+,
                        ..%,           .;.,./|)             ;;;)
                        ;;#~            ~@-,.*+,.           ,.~~
                       @-);            *+,.;_);;.~         ~););
                      ~~,.;         .~~@-);~~,.;.,         ./.,.;
                      ;,.*+        ,./|,.);  ~~@-         );;;,.(
                    ),.*+);                              ;#~~/|@-
                  __~~;#~~                                $';$;;


Enter fullscreen mode Exit fullscreen mode

The code just prints "Hello world".
I don't know how.

Collapse
 
jeremyf profile image
Jeremy Friesen
(defun jf/pulse (parg)
  "Pulse the current line.

If PARG (given as universal prefix), pulse between `point' and `mark'."
  (interactive "P")
  (if (car parg)
    (pulsar--pulse nil nil (point) (mark))
  (pulsar-pulse-line)))
(global-set-key (kbd "C-x l") 'jf/pulse)
Enter fullscreen mode Exit fullscreen mode

The above function uses the pulsar.el package to create a visual "pulse" that temporarily highlights either the current line or the region between mark and point.

Point is analogue to the cursor. Mark is analogue to a "temporary" bookmark.

In the above code, the last line (e.g. (global-set-key...)) maps to C-x l (e.g. Ctrl+x then l) the jf/pulse function defined on lines 1 through 8.

By default, if I just type C-x l, I will "pulse" the current line. If I "prefix" the function call by first typing C-u (e.g. Ctrl+u) then type C-x l, I will pulse the region between mark and point.

The anatomy of the above is as follows:

  • Line 1: Name the function jf/pulse and one parameter parg (e.g. prefix arg).
  • Line 2 through 4: This is the doc string, it's available throughout emacs.
  • Line 5: This declares the function as interactive (I can call it from a menu). The "P" indicates that the above parg parameter is a prefix argument.
  • Line 6: If given the parg (e.g. I typed C-u C-x l)...
  • Line 7: ...then pulse the region between point and mark.
  • Line 8: ...else pulse the current line.
  • Line 9: Bind the jf/pulse to the C-x l key combination.
Collapse
 
guitarino profile image
Kirill Shestakov
fn main() {
    println!("{:?}", get_primes_up_to(200));
}

fn get_primes_up_to(n: usize) -> Vec<usize> {
    let start = 2;
    let end = n + 1;
    let mut crossed_out = vec![false; end - start + 1];
    let mut primes = Vec::new();
    for (i, number) in (start..end).enumerate() {
        if !crossed_out[i] {
            primes.push(number);
            for multiple in (2 * number..end).step_by(number) {
                crossed_out[multiple - start] = true;
            }
        }
    }
    return primes;
}
Enter fullscreen mode Exit fullscreen mode

This Rust code finds and prints the first 200 primes via a sieve method. Sieve method works by plotting all numbers from 2 to n and crossing out those numbers that are known multiple of each prime.

Sieve method illustration

In our code we create crossed_out vector. This vector will be responsible for holding the crossed out state of all numbers from 2 to n. We also create a primes vector that will hold our found primes. In a loop, we go through all numbers from 2 to n (inclusively), and if the number hasn't yet been crossed out, that means that this number is a prime. If it is a prime, we iterate over every multiple of that number up to n and cross it out from the list.

I like how expressive the code is thanks to Rust's range. At first I also used Rust's enums, options and iterators but then realized I could simplify the code by having crossed_out be a vector of bool, and adding to primes vector within the same loop.

Collapse
 
wsgac profile image
Wojciech S. Gac

My implementation of factorial in Emacs Lisp

(defun factorial (n)
  "Compute the factorial of N in a tail-recursive manner."
  (labels ((tail-factorial (n acc)
        (if (zerop n)
            acc
          (tail-factorial (1- n) (* n acc)))))
    (tail-factorial n 1)))
Enter fullscreen mode Exit fullscreen mode

This is a standard way to implement factorial using tail recursion. defun marks the beginning of function definition. Then goes the name (factorial) and list of arguments ((n)). After that we have an optional docstring (the good part about Emacs being self-documenting has long been the fact that docstrings become incorporated into an online help system - this is no longer surprising in programming languages, but used to be rare). labels introduces a local function - only visible within the enclosing scope. It's actually this inner function that is tail-recursive - the parameter acc is used to weave the partial result through the sequence of recursive calls, to be returned at the bottom. By using tail recursion (provided our language supports it) leverage so-called TCO (Tail Call Optimization) to avoid building up a stack with recursive calls. Finally, we call our inner, tail-recursive function on the original parameter n and initialize acc to 1. This way we get the desired behavior of 0! = 1.

Collapse
 
leobm profile image
Felix Wittmann • Edited
%% Prolog example
yummy(apfel).
yummy(apfelkuchen).
yummy(apfelsaft).
yummy(paradiesapfel).
yummy(birne).

yummy_with_apple(X) :-
    yummy(X), 
    atom_chars(X, C),
    append(_,[a,p,f,e,l|_], C).
Enter fullscreen mode Exit fullscreen mode

test it with swish.swi-prolog.org/

apfel is apple in english

When you run following query ?- yummy_with_apple(X)
you get follwing result set:

X = apfel
X = apfelkuchen
X = apfelsaft
X = paradiesapfel

if you run follwing query:
?- yummy_with_apple(apfelsaft)

you get true as result

Collapse
 
jrothlander profile image
jrothlander • Edited

How about Verilog. This is typically one of the first ones you work through as an example. This is a 4-Bit binary counter that counts from 0 to 9 and displays the count on a 7-segment display. The display is just 7 LEDs, so it turns all of the on by default and you use a binary number to tell it which of the LEDs to turn off.

While Verilog is language, it a hardware descriptive language, meaning that it tells an FPGA (field programmable gate array) how to setup its hardware. So you are creating a chip at runtime and can rework it and reprogram it on the fly. You have one in your phone and they are great for AI. So a little different from a typical program. It is a way to implement software as hardware.

module top(                     
    input wire clk,
    output wire LED0,           // bit 1
    output wire LED1,           // bit 2
    output wire LED2,           // bit 4
    output wire LED3,           // bit 8
    output reg [6:0] LED_out,   // 7-segment LED display[0]
    output reg [6:0] LED_out1       // 7-segment LED display[1]
);    

    reg [31:0] cnt;                 // 32-bit counter   
    reg [3:0] LED_BCD;  
    reg [31:0] startbit = 25;       // starting counter index

    // assign LEDs to count bits, higher the index, the slower the count will run. 
    assign LED0 = cnt[startbit];
    assign LED1 = cnt[startbit + 1];
    assign LED2 = cnt[startbit + 2];
    assign LED3 = cnt[startbit + 3];        

    initial begin 
        cnt <= 32'h0; // start at zero
    end

    always @(posedge clk) begin
        cnt <= cnt + 1;             
        LED_BCD[0] <= cnt[startbit];
        LED_BCD[1] <= cnt[startbit + 1];
        LED_BCD[2] <= cnt[startbit + 2];
        LED_BCD[3] <= cnt[startbit + 3];

        if (LED_BCD  == 4'b1010)        // if LED_BCD equals 10 
            cnt <= 0;                       // reset
    end

    // 7-Segment LED display patterns
    always @(*)
        begin
            LED_out1 = 7'b11111111;   // "0"                                                                                
            case(LED_BCD)      // gfedcba                                                       
                4'h0: //LED_out  = 7'b1000000;   // "0"     
                    begin
                        LED_out = 7'b1000000;   // "0"                                                          
                        LED_out1 = 7'b1111001;   // "1"                                                                                 
                    end             
                4'h1: LED_out  = 7'b1111001; // "1"                         
                4'h2: LED_out = 7'b0100100;     // "2" 
                4'h3: LED_out = 7'b0110000;     // "3" 
                4'h4: LED_out = 7'b0011001;     // "4" 
                4'h5: LED_out = 7'b0010010;     // "5" 
                4'h6: LED_out = 7'b0000010;     // "6" 
                4'h7: LED_out = 7'b1111000;     // "7" 
                4'h8: LED_out = 7'b0000000;     // "8"  
                4'h9: LED_out = 7'b0010000;   // "9"                                                                            
            endcase
        end         
endmodule
Enter fullscreen mode Exit fullscreen mode

And you can't ignore Assembly. Here's an example I was working on from Ben Eater. It prints "Hello World". This is why we don't write in Assembly anymore.

PORTB = $6000
PORTA = $6001
DDRB = $6002
DDRA = $6003

E  = %10000000
RW = %01000000 m                                                   
RS = %00100000

  .org $8000

reset:
  lda #%11111111 ; Set all pins on port B to output
  sta DDRB

  lda #%11100000 ; Set top 3 pins on port A to output
  sta DDRA

  lda #%00111000 ; Set 8-bit mode; 2-line display; 5x8 font
  sta PORTB
  lda #0         ; Clear RS/RW/E bits
  sta PORTA
  lda #E         ; Set E bit to send instruction
  sta PORTA
  lda #0         ; Clear RS/RW/E bits
  sta PORTA

  lda #%00001110 ; Display on; cursor on; blink off
  sta PORTB
  lda #0         ; Clear RS/RW/E bits
  sta PORTA
  lda #E         ; Set E bit to send instruction
  sta PORTA
  lda #0         ; Clear RS/RW/E bits
  sta PORTA

  lda #%00000110 ; Increment and shift cursor; don't shift display
  sta PORTB
  lda #0         ; Clear RS/RW/E bits
  sta PORTA
  lda #E         ; Set E bit to send instruction
  sta PORTA
  lda #0         ; Clear RS/RW/E bits
  sta PORTA

  lda #"H"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"e"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"l"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"l"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"o"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #","
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #" "
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"w"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"o"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"r"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"l"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"d"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

  lda #"!"
  sta PORTB
  lda #RS         ; Set RS; Clear RW/E bits
  sta PORTA
  lda #(RS | E)   ; Set E bit to send instruction
  sta PORTA
  lda #RS         ; Clear E bits
  sta PORTA

loop:
  jmp loop

  .org $fffc
  .word reset
  .word $0000
Enter fullscreen mode Exit fullscreen mode
Collapse
 
derekenos profile image
Derek Enos • Edited

One of my recent favorites is this helper to convert a callback-based JS function to an awaitable:

function makeAwaitable (func, callbackArgIndex) {
  /* Return an awaitable version of a callback-based function.                                     

     Example:                                                                                      

       // Create an awaitable version of setTimeout, specifying the index                          
       // of the expected callback argument index (i.e. 0).                                        
       const awaitableSetTimeout = makeAwaitable(setTimeout, 0)                                    

       // Invoke the awaitable setTimeout, omitting the callback arg.                              
       await awaitableSetTimeout(1000)                                                             
       // Returns 1 second later.                                                                  

   */
  return (...args) => new Promise(
    (resolve, reject) => {
      // Splice resolve() into args at the callbackArgIndex location.                              
      args.splice(callbackArgIndex, 0, resolve)
      // Invoke func, reject the promise on error.                                                 
      try {
        return func(...args)
      } catch (e) {
        reject(e)
      }
    }
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jamesthomson profile image
James Thomson • Edited

Came up with this little snippet for Vue a couple years back that will assign a uid as a key on initial render and reuse the same key for subsequent renders. It's nothing fancy, but it's sure helpful.

function uid (el) {
  if (el.uid) return e.uid;

  // Could be replaced with actual uuid from lib
  const key = Math.random().toString(16).slice(2);

  Vue.set(el, 'uid', key);

  return el.uid;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dumboprogrammer profile image
Tawhid

The following c code generates a spinning donut with ASCII with some math going on with pseudo code liberties and 2d array.

const float theta_spacing = 0.07;
const float phi_spacing   = 0.02;

const float R1 = 1;
const float R2 = 2;
const float K2 = 5;
// Calculate K1 based on screen size: the maximum x-distance occurs
// roughly at the edge of the torus, which is at x=R1+R2, z=0.  we
// want that to be displaced 3/8ths of the width of the screen, which
// is 3/4th of the way from the center to the side of the screen.
// screen_width*3/8 = K1*(R1+R2)/(K2+0)
// screen_width*K2*3/(8*(R1+R2)) = K1
const float K1 = screen_width*K2*3/(8*(R1+R2));

render_frame(float A, float B) {
  // precompute sines and cosines of A and B
  float cosA = cos(A), sinA = sin(A);
  float cosB = cos(B), sinB = sin(B);

  char output[0..screen_width, 0..screen_height] = ' ';
  float zbuffer[0..screen_width, 0..screen_height] = 0;

  // theta goes around the cross-sectional circle of a torus
  for (float theta=0; theta < 2*pi; theta += theta_spacing) {
    // precompute sines and cosines of theta
    float costheta = cos(theta), sintheta = sin(theta);

    // phi goes around the center of revolution of a torus
    for(float phi=0; phi < 2*pi; phi += phi_spacing) {
      // precompute sines and cosines of phi
      float cosphi = cos(phi), sinphi = sin(phi);

      // the x,y coordinate of the circle, before revolving (factored
      // out of the above equations)
      float circlex = R2 + R1*costheta;
      float circley = R1*sintheta;

      // final 3D (x,y,z) coordinate after rotations, directly from
      // our math above
      float x = circlex*(cosB*cosphi + sinA*sinB*sinphi)
        - circley*cosA*sinB; 
      float y = circlex*(sinB*cosphi - sinA*cosB*sinphi)
        + circley*cosA*cosB;
      float z = K2 + cosA*circlex*sinphi + circley*sinA;
      float ooz = 1/z;  // "one over z"

      // x and y projection.  note that y is negated here, because y
      // goes up in 3D space but down on 2D displays.
      int xp = (int) (screen_width/2 + K1*ooz*x);
      int yp = (int) (screen_height/2 - K1*ooz*y);

      // calculate luminance.  ugly, but correct.
      float L = cosphi*costheta*sinB - cosA*costheta*sinphi -
        sinA*sintheta + cosB*(cosA*sintheta - costheta*sinA*sinphi);
      // L ranges from -sqrt(2) to +sqrt(2).  If it's < 0, the surface
      // is pointing away from us, so we won't bother trying to plot it.
      if (L > 0) {
        // test against the z-buffer.  larger 1/z means the pixel is
        // closer to the viewer than what's already plotted.
        if(ooz > zbuffer[xp,yp]) {
          zbuffer[xp, yp] = ooz;
          int luminance_index = L*8;
          // luminance_index is now in the range 0..11 (8*sqrt(2) = 11.3)
          // now we lookup the character corresponding to the
          // luminance and plot it in our output:
          output[xp, yp] = ".,-~:;=!*#$@"[luminance_index];
        }
      }
    }
  }

  // now, dump output[] to the screen.
  // bring cursor to "home" location, in just about any currently-used
  // terminal emulation mode
  printf("\x1b[H");
  for (int j = 0; j < screen_height; j++) {
    for (int i = 0; i < screen_width; i++) {
      putchar(output[i,j]);
    }
    putchar('\n');
  }

}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
whobeu profile image
Robert G. Schaffrath • Edited

I wrote this JavaScript snippet about two years ago to validate a USPS tracking ID. It is not exhaustive as to whether or not the ID is actually is a known USPS ID but it makes sure the minimum number of digits are present and the check-digit is correct.

Code Snippet

Collapse
 
fen1499 profile image
Fen
def openReturn(path):
    temp = []
    f = open(path, "r")
    for x in f:
        temp.append(str.split(str.strip(x),","))
    return temp
Enter fullscreen mode Exit fullscreen mode

This python code takes a csv like file and breaks it into arrays, very handy option for simple usecases and also a great example of how to not name your variables

Collapse
 
aarone4 profile image
Aaron Reese

Dylan Beattie got so fed up with recruiters wanting Rockstar developers he came up with the Rockstar language specification which allows you to write code that looks like 1990s soft-rock lyrics.
This talk is both facinating and hilarious and he plays a song at the end that is in fact FizzBuzz in Rockstar.
https://m.youtube.com/watch?v=6avJHaC3C2U&t=16s

Collapse
 
igulzaib profile image
Gul Zaib

HTML

<html>
<head>
<title>HTML is in our ❀️s</title>
</head>
<body>
<p>This is how html works</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
john4650hub profile image
JohnDelvin
for i in range(int(input())):
    num1,num2 = map(int,input().split())
    print(sum([num2,num1]))
Enter fullscreen mode Exit fullscreen mode

sample input

2
5 5
10
4 4
8
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adriens profile image
adriens

This short post brought me inspiration for an another post.
Thanks for the inspiration.

Collapse
 
k_penguin_sato profile image
K-Sato

console.log("Hello World");

Hello world in JS.

Collapse
 
exoutia profile image
Exoutia • Edited

This Is a constructor in python with the help of 'new' we can use it to return some value to a variable.πŸ₯²πŸ₯²(sorry for bad photo it's really not best to have no internet connection)