I'm trying to understand how to work with this package for Julia.
Im using the following code (is an example from the package):
using HttpServer
function fibonacci(n)
if n == 1 return 1 end
if n == 2 return 1 end
prev = BigInt(1)
pprev = BigInt(1)
for i=3:n
curr = prev + pprev
pprev = prev
prev = curr
end
return prev
end
http = HttpHandler() do req::Request, res::Response
m = match(r"^/fibo/(\d+)/?$",req.resource)
if m == nothing
return Response(404)
end
number = BigInt(m.captures[1])
if number < 1 || number > 100_000
return Response(500)
end
return Response(string(fibonacci(number)))
end
http.events["error"] = (client, err) -> println(err)
http.events["listen"] = (port) -> println("Listening on $port...")
server = Server(http)
run(server, 8031)
And trying to access to the server with this link:
http://localhost:8031/fibo/100
But i get the next error:
MethodError(convert,(BigInt,"100"))
ERROR: MethodError: Cannotconvert an object of type
SubString{String} to an object of type BigInt
What im doing wrong?
I have problems to figure out what r"^/fibo/(\d+)/? does, maybe there is my problem...
You get this error because method BigInt(s::AbstractString) is deprecated and was remove in julia 0.5. Use number = parse(BigInt,m.captures[1]) instead.
Related
I'm implementing the Ordering type according to the docs but I'm getting a missing method error. The docs don't say anything about needing to define iterate?
https://juliacollections.github.io/DataStructures.jl/v0.9/sorted_containers.html#Constructors-for-Sorted-Containers-1
ERROR: LoadError: MethodError: no method matching iterate(::Type{BidOrdering})
using DataStructures
import Base.Ordering
import Base.lt
import DataStructures.eq
struct MBOBookEntity
orderid::Int64
price::String
orderPriority::Int64
displayQty::Int64
end
mutable struct MBOBook
bidBook::SortedSet{MBOBookEntity}
askBook::SortedSet{MBOBookEntity}
function MBOBook()
bidBook = SortedSet{MBOBookEntity}(BidOrdering)
askBook = SortedSet{MBOBookEntity}(AskOrdering)
new(bidBook, askBook)
end
end
struct BidOrdering <: Ordering end
struct AskOrdering <: Ordering end
lt(::BidOrdering, o1::MBOBookEntity, o2::MBOBookEntity) = begin
if o1.price == o2.price
return o1.orderPriority < o2.orderPriority
else
return o2.price < o1.price
end
end
eq(::BidOrdering, o1::MBOBookEntity, o2::MBOBookEntity) = isequal(o1.orderid, o2.orderid)
lt(::AskOrdering, o1::MBOBookEntity, o2::MBOBookEntity) = begin
if o1.price == o2.price
return o1.orderPriority < o2.orderPriority
else
return o1.price < o2.price
end
end
eq(::AskOrdering, o1::MBOBookEntity, o2::MBOBookEntity) = isequal(o1.orderid, o2.orderid)
I think that you provide a type instead of a value :
mutable struct MBOBook
bidBook::SortedSet{MBOBookEntity}
askBook::SortedSet{MBOBookEntity}
function MBOBook()
bidBook = SortedSet{MBOBookEntity}(BidOrdering()) # <- here, forgotten ()
askBook = SortedSet{MBOBookEntity}(AskOrdering()) # <- here, forgotten ()
new(bidBook, askBook)
end
end
I'm using NLopt for a constrained maximization problem. Regardless of the algorithm or start values, the optimization program is force stopped even before the first iteration (or so I assume because it gives me the initial value). I've attached my code here. I'm trying to find probabilities attached to a grid such that a function is maximized under some constraints. Any help is appreciated.
uk = x -> x^0.5
function objective(u,p,grd)
-p'*u.(grd)
end
function c3(grd,p)
c =[]
d =[]
for i=1:length(grd)
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
end
return append!(d-c,-p)
end
function c4(grd,p)
return (grd .* p)-quadgk(x,0,1)
end
grd = n -> collect(0:1/n:1)
opt = Opt(:LD_SLSQP,11)
inequality_constraint!(opt, p -> c3(grd(10),p))
inequality_constraint!(opt, p -> -p)
equality_constraint!(opt, p -> sum(p)-1)
equality_constraint!(opt, p -> c4(grd(10),p))
opt.min_objective = p -> objective(-uk, p, grd(10))
k = push!(ones(11)*(1/11))
(minf,minx,ret) = optimize(opt, k)
I'm not a julia developer, but I only know this, if you need exit before complete the loop for is not your best choice, you need do a while with a sentinel variable.
here you have an article that explain you how while with sentinels works
and here you have a julia example changing your for to a while with a sentinel that exit after the third loop
i = 1
third = 0
while i < length(grd) && third != 1
# of course you need change this, it is only an example that will exit in the 3 loop
if i == 3
third = 1
end
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
i += 1
end
what is the prefered way to investigate or print out further detail (print input variable of a function, iteration number, etc.) of a failed #test inside a #testset?
I tried to wrap a try-catch-block around it. However, it doesn't seem to fire.
Here is a made-up example:
using Base.Test
rng = MersenneTwister(3231);
# define function that works different than expected
function compare(a,b)
if a == 3 && b == 3
return false
else
return a == b
end
end
# test function in a test set
#testset "Test Compare Function" begin
for iii = 1:10
number = rand(rng,1:10)
try
#test compare(number,number) == true
catch
#show(number)
end
end
end
Thank you very much!
You need to make sure it tests after the printing.
#testset "Test Compare Function" begin
for iii = 1:10
number = rand(rng,1:10)
#test begin
res = compare(number,number) == true
if !res
#show number
flush(STDOUT)
end
res
end
end
end
I am having trouble figuring out how to get the length of a matrix within a matrix within a matrix (nested depth of 3). So what the code is doing in short is... looks to see if the publisher is already in the array, then it either adds a new column in the array with a new publisher and the corresponding system, or adds the new system to the existing array publisher
output[k][1] is the publisher array
output[k][2][l] is the system
where the first [] is the amount of different publishers
and the second [] is the amount of different systems within the same publisher
So how would I find out what the length of the third deep array is?
function reviewPubCount()
local output = {}
local k = 0
for i = 1, #keys do
if string.find(tostring(keys[i]), '_') then
key = Split(tostring(keys[i]), '_')
for j = 1, #reviewer_code do
if key[1] == reviewer_code[j] and key[1] ~= '' then
k = k + 1
output[k] = {}
-- output[k] = reviewer_code[j]
for l = 1, k do
if output[l][1] == reviewer_code[j] then
ltable = output[l][2]
temp = table.getn(ltable)
output[l][2][temp+1] = key[2]
else
output[k][1] = reviewer_code[j]
output[k][2][1] = key[2]
end
end
end
end
end
end
return output
end
The code has been fixed here for future reference: http://codepad.org/3di3BOD2#output
You should be able to replace table.getn(t) with #t (it's deprecated in Lua 5.1 and removed in Lua 5.2); instead of this:
ltable = output[l][2]
temp = table.getn(ltable)
output[l][2][temp+1] = key[2]
try this:
output[l][2][#output[l][2]+1] = key[2]
or this:
table.insert(output[l][2], key[2])
I am using MySQLdb to talk to mysql database and I am able to retrieve dynamically all the result sets.
My problem is that once I get the result set, there are a couple columns which are declared as timestamps in mysql but when it is retrieved, it turns to None.
I have two columns, both are declared timestamps but one returns correct data while other returns None. Both utime and enddate are declared timestamps but utime does not return correctly while enddate does.
['utime', 'userstr', 'vstr_client', 'enddate']
((None, '000102030ff43260gg0809000000000004', '7.7.0', '1970-01-01 12:00:00.000000'))
def parse_data_and_description(cursor, data):
res = []
cols = [d[0] for d in cursor.description]
print cols
print data
for i in data:
res.append(OrderedDict(zip(cols, i)))
return res
def call_multi_rs(sp, args):
rs_id=0;
conn = connect()
cursor = conn.cursor()
try:
conn.autocommit(True)
cursor.execute ("CALL %s%s" % (sp, args))
while True:
rs_id+=1
data = cursor.fetchone( )
listout = parse_data_and_description(cursor, data)
print listout
if cursor.nextset( )==None:
# This means no more recordsets available
break
Finally after nobody answered or tried finding more information, I went ahead and looked for more solutions and found that the MySQLdb library converts the datatypes from sql to python and there is a bug which does not convert the timestamp.
I still do not know why one of them is converted and the other is not. If somebody can figure that out, please update this.
But here is the modification that needs to be done when connecting to the mysql database.
MySQLdb can't serialize a python datetime object
try:
import MySQLdb.converters
except ImportError:
_connarg('conv')
def connect(host='abc.dev.local', user='abc', passwd='def', db='myabc', port=3306):
try:
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
convert = dict(zip(conv_iter, [str,] * len(orig_conv.keys())))
print "Connecting host=%s user=%s db=%s port=%d" % (host, user, db, port)
conn = MySQLdb.connect(host, user, passwd, db, port, conv=convert)
except MySQLdb.Error, e:
print "Error connecting %d: %s" % (e.args[0], e.args[1])
return conn
I stumbled upon the same problem: Retrieving data of the DATETIME(1)-type returns None.
Some research brought up MySQLdb-Bug #325. According to that bug tracker, the issue is still open (has been for over 2 years now), but the comments provide a working solution:
In times.py of the MySQLdb package, you need to insert some lines to handle microseconds like this:
def DateTime_or_None(s):
if ' ' in s:
sep = ' '
elif 'T' in s:
sep = 'T'
else:
return Date_or_None(s)
try:
d, t = s.split(sep, 1)
if '.' in t:
t, ms = t.split('.',1)
ms = ms.ljust(6, '0')
else:
ms = 0
return datetime(*[ int(x) for x in d.split('-')+t.split(':')+[ms] ])
except (SystemExit, KeyboardInterrupt):
raise
except:
return Date_or_None(s)
def TimeDelta_or_None(s):
try:
h, m, s = s.split(':')
if '.' in s:
s, ms = s.split('.')
ms = ms.ljust(6, '0')
else:
ms = 0
h, m, s, ms = int(h), int(m), int(s), int(ms)
td = timedelta(hours=abs(h), minutes=m, seconds=s,
microseconds=ms)
if h < 0:
return -td
else:
return td
except ValueError:
# unpacking or int/float conversion failed
return None
def Time_or_None(s):
try:
h, m, s = s.split(':')
if '.' in s:
s, ms = s.split('.')
ms = ms.ljust(6, '0')
else:
ms = 0
h, m, s, ms = int(h), int(m), int(s), int(ms)
return time(hour=h, minute=m, second=s, microsecond=ms)
except ValueError:
return None
What I cannot explain, though, is your original query working on one column and not on the other.. Maybe, the second does not have any microsecond-information in it?