Skip to content

Instantly share code, notes, and snippets.

@valtih1978
valtih1978 / lib.html
Last active Sep 2, 2018
javascript-based parser
View lib.html
<script id="library" title="it must be a part of starndard javascript">
const log = console.log ; const assert = console.assert
update = (o, mutator) => {mutator(o); return o}
trace = (value, format) => {format = format || (data => data) ; log(format(value)); return value};
tracejs = (msg, data) => trace(data, data => [msg, data.json()])
Object.prototype.trace = function(format) {trace(this, format)}
function range (len, begin) {begin = begin || 0
@valtih1978
valtih1978 / HuffmanScalaAssignment.sc
Last active May 3, 2018
Odersky ProgFun coursera Huffman coding assignment
View HuffmanScalaAssignment.sc
/**
* Assignment 4: Huffman coding
*
*/
object Huffman1 {
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
@valtih1978
valtih1978 / 1.sequence_generator.py
Last active Sep 17, 2017
Sequence Generator - generates some C (or Java?) programs
View 1.sequence_generator.py
# There were multiple goals: to implement AI for my game, to inject bugs ino VHDL and prove that sexual demorphims
# where boys have much higher mutation rate ' Сперматозоидов у мужчины за всю его жизнь вырабатывается гораздо больше, чем яйцеклеток у женщины. Это значит, что предшественники мужских половых клеток делятся гораздо интенсивнее и, следовательно, у них больше риск возникновения мутаций.'
#, is advantageous.
# Inspired by http://eli.thegreenplace.net/2010/01/28/generating-random-sentences-from-a-context-free-grammar
from collections import defaultdict
import random
def weighted_choice(weights):
rnd = random.random() * sum(weights)
View 1. ProxyDB - reduced.sc
import java.lang.reflect.{Method, InvocationHandler, Proxy}
import scala.language.reflectiveCalls, scala.language.postfixOps
import scala.collection.mutable, java.io._, Util._
// I called this version "reduced" because proxies are not GC-ed when not referenced by user
// This makes a code a bit simpler and, probably, even faster if proxies are small indeed.
// The experiment
// timeit "scala -J-Xmx33m ProxyDemo + 16 100 > nul"
// however suggests that this implementation is slow as 144 sec vs 129 sec for managed proxies.
@valtih1978
valtih1978 / Test.sc
Last active Sep 1, 2017
vhdl parser based on scala parser combinators
View Test.sc
import Vhdl._
// TODO: CharLiteral -> Char, StringLiteral -> String to save memory
object AllTests extends App {
def recover[T](okMsg: String/*, shouldRecover: T => Boolean = _ => true*/): ParseResult[T] => ParseResult[_] = pr => pr match {
case f @ Failure(msg, rem) => Success(okMsg, rem) //if (shouldRecover(msg)) Success(okMsg, rem) else f
case e @ Error(msg, rem) => println("Recovering error " + msg); Success(okMsg, rem) //if (shouldRecover(msg)) Success(okMsg, rem) else f
case s @ Success(msg, rem) => Failure(s"we had to fail because $okMsg but succeeded with " + msg, rem); case a => a
}
View parprog - week1.sc
// task and parallel definition can be found at https://www.coursera.org/learn/parprog1/discussions/weeks/1/threads/2gsI2DHVEeaKAhJC1hWxEQ/replies/-avxXTIBEeabvwrOSKMg4w/comments/O5yTH3K6EeeM7BK4-ybiDA
/** Computes the blurred RGBA value of a single pixel of the input image. */
def boxBlurKernel(src: Img, x: Int, y: Int, radius: Int): RGBA = {
val xMin = clamp(x-radius, 0, src.width-1)
val xMax = clamp(x+radius, 0, src.width-1)
val yMin = clamp(y-radius, 0, src.height-1)
val yMax = clamp(y+radius, 0, src.height-1)
var (i,j,n) = (xMin, yMin, 0.0)
var r,g,b,a = 0.0
@valtih1978
valtih1978 / CoinChange+perm=Anagrams.sc
Last active Jun 27, 2017
Describes how to exploint coin change algorithm + permutations for anagram search
View CoinChange+perm=Anagrams.sc
package forcomp
object SicpAnagrams {
// Inplementing Odersky anagrams (FP Scala coursera) using SICP algorithm, http://mitpress.mit.edu/sicp/full-text/sicp/book/node16.html
// PART I: SICP count change algorithm
// Odersky recomends SICP book as the course resource material. Before taking the course,
// I studied it. Might be for this reason, I realized that the anagram assignment is the
@valtih1978
valtih1978 / header.js
Last active Nov 14, 2016
javascript unils
View header.js
const log = console.log ; const assert = console.assert
//Object.prototype.trace = function(format) {format = format || (data => data); log(format(this)); return this} // prints something wrong
const trace = (data, format) => {format = format || (data => data); log(format(data)); return data}
const tracejs = (ms, data) => trace(data, data => [ms, data.json()])
function range (len, begin) {begin = begin || 0
return Array.apply(null, Array(len)).map((_, i) => {return begin+i;})}
//Array.prototype.fill = function(filler) {return this.map(_ => filler)} // startard func
Array.prototype.equals = function(that) {return this.every((my, i) => my == that[i] )} ; [1,2].equals([1,2])
Array.prototype.sum = function() {return this.reduce((acc, el) => acc + el,0)}
@valtih1978
valtih1978 / Expressions.sc
Last active Nov 4, 2015
Symbolic expressions
View Expressions.sc
trait E {
def e(dict: Map[Const, Int]): Int
def +(another: E): E = (this, another) match {
case (zero, _) => another // Bug! Bug! this unintentionally redefines zero
case (_, zero) => this
case _ => Plus(this, another)
}
def *(another: E): E = {
def par(e: E) = e match {case e @ Plus(a,b) => Par(e); case e => e}
Mult(par(this), par(another))
@valtih1978
valtih1978 / 1. asexual_oversimplication.scala
Last active Aug 29, 2015
4% degradation with every generation
View 1. asexual_oversimplication.scala
// This talk https://www.youtube.com/watch?v=MGfr_col5PI claims that if 4% of healty people degenerate with every
// and if 50% recover from defective genetics then we reach 8% failed genetics. Here is the simulation that confirms this.
def sim1(healthy: Double, generation: Int = 1): Unit = if (generation < 100) {
val degenerates = 1 - healthy; println((degenerates * 100) + "% down" )
sim1(healthy * 0.96 + degenerates * 0.5, generation + 1)
} //> sim1: (healthy: Double, generation: Int)Unit
sim1(1) //> 0.0% down
//| 4.0000000000000036% down
You can’t perform that action at this time.