How to get the result of count in typedb / grakn? - vaticle-typedb

I'm trying to count the instances in the base with the python API:
q = '''match
$x isa processo;
get $x; count;'''
with TypeDB.core_client("localhost:1729") as client:
with client.session(keyspace, SessionType.DATA) as session:
with session.transaction(TransactionType.READ) as read_transaction:
result = read_transaction.query().match_aggregate(q)
print(result.get())
This prints:
<typedb.concept.answer.numeric._Numeric object at 0x00000256FCB8AA00>
How can I get the resulting number?

I got the right result using:
print(result.get().as_int())

Related

INVALID_REQUEST when I'm using page_token

I try to capture the info in a list on r when I'm using page_token in google_places
In general the short code is functional, but I can see in google.maps 65 results, and my code just return me 60 results.
key_word = 'McDonalds Bogota'
res <- google_places(search_string = key_word)
info <- list(res)
while (res$status == 'OK') {
Sys.sleep(1.5)
res <- google_places(search_string = '',
page_token = res$next_page_token)
info <- c(info,list(res))
}
I obtain a list with complete information in info[[1]], info[[2]] and info[[3]], but when I see info[[4]] I get status INVALID_REQUEST, so I want to see the final 5 observations in info[[4]] but I could not to do this
info[[3]] does not have a $next_page_token since the number of results caps at 60. So the following loop for info[[4]] will not have a valid token to request more results.
next_page_token contains a token that can be used to return up to 20
additional results. A next_page_token will not be returned if there
are no additional results to display. The maximum number of results
that can be returned is 60.
https://developers.google.com/places/web-service/search

how do I loop through nextToken

I just kind of figured out how to use the nextToken in boto3. The API call I am making I should expect about 300 entries. I only get 100. I know I need to loop through the next token but I am struggling on how to do that. I am new to the python army.
def myservers():
response = client.get_servers(maxResults=100,)
additional = client.get_servers(nextToken=response['nextToken'])
this little snipit will give me the first 50 plus the first 'nextToken' for a total of 100 items. Clearly I need to iterate over and over to get the rest. I am expecting 300 plus items.
I would just do a simple while loop:
response = client.get_servers()
results = response["serverList"]
while "NextToken" in response:
response = client.get_servers(NextToken=response["NextToken"])
results.extend(response["serverList"])
I used the suggestion here:
https://github.com/boto/botocore/issues/959#issuecomment-429116381
You have to keep calling client.get_servers() passing in the NextToken.
Derived from the answer #Luke mentioned, here is a simple method to call any method using the nextToken
def get_all_boto_records(method, args_dict, response_to_list):
all_records = []
extraArgs = {**args_dict}
while True:
resp = method(**extraArgs)
all_records += response_to_list(resp)
if "nextToken" in resp:
extraArgs["nextToken"] = resp["nextToken"]
else:
break
return all_records
Here is how to use it:
all_log_records = get_all_boto_records(
client.filter_log_events,
{
"logGroupName": "",
"filterPattern": "",
},
lambda x: x["events"],
)
Another great example with another method to get the log groups
all_log_groups = get_all_boto_records(
client.describe_log_groups,
{"logGroupNamePrefix": f"/aws/lambda/{q}"},
lambda x: x["logGroups"],
)

How do you use matrices in Nimrod?

I found this project on GitHub; it was the only search term returned for "nimrod matrix". I took the bare bones of it and changed it a little bit so that it compiled without errors, and then I added the last two lines to build a simple matrix, and then output a value, but the "getter" function isn't working for some reason. I adapted the instructions for adding properties found here, but something isn't right.
Here is my code so far. I'd like to use the GNU Scientific Library from within Nimrod, and I figured that this was the first logical step.
type
TMatrix*[T] = object
transposed: bool
dataRows: int
dataCols: int
data: seq[T]
proc index[T](x: TMatrix[T], r,c: int): int {.inline.} =
if r<0 or r>(x.rows()-1):
raise newException(EInvalidIndex, "matrix index out of range")
if c<0 or c>(x.cols()-1):
raise newException(EInvalidIndex, "matrix index out of range")
result = if x.transposed: c*x.dataCols+r else: r*x.dataCols+c
proc rows*[T](x: TMatrix[T]): int {.inline.} =
## Returns the number of rows in the matrix `x`.
result = if x.transposed: x.dataCols else: x.dataRows
proc cols*[T](x: TMatrix[T]): int {.inline.} =
## Returns the number of columns in the matrix `x`.
result = if x.transposed: x.dataRows else: x.dataCols
proc matrix*[T](rows, cols: int, d: openarray[T]): TMatrix[T] =
## Constructor. Initializes the matrix by allocating memory
## for the data and setting the number of rows and columns
## and sets the data to the values specified in `d`.
result.dataRows = rows
result.dataCols = cols
newSeq(result.data, rows*cols)
if len(d)>0:
if len(d)<(rows*cols):
raise newException(EInvalidIndex, "insufficient data supplied in matrix constructor")
for i in countup(0,rows*cols-1):
result.data[i] = d[i]
proc `[][]`*[T](x: TMatrix[T], r,c: int): T =
## Element access. Returns the element at row `r` column `c`.
result = x.data[x.index(r,c)]
proc `[][]=`*[T](x: var TMatrix[T], r,c: int, a: T) =
## Sets the value of the element at row `r` column `c` to
## the value supplied in `a`.
x.data[x.index(r,c)] = a
var m = matrix( 2, 2, [1,2,3,4] )
echo( $m[0][0] )
This is the error I get:
c:\program files (x86)\nimrod\config\nimrod.cfg(36, 11) Hint: added path: 'C:\Users\H127\.babel\libs\' [Path]
Hint: used config file 'C:\Program Files (x86)\Nimrod\config\nimrod.cfg' [Conf]
Hint: system [Processing]
Hint: mat [Processing]
mat.nim(48, 9) Error: type mismatch: got (TMatrix[int], int literal(0))
but expected one of:
system.[](a: array[Idx, T], x: TSlice[Idx]): seq[T]
system.[](a: array[Idx, T], x: TSlice[int]): seq[T]
system.[](s: string, x: TSlice[int]): string
system.[](s: seq[T], x: TSlice[int]): seq[T]
Thanks you guys!
I'd like to first point out that the matrix library you refer to is three years old. For a programming language in development that's a lot of time due to changes, and it doesn't compile any more with the current Nimrod git version:
$ nimrod c matrix
...
private/tmp/n/matrix/matrix.nim(97, 8) Error: ']' expected
It fails on the double array accessor, which seems to have changed syntax. I guess your attempt to create a double [][] accessor is problematic, it could be ambiguous: are you accessing the double array accessor of the object or are you accessing the nested array returned by the first brackets? I had to change the proc to the following:
proc `[]`*[T](x: TMatrix[T], r,c: int): T =
After that change you also need to change the way to access the matrix. Here's what I got:
for x in 0 .. <2:
for y in 0 .. <2:
echo "x: ", x, " y: ", y, " = ", m[x,y]
Basically, instead of specifying two bracket accesses you pass all the parameters inside a single bracket. That code generates:
x: 0 y: 0 = 1
x: 0 y: 1 = 2
x: 1 y: 0 = 3
x: 1 y: 1 = 4
With regards to finding software for Nimrod, I would like to recommend you using Nimble, Nimrod's package manager. Once you have it installed you can search available and maintained packages. The command nimble search math shows two potential packages: linagl and extmath. Not sure if they are what you are looking for, but at least they seem more fresh.

Scilab, get the last index of the maximum element in a vector

Given a vector, A=[1,2,10,10,10,1], [m,k]=max(A) returns k=3.
How to get the last index of the maximum element? In this example, I want to get 5.
The most succinct way I can think of is: [m,k]=max(A($:-1:1))
Is there a better way or does scilab provide a parameter to do this? Reversing a large vertex is not a good idea in any way.
Use the find command
You can use the find command to get all indices of the maximum:
indices = find(A==max(A))
last = max(indices)
Implement it yourself
Or if you want a single pass, you can implement it yourself:
//Create a c-function with your wanted behaviour
f1=['void max_array(int in_array[],int* in_num_elements,int *out_max, int *out_index)'
'{'
'int i;'
'*out_max=in_array[0];'
'*out_index=-1;'
'for (i=0; i<*in_num_elements; i++)'
'{'
'if(in_array[i]>=*out_max)'
'{'
'*out_max=in_array[i];'
'*out_index=i;'
'}'
'}'
'}'];
//Place it in a file in the current directory
mputl(f1,'max_array.c')
//Create the shared library (a gateway, a Makefile and a loader are
//generated.
ilib_for_link('max_array','max_array.c',[],"c")
//Load the library
exec loader.sce
//Create wrapper for readability
function [m,k] = last_max(vector)
[m, k] = call('max_array', vector, 1,'i', length(vector),2,'i', 'out',[1,1],3,'i',[1,1],4,'i');
// Because c is zero-indexed add 1
k = k + 1
endfunction
//Your data
A=[1,2,10,10,10,1];
//Call function on your data
[m,k] = last_max(A)
disp("Max value is " + string(m) + " at index " + string(k) )

mysqldb converts timestamp data to None

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?

Resources