Use 2 CALLS in the same query - database

I need to get the return of the first CALL, keep it in a variable and use it for a second CALL.
For example, I want to know how many laws were proposed at the 114th Congress, and how many of these are currently active?
`
MATCH (b:Bill)
CALL{
MATCH (b)-[:PROPOSED_DURING]->(c:Congress)
WHERE c.number = '114'
RETURN b as bills
}
WITH bills
CALL {
MATCH (bills)
WHERE bills.active = 'True'
RETURN bills as activeBills
}
return count(bills), count(activeBills)
`
Bill are the laws, which are proposed during a congress.
Do you know why this is not working properly as it just remains loading without ending?

The query is doing a triple cartesian product on the number of bills, number of bills proposed in 144th congress and active bills on that session. That is why the query is just loading endlessly.
n(Bills) x n(bills in 114th Congress) x n(active bills in 114th Congress) = big number
I would propose an alternative solution without using CALL function.
MATCH (b:Bill)-[:PROPOSED_DURING]->(c:Congress) WHERE c.number = '114'
WITH collect(b) as bills
RETURN size(bills) as billCounts, size([b in bills where b.active = 'True'|b]) as activeBillCounts
Going back to your query, below is the fix on your query and it is quite wordy. The problem was within the CALL function, you need to add another line WITH b so that the bills will be passed within the CALL function. Without it (With b inside the CALL function), it will do a cartesian product on ALL bills x Bills in 114th congress. On the 2nd CALL function, you need to collect the bills and UNWIND it inside 2nd CALL function. This is because using the same variable bills from 1st CALL function to 2nd CALL function will filter the bills and you will get incorrect count. This is because using the same variables between two CALLS will also remove Inactive bills on the 2nd CALL.
MATCH (b:Bill)
CALL{
WITH b // <- please add this line
MATCH (b)-[:PROPOSED_DURING]->(c:Congress)
WHERE c.number = '114'
RETURN b as bills
}
WITH collect(b) as bills // <- please add this line
CALL { WITH bills // <- please add this line
UNWIND bills as bill // <- please add this line
MATCH (bill)
WHERE bill.active = 'True'
RETURN bill as activeBills
}
return size(bills), count(activeBills)

Related

How to make it roll multiple times

I am trying to be able to have a person specify how many sets of dice they want to roll. at present if they want to roll three sets of a d100 they have to enter the command 3 times. I want to be able to have them enter an amount like !3d100 and have it roll it 3 times?
#client.command(name='d100', help='Rolls a d100 sice')
async def dice(context):
diceEmbed = discord.Embed(title="Rolling for " + str(context.message.author.display_name), color=0xCC5500)
roll = (random.randint(1, 100))
url = "http://157.230.225.61/images/dice/d100/d100_{:03}.png"
url = url.format(roll)
diceEmbed.set_image(url=url)
diceEmbed.add_field(name="d100", value=roll, inline=True)
if roll == 1:
diceEmbed.set_footer(text="FUMBLE")
await context.message.channel.send(embed=diceEmbed)
First of all consider using f string. You will have to add a input to your command !dice 3 This will give you 3 rolls if no amount given only 1.
Keep in mind in embed you can only place one image so i took the highest according to you.
#bot.command()
async def dice(ctx, amount: int = 1):
diceEmbed = discord.Embed(title=f"Rolling for {ctx.message.author.display_name}", color=0xCC5500)
max_roll = 0
for i in range(amount):
roll = (random.randint(1, 100))
if roll > max_roll:
url = f"http://157.230.225.61/images/dice/d100/d100_{roll:03d}.png"
max_roll = roll
diceEmbed.add_field(
name=f"Role number {i+1}", value=roll, inline=False)
if roll == 1:
diceEmbed.set_footer(text="FUMBLE")
# You can have only one image which is the highest
diceEmbed.set_image(url=url)
await ctx.message.channel.send(embed=diceEmbed)

How to build an array comprised of two others using only particular elements of each?

I writing a little program to generate some bogus top-ten sales numbers for book sales. I'm trying to do this in as compact a fashion as possible and do it without using MySQL or another DB.
I have written out what I want to happen. I've created a bogus catalog array and a bogus sales array corresponding sales to the index of the catalog entries. That part all works great.
I want to create a third array that includes all the titles from the catalog array with the sales numbers from the sales array, like a join in a DB, but without any DB. I can't figure out how to do that part of it though. I think once I have it in there I can sort it the way I want it, but making that third array is killing. I cannot figure out what I'm doing wrong or how to do it right.
So given the following code:
require 'random_word'
class BestOnline
def initialize
#catalog = Array.new
#sales = Array.new
#topten = Array.new
inventory = rand(50) + 10
days = rand(1..50)
now = Time.now
yesterday = now - 86400
saleshistory = now - (days * 86400)
(1..inventory).each do
#catalog << {
:title => "#{RandomWord.adjs.next.capitalize} #{RandomWord.nouns.next.capitalize}",
:price => rand(5.99..29.99).round(2)}
end
(0..days).each do
#sales << {
:id => rand(0..#catalog.count),
:salescount => rand(0..24),
:date => rand(saleshistory..now) }
end
end
def bestsellers
#sales.each do
# THIS DOESNT WORK AND I'M STUCK AS HOW TO FIX IT.
# #topten << {
# :title => #catalog[:id],
# :salescount => #sales[:salescount]
# }
end
puts #topten.group_by{ |tt| tt[:salescount]}.sort_by{ |k,v| -k}.first(10)
end
end
BestOnline.new.bestsellers
How can I create a third array that contains the titles and number of sales and output the result of the top-ten books sold?
Try this out:
def bestsellers
#sales.each do |sale|
#topten << {
title: #catalog[sale[:id]][:title],
salescount: sale[:salescount] }
end
#topten.sort! { |x, y| y[:salescount] <=> x[:salescount] }
puts #topten.first(10)
end
I suggest you write:
def bestsellers(sales)
sales.max_by(10) { |h| h[:salescount][:salescount]] }
end
puts bestsellers(sales)
Enumerable#max_by was permitted to have an argument in Ruby v2.2.
There are several problems with the way you've structured your code. Now that you have running code (by incorporating #fbonds66's answer), I suggest you post it at SO's sister-site Code Review. The purpose of CR is to suggest improvements to working code. If you read through some of the questions and answers there I think you will be impressed.
I was doing the dereferencing wrong trying to build the 3rd array of the 1st two:
#sales.each do |sale|
#topten << {
:title => #catalog[sale[:id]][:title],
:salescount => sale[:salescount]
}
end
I needed to work on the hash returned from .each as |sale| and use correct syntax to get what I was after from the other arrays.

Matlab string manipulation

I need help with matlab using 'strtok' to find an ID in a text file and then read in or manipulate the rest of the row that is contained where that ID is. I also need this function to find (using strtok preferably) all occurrences of that same ID and group them in some way so that I can find averages. On to the sample code:
ID list being input:
(This is the KOIName variable)
010447529
010468501
010481335
010529637
010603247......etc.
File with data format:
(This is the StarData variable)
ID>>>>Values
002141865 3.867144e-03 742.000000 0.001121 16.155089 6.297494 0.001677
002141865 5.429278e-03 1940.000000 0.000477 16.583748 11.945627 0.001622
002141865 4.360715e-03 1897.000000 0.000667 16.863406 13.438383 0.001460
002141865 3.972467e-03 2127.000000 0.000459 16.103060 21.966853 0.001196
002141865 8.542932e-03 2094.000000 0.000421 17.452007 18.067214 0.002490
Do not be mislead by the examples I posted, that first number is repeated for about 15 lines then the ID changes and that goes for an entire set of different ID's, then they are repeated as a whole group again, think [1,2,3],[1,2,3], the main difference is the values trailing the ID which I need to average out in matlab.
My current code is:
function Avg_Koi
N = evalin('base', 'KOIName');
file_1 = evalin('base', 'StarData');
global result;
for i=1:size(N)
[id, values] = strtok(file_1);
result = result(id);
result = result(values)
end
end
Thanks for any assistance.
You let us guess a lot, so I guess you want something like this:
load StarData.txt
IDs = { 010447529;
010468501;
010481335;
010529637;
010603247;
002141865}
L = numel(IDs);
values = cell(L,1);
% Iteration through all arrays and creating an cell array with matrices for every ID
for ii=1:L;
ID = IDs{ii};
ID_first = find(StarData(:,1) == ID,1,'first');
ID_last = find(StarData(:,1) == ID,1,'last');
values{ii} = StarData( ID_first:ID_last , 2:end );
end
When you now access the index ii=6 adressing the ID = 002141865
MatrixOfCertainID6 = values{6};
you get:
0.0038671440 742 0.001121 16.155089 6.2974940 0.001677
0.0054292780 1940 0.000477 16.583748 11.945627 0.001622
0.0043607150 1897 0.000667 16.863406 13.438383 0.001460
0.0039724670 2127 0.000459 16.103060 21.966853 0.001196
0.0085429320 2094 0.000421 17.452007 18.067214 0.002490
... for further calculations.

How to update a Mnesia table in Erlang

I have a little problem with my code. I have a table containing car details, name, price and quantity, so I am trying to create a function called buy which will be used to buy a specific car. When a user buys eg 5 BMW cars, they will call buy_car(bmw,5). Now after this I want to update the new value of quantity for BMW cars.
My attempt is below but I can't seem to work around it, I am new to Erlang.
buy_car(X,Ncars) ->
F = fun() ->
%% ----first i find the number of car X available in the shop
[Xcars] = mnesia:read({car,X}),
Nc = Xcars#car.quantity,
Leftcars = Xcars#car{quantity = Nc - Ncars},
%% ---now we update the database
mnesia:write(Leftcars),
end,
mnesia:transaction(F).
Please help me with how I can write a function that buys cars from the shop.
But your implementation works fine except you added illegal comma after mnesia:write(Leftcars).
Here is code that works (I tried your implementation as buy_car2).
-module(q).
-export([setup/0, buy_car/2, buy_car2/2]).
-record(car, {brand, quantity}).
setup() ->
mnesia:start(),
mnesia:create_table(car, [{attributes, record_info(fields, car)}]),
mnesia:transaction(fun() -> mnesia:write(#car{brand=bmw, quantity=1000}) end).
buy_car(Brand, Ncars) ->
F = fun() ->
[Car] = mnesia:read(car, Brand), % crash if the car is missing
mnesia:write(Car#car{quantity = Car#car.quantity - Ncars})
end,
mnesia:transaction(F).
buy_car2(X,Ncars) ->
F = fun() ->
%% ----first i find the number of car X available in the shop
[Xcars] = mnesia:read({car,X}),
Nc = Xcars#car.quantity,
Leftcars = Xcars#car{quantity = Nc - Ncars},
%% ---now we update the database
mnesia:write(Leftcars)
end,
mnesia:transaction(F).
I would do something like below:
Considering the record is defined as :
-record(car_record, {car, quantity}).
The following function will update the data:
buy_car(X,NCars) ->
Row = #car_record{car = X, quantity = NCars}.
mnesia:ets(fun()-> mnesia:dirty_write(Row) end),
mnesia:change_table_copy_type(guiding_data, node(), disc_copies).
To use the above method, mnesia table must be created as "ram_copies" and with no replication nodes. Also, if there are lot of updates happening, you might not want to copy the ram_copies to disk for every update due to performance issues, rather you will do it in time triggered manner.

How to do a "while quantity is greater than zero loop"

So I am using a gift certificate module with satchmo store and in order to send multiple gift certificate codes equal to the number of items purchased I need to add a loop doing
"while quantity is greater than zero loop"
Here is the code, the loop is being added to right before "price=order_item.unit_price"
def order_success(self, order,
order_item):
log.debug("Order success called, creating gift certs on order:
%s", order)
message = ""
email = ""
for detl in order_item.orderitemdetail_set.all():
if detl.name == "email":
email = detl.value
elif detl.name == "message":
message = detl.value
price=order_item.unit_price
log.debug("Creating gc for %s", price)
gc = GiftCertificate(
order = order,
start_balance= price,
purchased_by = order.contact,
valid=True,
message=message,
recipient_email=email
)
gc.save()
I am not sure I understand the question, but maybe something like
for ix in range(0, order_item.quantity):
... do stuff
might do the trick. You don't have to use the ix anywhere inside the loop, it is just (arguably) the standard way to do something n times in Python.

Resources