julia Julia中区块链的一个非常基本的实现。

Julia中区块链的一个非常基本的实现。

Blockchain.jl
using SHA

"""
An individual block structure
"""
struct Block
    index::Int
    timestamp::DateTime
    data::String
    previous_hash::String
    hash::String
    """
    The constructor which will also create hash for the block.
    It will use 256 bit encryption for the blockchain's security needs.
    """
    function Block(index, timestamp, data, previous_hash)
        hash = sha2_256(string(index, timestamp, data, previous_hash))
        new(index, timestamp, data, previous_hash, bytes2hex(hash))
    end
end

"""
Add another block to the chain.
You can't have a blockchain with just one block after all.
"""
function next_block(tail_block::Block)
    new_index = tail_block.index + 1
    return Block(new_index, Dates.now(), string("This is block ",new_index), tail_block.hash)
end

# Create the special first block or the head of the blockchain.
Blockchain = [Block(0, Dates.now(), "Genesis Block", "0")]

println("Genesis Block : 1")
println("Hash :", Blockchain[1].hash)

# Size of the blockchain
Blockchain_limit = 13

# To make addition of blocks to the blockchain non-arbitary (unlike here),
# a proof of work task is required.
for tail = 1:Blockchain_limit
    # Link the new block to the chain
    append!(Blockchain, [next_block(Blockchain[tail])])
    # The details of the block
    println("Block : $(tail+1)")
    println("Hash :", Blockchain[tail+1].hash)
end

# Reference - https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b

julia sample.jl

sample.jl
function mandel(z)
    c = z
    maxiter = 80
    for n = 1:maxiter
        if abs2(z) > 4
            return n-1
        end
        z = z^2 + c
    end
    return maxiter
end

function randmatstat(t)
    n = 5
    v = zeros(t)
    w = zeros(t)
    for i = 1:t
        a = randn(n,n)
        b = randn(n,n)
        c = randn(n,n)
        d = randn(n,n)
        P = [a b c d]
        Q = [a b; c d]
        v[i] = trace((P.'*P)^4)
        w[i] = trace((Q.'*Q)^4)
    end
    std(v)/mean(v), std(w)/mean(w)
end

julia Nulls为半字节大小的bitflag sentinals

Nulls为半字节大小的bitflag sentinals

NibbleNulls.jl
#=
    proof of concept
        multidimensional indicies are not treated
        no comparative benchmarking has been done
=#

module NibbleNulls

export notnull, isnull, setnull!, clearnull!,
       NibbleVec

const NibbleVec = Vector{UInt8}

function notnull(nibbles::NibbleVec, index::U) where U<:Unsigned
   mask   = isodd(index) ? 0x0F : 0xF0
   index  = index >>> one(U)
   @inbounds nibble = getindex(nibbles, index)
   nibble = nibble & mask
   return nibble === zero(UInt8)
end

@inline function notnull(nibbles::NibbleVec, index::S) where S<:Signed
     index >=  one(S) && return notnull(nibbles, reinterp(Unsigned, index))
     exception_as_false("Illegal index value")
end

function isnull(nibbles::NibbleVec, index::U) where U<:Unsigned
   mask   = isodd(index) ? 0x0F : 0xF0
   index  = index >>> one(U)
   @inbounds nibble = getindex(nibbles, index)
   nibble = nibble & mask
   return nibble !== zero(UInt8)
end

@inline function isnull(nibbles::NibbleVec, index::S) where S<:Signed
     index >=  one(S) && return isnull(nibbles, reinterp(Unsigned, index))
     exception_as_false("Illegal index value")
end

function setnull!(nibbles::NibbleVec, index::U) where U<:Unsigned
   mask   = isodd(index) ? 0x01 : 0x10
   index  = index >>> one(U)
   @inbounds begin
       nibble = getindex(nibbles, index)
       nibble = nibble | mask
       setindex!(nibbles, nibble, index)
   end
   return nothing
end

@inline function setnull!(nibbles::NibbleVec, index::S) where S<:Signed
     index >=  one(S) && return setnull!(nibbles, reinterp(Unsigned, index))
     exception_as_nothing("Illegal index value")
end

function clearnull!(nibbles::NibbleVec, index::U) where U<:Unsigned
   mask  = isodd(index) ? 0x10 : 0x01
   index = index >>> one(U)
   @inbounds begin
       nibble = getindex(nibbles, index)
       nibble = nibble & mask
       setindex!(nibbles, nibble, index)
   end
   return nothing
end

@inline function clearnull!(nibbles::NibbleVec, index::S) where S<:Signed
     !signbit(index - one(S)) && return clearnull!(nibbles, reinterp(Unsigned, index))
     exception_as_nothing("Illegal index value")
end

reinterp(::Type{Unsigned}, index::Int8)   = reinterpret(UInt8, index)
reinterp(::Type{Unsigned}, index::Int16)  = reinterpret(UInt16, index)
reinterp(::Type{Unsigned}, index::Int32)  = reinterpret(UInt32, index)
reinterp(::Type{Unsigned}, index::Int64)  = reinterpret(UInt64, index)
reinterp(::Type{Unsigned}, index::Int128) = reinterpret(UInt128, index)

# somehow exception(str)::nothing
function exception_as_nothing(str::String)
    println(string("*Runtime Exception*:", str))
    return nothing
end

end # module

julia Julia的BitOps

Julia的BitOps

BitOps.jl
"""
BitOps exports functions using low level bit manipulation to modify standard Int and UInt values.
Note:  Functions that check their arguments are named `safe_..`, others do no checking.

Copyright 2017 by Jeffrey Sarnoff.  Released under the MIT License.
"""
module BitOps

using Compat

export bitsizeof, clr_bit, set_bit, flp_bit, 
       iso_bit, get_bit, put_bit,
       clr_lsbits, set_lsbits, clr_msbits, set_msbits,
       mask_bits, filt_bits

#if VERSION < v"0.6.0-alpha"
#  xor(a,b) = a$b
#end
       
"bit size of type or value"
bitsizeof{T}(::Type{T}) = sizeof(T) << 3
bitsizeof{T}(x::T) = bitsof(T)

const SUN = Union{Signed, Unsigned}
const INT = Union{Int32, Int64}        # bit manipulations with Int32 shifts tend to be faster

set_bit{T<:SUN, I<:INT}(::Type{T}, bitidx::I) =   one(T) << bitidx
clr_bit{T<:SUN, I<:INT}(::Type{T}, bitidx::I) = ~(one(T) << bitidx)

@compat flp_bit{T<:SUN, I<:INT}(x::T, bitidx::I) = xor(x, set_bit(T, bitidx))

iso_bit{T<:SUN, I<:INT}(x::T, bitidx::I) = x & set_bit(T, bitidx)
get_bit{T<:SUN, I<:INT}(x::T, bitidx::I) = (iso_bit(x, bitidx) >> bitidx) == one(T)
put_bit{T<:SUN, I<:INT}(x::T, bitidx::I, bitvalue::Bool) = (x & clr_bit(T, bitidx)) | (bitvalue << bitidx)


set_lsbits{T<:SUN, I<:INT}(::Type{T}, bitidx::I) =   (one(T) << bitidx) - one(T)
clr_lsbits{T<:SUN, I<:INT}(::Type{T}, bitidx::I) = ~((one(T) << bitidx) - one(T))
clr_msbits{T<:SUN, I<:INT}(::Type{T}, bitidx::I) =   ~zero(T) >>> bitidx
set_msbits{T<:SUN, I<:INT}(::Type{T}, bitidx::I) = ~(~zero(T) >>> bitidx)

# inclusive of lobitidx and hibitidx
mask_bits{T<:SUN, I<:INT}(::Type{T}, lobitidx::I, hibitidx::I) =   set_lsbits(T, hibitidx-lobitidx+1) << lobitidx
filt_bits{T<:SUN, I<:INT}(::Type{T}, lobitidx::I, hibitidx::I) = ~(set_lsbits(T, hibitidx-lobitidx+1) << lobitidx)

set_lsbits{T<:SUN, I<:INT}(x::T, bitidx::I) = x | set_lsbits(T, bitidx)
clr_lsbits{T<:SUN, I<:INT}(x::T, bitidx::I) = x & clr_lsbits(T, bitidx)
set_msbits{T<:SUN, I<:INT}(x::T, bitidx::I) = x | set_msbits(T, bitidx)
clr_msbits{T<:SUN, I<:INT}(x::T, bitidx::I) = x & clr_msbits(T, bitidx)

mask_bits{T<:SUN, I<:INT}(x::T, lobitidx::I, hibitidx::I) = x & mask_bits(T, lobitidx, hibitidx)
filt_bits{T<:SUN, I<:INT}(x::T, lobitidx::I, hibitidx::I) = x & filt_bits(T, lobitidx, hibitidx)


import Base: sign_mask, exponent_mask, significand_mask,
             exponent_bits, significand_bits,
             (~), (&), (|)


for (U,S) in [(:UInt8, :Int8), (:UInt16, :Int16), (:UInt32, :Int32), (:UInt64, :Int64), (:UInt128, :Int128)]
    @eval begin
        Base.reinterpret(::Type{Signed}, x::$U) = reinterpret($S, x)
        Base.reinterpret(::Type{Signed}, x::$S) = x
        Base.reinterpret(::Type{Unsigned}, x::$S) = reinterpret($U, x)
        Base.reinterpret(::Type{Unsigned}, x::$U) = x
    end
end

end # module BitOps

julia 用于http://rosalind.info/problems/fib/的兔子fibonacci函数

用于http://rosalind.info/problems/fib/的兔子fibonacci函数

fib.jl
function total(n,k=3)
    rfib(n) = n < 2 ? n : rfib(n-1) + k*rfib(n-2)
    return rfib(n)
end

total(5,3)

julia 来自https://www.notex.ch/editor#

来自https://www.notex.ch/editor#

AbstractTime.jl
module TemporalAbstractions

export AbstractTime, 
       AbstractCalendar, AbstractDate, AbstractTimeOfDay,
       AbstractDateTime, AbstractDateTimeZone

import Base.Dates: AbstractTime

abstract type TemporalAbstraction end

# parameter T for TemporalResolution realization (e.g. smallest time step available: day, nanosecond)
# either as a symbol or as any other type enfolding

abstract type TemporalResolution{T} <: TemporalAbstraction end

abstract type AbstractTimes{T} <: TemporalResolution{T} end

abstract type AbstractCalendar{T} <: AbstractTimes{T} end 
# BusinessDays defines HolidayCalendar as an abstract type
# this would be its supertype (if Felipe agrees .. he has been agreeable to date).

abstract type AbstractDate{T} <: AbstractTimes{T} end
# ideally, Base.Dates.Date would become a subtype of this

abstract type AbstractTimeOfDay{T} <: AbstractTimes{T} end
# ideally, Base.Dates.Time would become a subtype of this

abstract type AbstractDateTime{T} <: AbstractTimes{T} end
# ideally, Base.Dates.DateTime would become a subtype of this

abstract type AbstractDateTimeZone{T} <: AbstractDateTime{T} end
# ZonedDateTime <: this

end # module
        
   

julia Julia中的合并排序,在C上使用Stanford的[算法:设计和分析,第1部分](https://class.coursera.org/algo-005/)时实现

在Julia中合并排序,在Coursera上使用Stanford的[算法:设计和分析,第1部分](https://class.coursera.org/algo-005/)

merge_sort.jl
function merge_sorted(lhs::Array, rhs::Array)
  fullsize = length(lhs) + length(rhs)
  retvals = Array(Int64, fullsize)

  for k = 1:fullsize

    if first(lhs) <= first(rhs)
      retvals[k] = shift!(lhs)
     else
       retvals[k] = shift!(rhs)
    end

    if isempty(lhs)
      return transfer_tail(retvals, rhs, k)
    elseif isempty(rhs)
      return transfer_tail(retvals, lhs, k)
    end

  end
end

function transfer_tail(vals::Array, tail::Array, count::Int64)
  for k = (count + 1):(length(tail) + count)
    vals[k] = shift!(tail)
  end
  vals
end

function sortmerge(to_sort::Array)
  len = length(to_sort)
  len <= 1 && return to_sort
  head = to_sort[1:(ceil(len/2))]
  tail = to_sort[(length(head)+1):end]
  merge_sorted(sortmerge(head), sortmerge(tail))
end

x = sortmerge([1,3,2,4])
y = sortmerge([1,2,3,4,5, 99, 54, 33, 21, 67, 88, 9, 39, 76, 88, 89, 100001, 45, 3000, 6,867,8,10])

println("x: $x \n y: $y")