I need to simulate the requests and responses being processed by a network of routers and began small by creating a server class:
class NBServer:
"""Name based content server"""
def __init__(self, _id):
self.id = _id
self.requests = deque('x')
self.responses = deque('x')
self.req_load = 0
self.res_load = 0
self.color = ''
self.forwarding_table = {}
self.content_store = {}
self.pending_table = {}
def __str__(self):
return 'current load: ' + str(req_load + req_load)
def request(self, content_name, requester_id):
self.requests.append((content_name, requester_ids))
self.req_load += 1
def response(self, content_name, content_url):
self.responses.append((content_url, destination_ids))
return ((content_url, destination_ids))
def process(self):
for req in self.requests:
# Case 1: content in cache
if content_name in self.content_store:
return self.content_name[content_name]
# Case 2: duplicate request exists
elif content_name in self.pending_table:
self.pending_table[content_name].append(requester_id)
# Case 3: add to PT, forward to next router
else:
self.pending_table[content_name] = [requester_id]
response = response.popleft()
if response:
for dest_id in self.pending_table[content_name]:
nodes[dest_id].response(content_name, content_url)
del self.pending_table[content_name]
However, now I am getting confused on how the communication between the routers can be represented:
Any advice on how to do this with NumPy?
Any help is greatly appreciated!
Related
I'm having trouble getting the updated value of a class variable.
When ConnectTestAPI is called after the p_request function is executed, the class variables which are result and orderNo should updated in the post function.
Then I want to receive the updated value of class variables by looping while statement in the p_request function.
However, despite setting the values of class variables with the post request, when the while statement is run, the corresponding values are still empty and 0 value respectively,
So, the while statement cannot be terminated and results in a time out error.
Here is my source code. Thank you in advance!
class ConnectTestAPI(APIView):
result=""
orderNo=0
def post(self, request):
data = request.data
ConnectTestAPI.result = data['result']
ConnectTestAPI.orderNo = data['orderNo']
print(ConnectTestAPI.result) # I could successfully get data from POST request here!
print(ConnectTestAPI.orderNo) # I could successfully get data from POST request here!
return HttpResponse("ok")
def p_request():
data = {
"a" : 1234,
"b" : 5678
}
data = json.dumps(data,ensure_ascii=False).encode('utf-8')
con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
con.set("data_dict", data)
while True:
if ConnectTestAPI.result != "" and ConnectTestAPI.orderNo != 0:
break
res_result = ConnectTestAPI.result
res_orderNo = ConnectTestAPI.orderNo
return res_result, res_orderNo
You need to access the class variables using self:
class ConnectTestAPI(APIView):
result=""
orderNo=0
def post(self, request):
data = request.data
self.result = data['result']
self.orderNo = data['orderNo']
print(self.result) # I could successfully get data from POST request here!
print(self.orderNo) # I could successfully get data from POST request here!
return HttpResponse("ok")
def p_request():
data = {
"a" : 1234,
"b" : 5678
}
data = json.dumps(data,ensure_ascii=False).encode('utf-8')
con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
con.set("data_dict", data)
while True:
if self.result != "" and self.orderNo != 0:
break
res_result = self.result
res_orderNo = self.orderNo
return res_result, res_orderNo
NOTE: This usage of class attributes is not recommended. You are mutating a class attribute which has side effects on all instances of that class. In your case, an ordinary attribute initialized within __ init__() would be ok:
class ConnectTestAPI(APIView):
def __init__(self):
self.result=""
self.orderNo=0
def post(self, request):
data = request.data
self.result = data['result']
self.orderNo = data['orderNo']
print(self.result) # I could successfully get data from POST request here!
print(self.orderNo) # I could successfully get data from POST request here!
return HttpResponse("ok")
def p_request():
data = {
"a" : 1234,
"b" : 5678
}
data = json.dumps(data,ensure_ascii=False).encode('utf-8')
con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
con.set("data_dict", data)
while True:
if self.result != "" and self.orderNo != 0:
break
res_result = self.result
res_orderNo = self.orderNo
return res_result, res_orderNo
I have the following function
import requests
children_dict = {}
def get_list_of_children(base_url, username, password, folder="1"):
token = get_token()
url = f"{base_url}/unix/repo/folders/{folder}/list"
json = requests_json(url,token)
for obj in json["list"]:
if obj['name'] == 'MainFolder':
folderId = obj['id']
url_parent = f"{base_url}/unix/repo/folders/{folderId}/list"
json_parent = requests_json(url_parent,token)
for obj_child in json_parent['list']:
if obj_child['folder'] == True:
folder_grand_child_id = obj_child['id']
url_grand_child = f"{base_url}/unix/repo/folders/{folder_grand_child_id}/list"
json_grand_child = requests_json(url_grand_child,token)
for obj_grand_child in json_grand_child["list"]:
if obj_grand_child['name'] == 'SubFolder':
folder_grand_grand_child = obj_grand_child['id']
url_grand_grand_child = f"{base_url}/unix/repo/folders/{folder_grand_grand_child}/list"
json_grand_grand_child = requests_json(url_grand_grand_child,token)
for obj_grand_grand_child in json_grand_grand_child["list"]:
if obj_grand_grand_child['name'] == 'MainTasks':
folder_grand_grand_grand_child = obj_grand_grand_child['id']
url_grand_grand_grand_child = f"{base_url}/unix/repo/folders/{folder_grand_grand_grand_child}/list"
json_grand_grand_grand_child = requests_json(url_grand_grand_grand_child,token)
for obj_grand_grand_grand_child in json_grand_grand_grand_child["list"]:
children_dict[[obj_grand_grand_grand_child['id']] = obj_grand_grand_grand_child['name']
return children_dict
What i am trying to accomplish here is to make repeated api calls to traverse through http folder structure to get the list of files in the last directory
The function works as intended but sonarlint is through the below error
Refactor this function to reduce its Cognitive Complexity from 45 to the 15 allowed. [+9 locations]sonarlint(python:S3776)
is there is a better way to handle this function ?
can anyone refactor this, pointing me in the right direct will do
This isn't a complete solution, but to answer your question "how can I simplify this" more generally, you need to look for repeated patterns in your code and generalize them into a function. Perhaps it's a function you can call recursively, or in a loop. For example, in that deeply-nested statement of yours it's just the same pattern over and over again like:
url = f"{base_url}/unix/repo/folders/{folder}/list"
json = requests_json(url,token)
for obj in json["list"]:
if obj['name'] == '<some folder name>':
folderId = obj['id']
# ...repeat...
So try generalizing this into a loop, maybe, like:
url_format = "{base_url}/unix/repo/folders/{folder_id}/list"
folder_hierarchy = ['MainFolder', 'SubFolder', 'MainTasks']
folder_id = '1' # this was the argument passed to your function
for subfolder in folder_hierarchy:
url = url_format.format(base_url=base_url, folder_id=folder_id)
folder_json = requests_json(url, token)
for obj in folder_json['list']:
if obj['name'] == subfolder:
folder_id = obj['id']
break
# Now the pattern repeats for the next level of the hierarchy but
# starting with the new folder_id
This is just schematic and you may need to generalize further, but it's one idea.
If your goal is to traverse a more complicated hierarchy you might want to look into tree-traversal algorithms.
There's plenty of repeating code. Once you identify the repeating patterns, you can extract them to the classes and functions. In particular, I find it useful to isolate all the web API logic from the rest of the code:
class Client:
def __init__(self, base_url, token):
self.base_url = base_url
self.token = token
def list_folder(self, folder_id):
return request_json(
f'{self.base_url}/unix/repo/folders/{folder_id}/list', self.token
)['list']
def get_subfolders(self, parent_id=1):
return [c for c in self.list_folder(parent_id) if c['folder']]
def get_subfolder(self, parent_id, name):
children = self.list_folder(parent_id)
for child in children:
if child['name'] == name:
return child
return None
def resolve_path(self, path, root_id=1):
parent_id = root_id
for p in path:
current = self.get_subfolder(parent_id, p)
if not current:
return None
parent_id = current['id']
return current
Now you can use the class above to simplify the main code:
client = Client(base_url, token)
for folder in client.get_subfolders():
child = client.resolve_path(folder['id'], ('SubFolder', 'MainTasks'))
if child:
# do the rest of the stuff
The code above is not guaranteed to work as is, just an illustration of the idea.
I can't really test it, but I'd make it like the following in order to easily build many levels of repeating code.
class NestedProcessing:
def __init__(self, base_url):
self.base_url = base_url
self.token = get_token()
self.obj_predicates = []
def next_level_predicate(self, obj_predicate):
self.obj_predicates.append(obj_predicate)
return self
def final_action(self, obj_action):
self.obj_action = obj_action
return self
def process(self, first_folder_id):
self.process_level(0, first_folder_id)
def process_level(self, index, folder_id):
obj_is_good = self.obj_predicates[index]
url = f"{self.base_url}/unix/repo/folders/{folder_id}/list"
json = requests_json(url, self.token)
for obj in json["list"]:
if index == len(self.obj_predicates) - 1: # last level
self.obj_action(obj)
elif obj_is_good(obj):
self.process_level(index + 1, obj['id'])
def get_list_of_children(base_url, username, password, folder="1"):
children_dict = {}
NestedProcessing(base_url)
.next_level_predicate(lambda obj: obj['name'] == 'MainFolder')
.next_level_predicate(lambda obj: obj['folder'] == True)
.next_level_predicate(lambda obj: obj['name'] == 'SubFolder')
.next_level_predicate(lambda obj: obj['name'] == 'MainTasks')
.final_action(lambda obj, storage=children_dict: storage.update({obj['id']: obj['name']})
.process(folder)
return children_dict
I am trying to create my own blockchain using python.
I took this source code and I am trying to tweak it to fit what I need.
My code:
import datetime
import hashlib
class Block:
def __init__(
self,
previous_block_hash,
data,
timestamp,
sender,
):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
self.hash = self.get_hash()
self.sender = self.get_sender()
#staticmethod
def create_genesis_block():
return Block('0', '0', datetime.datetime.now(), '')
def get_sender(self):
self.sender = input('Enter senders ID number: ')
return self.sender
def get_hash(self):
header_bin = str(self.previous_block_hash) + str(self.data) \
+ str(self.timestamp) + str(self.sender)
inner_hash = \
hashlib.sha256(header_bin.encode()).hexdigest().encode()
outer_hash = hashlib.sha256(inner_hash).hexdigest()
return outer_hash
blockchain = [Block.create_genesis_block()]
length_of_blockchain = len(blockchain)
print ('The genesis block has been created.')
print ('Hash: %s' % blockchain[0].hash)
blockchain.append(Block(blockchain[length_of_blockchain - 1].hash,
'Blockchain Number: '[length_of_blockchain - 1],
datetime.datetime.now(), Block.get_sender()))
I want to add a sender and receiver to the Block. So, I started out with one first and that is the sender. I keep getting this error here and I am not sure how to fix it. Everything is being tested locally to make sure everything checks out then I will add react native to it. Hoping someone can help me
You're trying to access self.sender before initializing it. Reordering initialization might help us here.
import datetime
import hashlib
class Block:
def __init__(
self,
previous_block_hash,
data,
timestamp,
sender,
):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
#reordering self.hash and self.sender as self.get_sender() references to self.sender
self.sender = self.get_sender()
self.hash = self.get_hash()
#staticmethod
def create_genesis_block():
return Block('0', '0', datetime.datetime.now(), '')
def get_sender(self):
self.sender = input('Enter senders ID number: ')
return self.sender
def get_hash(self):
header_bin = str(self.previous_block_hash) + str(self.data) \
+ str(self.timestamp) + str(self.sender)
inner_hash = \
hashlib.sha256(header_bin.encode()).hexdigest().encode()
outer_hash = hashlib.sha256(inner_hash).hexdigest()
return outer_hash
hope this helps
I am trying add a stop loss order along with a buy order using Oanda's REST API. As of right now I can easily specify a price for a stop loss, however, I would like to calculate my stop based on the current price. For instance "current_price" + .1 . I am not very familiar with Python, hence the simple question, but this is driving me nuts. Any help would be appreciated!
I get this error code (along with many others when I try and fix the problem)
trading.py", line 41, in <module>
stopLoss = float("bid") -- float(.01)
ValueError: could not convert string to float: bid
Thanks in advance, code as follows
trading.py
import Queue
import threading
import time
from execution import Execution
from settings import STREAM_DOMAIN, API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID
from strategy import TestRandomStrategy
from streaming import StreamingForexPrices
def trade(events, strategy, execution):
"""
Carries out an infinite while loop that polls the
events queue and directs each event to either the
strategy component of the execution handler. The
loop will then pause for "heartbeat" seconds and
continue.
"""
while True:
try:
event = events.get(False)
except Queue.Empty:
pass
else:
if event is not None:
if event.type == 'TICK':
strategy.calculate_signals(event)
elif event.type == 'ORDER':
print "Executing order!"
execution.execute_order(event)
time.sleep(heartbeat)
if __name__ == "__main__":
heartbeat = 0 # Half a second between polling
events = Queue.Queue()
# Trade 1000 unit of EUR/USD
instrument = "EUR_USD"
units = 1000
stopLoss = float("bid") -- float(.01)
# Create the OANDA market price streaming class
# making sure to provide authentication commands
prices = StreamingForexPrices(
STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
instrument, events
)
# Create the execution handler making sure to
# provide authentication commands
execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)
# Create the strategy/signal generator, passing the
# instrument, quantity of units and the events queue
strategy = TestRandomStrategy(instrument, units, events, stopLoss)
# Create two separate threads: One for the trading loop
# and another for the market price streaming class
trade_thread = threading.Thread(target=trade, args=(events, strategy, execution))
price_thread = threading.Thread(target=prices.stream_to_queue, args=[])
# Start both threads
trade_thread.start()
price_thread.start()
execution.py
import httplib
import urllib
class Execution(object):
def __init__(self, domain, access_token, account_id):
self.domain = domain
self.access_token = access_token
self.account_id = account_id
self.conn = self.obtain_connection()
def obtain_connection(self):
return httplib.HTTPSConnection(self.domain)
def execute_order(self, event):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + self.access_token
}
params = urllib.urlencode({
"instrument" : event.instrument,
"units" : event.units,
"type" : event.order_type,
"side" : event.side,
"stopLoss" : event.stopLoss
})
self.conn.request(
"POST",
"/v1/accounts/%s/orders" % str(self.account_id),
params, headers
)
response = self.conn.getresponse().read()
print response
Event.py
class Event(object):
pass
class TickEvent(Event):
def __init__(self, instrument, time, bid, ask):
self.type = 'TICK'
self.instrument = instrument
self.time = time
self.bid = bid
self.ask = ask
class OrderEvent(Event):
def __init__(self, instrument, units, order_type, side, stopLoss):
self.type = 'ORDER'
self.instrument = instrument
self.units = units
self.order_type = order_type
self.side = side
self.stopLoss = stopLoss
Strategy.py
import random
from event import OrderEvent
class TestRandomStrategy(object):
def __init__(self, instrument, units, events, stopLoss):
self.instrument = instrument
self.units = units
self.events = events
self.ticks = 0
self.stopLoss = stopLoss
def calculate_signals(self, event):
if event.type == 'TICK':
self.ticks += 1
if self.ticks % 1 == 0:
side = random.choice(["buy"])
order = OrderEvent(
self.instrument, self.units, "market", side, self.stopLoss
)
self.events.put(order)
Thanks again..
If you want to combine string and you should convert float to string
""+str(.1)
from datetime import datetime
class sms_store:
store = []
read = []
def add_new_arrival(self,number,time,text):
sms_store.read.append(len(sms_store.store))
sms_store.store.append(("From: {}, Recieved: {}, Msg: {}".format(number,time,text)))
def delete(self,i):
try:
del sms_store.store[i]
except IndexError:
print("Index is out of range. Cannot delete")
def message_count(self):
return print("Amt of messages in inbox: {}".format(len(sms_store.store)))
def viewall(self):
print(sms_store.store)
def get_unread_indexes(self):
#### ###################################I need help for this method.
def get_message(self,i)
print(sms_store.store[i])
### tests ####
time = datetime.now().strftime('%H:%M:%S')
my_inbox = sms_store() #instantiate an object 'store' for class
my_inbox.add_new_arrival("12345",time,"Hello how are you?") #instance of store object
my_inbox.add_new_arrival("1111111",time,"BYE BYE BYE")
my_inbox.viewall()
my_inbox.msgcount()
Thanks for viewing this.
This is what I need to do:
my_inbox.add_new_arrival()
When adding a new message, its has_been_viewed status is set False.
my_inbox.get_unread_indexes()
Returns list of indexes of all not-yet-viewed SMS messages
my_inbox.get_message(i)**
Return (from_number, time_arrived, text_of_sms) for message[i]
Also change its state to "has been viewed".
If there is no message at position i, return None
Please help me on those above methods!?
Thank you so much!
Hi I tweaked your code a bit, I think I have done this before in the "How to think like a computer Scientist Book", Hope it works for you.
from datetime import datetime
and
class SMS_store:
then
def __init__(self):
self.store = []
def __str__(self):
return ("{0}".format(self))
def add_new_arrival(self, number, time, text ):
self.store.append(("Read: False", "From: "+number, "Recieved: "+time, "Msg: "+text))
def message_count(self):
return (len(self.store))
def get_unread_indexes(self):
result = []
for (i, v) in enumerate(self.store):
if v[0] == "Read: False":
result.append(i)
return (result)
def get_message(self, i):
msg = self.store[i]
msg = ("Read: True",) + msg[1:]
self.store[i] = (msg)
return (self.store[i][1:])
def delete(self, i):
del self.store[i]
def clear(self):
self.store = []
Why don't you add another list to your class called unread. Change add_new_arrival to add the message to unread.
Then under the get_message method move the specified message from unread to read.
Lastly your get_unread method just lists the indexes of the unread list.
Python SMS store program using class and methods - has_been_viewed status
import time
class SMS_store:
def __init__(self):
self.inbox = []
def add_new_arrival(self, from_number, text_of_sms,read_status = False):
number = str(from_number)
time_received = time.strftime("%D %T")
self.inbox.append([time_received, number, text_of_sms, read_status])
def message_count(self):
return "There are {0} messages in your Inbox".format(len(self.inbox))
def get_unread_indexes(self):
unread = []
for index, message in enumerate(self.inbox):
if False in message:
unread.append(index)
return "Unread Messages in:", unread
def get_message(self, index):
message = self.inbox[index]
message[3] = "Read"
return message[ : 3]
def delete(self, index):
del self.inbox[index]
return "Deleted Message", index
def clear(self):
self.inbox = []
return "Empty Inbox"