Skip to content

Instantly share code, notes, and snippets.

View sasa1977's full-sized avatar

Saša Jurić sasa1977

View GitHub Profile
cmd = ~S"""
ruby -e '
require "bundler"
require "erlang/etf"
require "stringio"
@input = IO.new(3)
@output = IO.new(4)
@output.sync = true
defrecord Person, id: nil, name: nil
defrecord ParserState, persons: [], current_person: nil
defmodule TestXmerlSax do
def xml do
%b(
<doc>
<person id="1">Joe Armstrong</person>
<person id="2">José Valim</person>
</doc>
@sasa1977
sasa1977 / xmerl_demo.ex
Last active July 26, 2023 10:07
Simple xmerl usage demo in Elixir
defmodule XmlNode do
require Record
Record.defrecord :xmlAttribute, Record.extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
Record.defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
def from_string(xml_string, options \\ [quiet: true]) do
{doc, []} =
xml_string
|> :binary.bin_to_list
|> :xmerl_scan.string(options)
@sasa1977
sasa1977 / sql_parser.exs
Created October 13, 2019 08:56
Basic SQL parser developed at WebCamp Zagreb, 2019
defmodule SqlParser do
def run() do
input = "select col1 from (
select col2, col3 from (
select col4, col5, col6 from some_table
)
)
"
IO.puts("input: #{inspect(input)}\n")
IO.inspect(parse(input))
defmodule RubyServer do
use GenServer
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, nil, opts)
end
def cast(server, cmd) do
GenServer.cast(server, {:cast, cmd})
end
# This is the proper BEAM test for https://github.com/uber/denial-by-dns. The Erlang test in that repo is sequential
# (https://github.com/uber/denial-by-dns/blob/b809cc561a691d9d6201d06d38d06c33c9c9f9ec/erlang-httpc/main.erl)
# which is not consistent with the test description (https://github.com/uber/denial-by-dns/tree/b809cc561a691d9d6201d06d38d06c33c9c9f9ec#how-it-works)
# and also differs from e.g. go test in the same repo which issues requests concurrently.
#
# Consequently, the conclusion in that repo as well as the original article (https://eng.uber.com/denial-by-dns/) is incorrect.
# A properly written Erlang test would pass, as demonstrated by this Elixir script.
#
# This code performs a slightly refined and a correct version of that tests in Elixir:
#
cmd = ~S"""
ruby -e '
STDOUT.sync = true
context = binding
while (cmd = gets) do
eval(cmd, context)
end
'
"""
defmodule Overrider do
defmacro __using__(_) do
quote do
import Kernel, except: [def: 2]
import Overrider
end
end
defmacro def(fun_def, opts) do
quote do
cmd = ~S"""
ruby -e '
STDOUT.sync = true
def receive_input
encoded_length = STDIN.read(4)
return nil unless encoded_length
length = encoded_length.unpack("N").first
STDIN.read(length)
# http://adventofcode.com/2017/day/4
defmodule Day4 do
def part1(), do:
passphrases()
|> Stream.map(&words/1)
|> Stream.reject(&any_duplicate?/1)
|> Enum.count()
def part2(), do: