def setUp(self): self.client = Redis(decode_responses=True) self.client.flushdb() self.peter = Relationship(self.client, "peter") self.jack = Relationship(self.client, "jack") self.common_following = CommonFollowing(self.client)
def testinsertRelationship(): #relationship 1 print("yes") r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None) # dao.insertRelationship(r) r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None) dao.insertRelationship(r)
def testInsertRelationshipNoneType(self): r = Relationship(None, "101010", "Checked Out", "2021-01-01 01:01:01", None, None) rc, msg = self.dao.insertRelationship(r) self.assertFalse(rc) r = Relationship("*****@*****.**", None, "Checked Out", "2021-01-01 01:01:01", None, None) rc, msg = self.dao.insertRelationship(r) self.assertFalse(rc) r = Relationship("*****@*****.**", "101010", None, "2021-01-01 01:01:01", None, None) rc, msg = self.dao.insertRelationship(r) self.assertFalse(rc)
def selectPendingReturns(self): try: logging.info("Entering selectPendingReturns") sql = "SELECT * from hascontainer WHERE status = 'Pending Return' " myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult #myresult = myresult[1] #print(myresult) temp = [] for x in myresult[1]: email = x[0] qrcode = x[1] status = x[2] statusUpdateTime = str(x[3]) location_qrcode = x[4] descrption = x[5] r = Relationship(email, qrcode, status, statusUpdateTime, location_qrcode, descrption) temp.append(r) #print(temp) logging.info("selectPendingReturns successful") return True, temp except Exception as e: logging.error("Error in selectPendingReturns") logging.error(str(e)) return self.handleError(e)
def selectAllByEmail(self, email): try: logging.info("Entering selectAllByEmail") #select all tuples that are from this one user sql = "SELECT * from hascontainer WHERE email = '" + email + "'" myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult temp = [] for x in myresult[1]: email = x[0] qrcode = x[1] status = x[2] statusUpdateTime = str(x[3]) location_qrcode = x[4] descrption = x[5] r = Relationship(email, qrcode, status, statusUpdateTime, location_qrcode, descrption) temp.append(r) logging.info("selectAllByEmail successful") return True, temp except Exception as e: logging.error("Error in selectAllByEmail") logging.error(str(e)) return self.handleError(e)
def selectActiveQRcode(self, qrcode): try: logging.info("Entering selectActiveQRcode") sql = "SELECT * from hascontainer WHERE qrcode = '" + qrcode + "' and status != 'Verified Return'" myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult #myresult = myresult[1] temp = [] for x in myresult[1]: email = x[0] qrcode = x[1] status = x[2] statusUpdateTime = str(x[3]) location_qrcode = x[4] descrption = x[5] r = Relationship(email, qrcode, status, statusUpdateTime, location_qrcode, descrption) temp.append(r) logging.info("selectActiveQRcode successful") return True, temp except Exception as e: logging.error("Error in selectActiveQRcode") logging.error(str(e)) return self.handleError(e)
def testUpdateStatusNotValid(self): """ Test that we cannot update a status that is not: Checked Out | Pending Return | Verified Return | Damaged Lost """ rc, msg = self.testInsertRelationshipSmoke() self.assertTrue(rc) r = Relationship("*****@*****.**", "101010", "WRONG STATUS", "2021-01-01 01:01:01", None, "Pending Return") rc, updateRelationship = self.dao.updateRelationship(r) self.assertFalse(rc) r.status = "Checked out" rc, updateRelationship = self.dao.updateRelationship(r) self.assertFalse(rc) r.status = "pending return" rc, updateRelationship = self.dao.updateRelationship(r) self.assertFalse(rc) r.status = "VERIFIED RETURN" rc, updateRelationship = self.dao.updateRelationship(r) self.assertFalse(rc)
def rnn(filename): bucket_name = "novelnet" coref = Coref() print("job " + filename + " is started") s3 = boto3.resource('s3') s3.Object("novelnet", filename).download_file("test") with open("test", 'r') as f: text = f.read() #print(text) relationship = Relationship(id=filename, pipeline=coref, text=text, threshold=20, verbose=False) relationship.report() doc_name = 'doc' + filename + '.pkl' clusters_name = 'clusters' + filename + '.pkl' mentions_name = 'mentions' + filename + '.pkl' ner_name = 'ner' + filename + '.txt' s3.Object(bucket_name, "results/" + doc_name).upload_file(doc_name) s3.Object(bucket_name, "results/" + clusters_name).upload_file(clusters_name) s3.Object(bucket_name, "results/" + mentions_name).upload_file(mentions_name) s3.Object(bucket_name, "results/" + ner_name).upload_file(ner_name) os.remove("status") os.remove("test") print("job " + filename + " is finished")
def testDeleteRelationship(self): """ Test that we can delete a relationship that exists in the database already """ rc, msg = self.testInsertRelationshipSmoke() self.assertTrue(rc) r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None, None) rc, deleteRelationship = self.dao.deleteRelationship(r) self.assertTrue(rc) r = Relationship("*****@*****.**", "101010", "Damaged Lost", "2021-01-01 01:01:01", None, None) rc, msg = self.dao.insertRelationship(r) self.assertTrue(rc) rc, deleteRelationship = self.dao.deleteRelationship(r) self.assertTrue(rc)
def testInsertQRCodeTooLong(self): """ Test that we cannot add a QR code that is over 45 characters long """ r = Relationship("*****@*****.**", "101010xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "Checked Out", "2021-01-01 01:01:01", None, None) self.dao = RelationshipDAO() rc, insertRelationship = self.dao.insertRelationship(r) self.assertFalse(rc)
def testUpdateRelationship(self): """ Test that we can update a relationship that exists in the database already """ rc, msg = self.testInsertRelationshipSmoke() self.assertTrue(rc) #r = Relationship("*****@*****.**","101010","Pending Return","2021-01-01 01:01:01",None,"Pending Return") r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None, None) rc, updateRelationship = self.dao.updateRelationship(r) self.assertTrue(rc)
def generate_book(num): date = datetime.date.fromisoformat('2010-12-01') for i in range(num): logging.debug(f"Chapter {str(i + 1)}") # Print HTML header print(f''' <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id='container'> <div id='wrapper'> ''') print(f'<h4>Chapter {str(i + 1)}</h4>') new_person = generate_person() r = Relationship(protagonist, new_person, date) r.simulate() r.simulate_reflection() date = r.events[len(r.events) - 1]['date'] relationship_narrator.narrate(r) if (r.phase == Phase.COURTING and random.random() < 0.5) or (r.phase == Phase.DATING): print(f'<h4>Chapter {str(i + 1.5)}</h4>') print(epilogue.get_epilogue(r, date)) # Print HTML closing tags print(f''' <p><a href="{i+1}.html">Next</a></p> </div> </div> <div id="bar"> <h5 id="debug">Hide debug 🥵</h5> <h4>ALEX 1.0</h4> <a href="/">home</a><br> <a href="process.html">about</a><br> <a href="https://github.com/c-dacanay/nanogenmo"><img id="github" src="https://image.flaticon.com/icons/png/512/25/25231.png" width="20" height="20"></a> <div id="toc"></div> </div> <script src="script.js"></script> </body> </html> ''') # Print separator line so that we can turn this into multiple # HTML files later print('|')
def tearDown(self): """ Delete the temporary database """ r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None, None) # r is relationship object self.dao.deleteRelationship(r) r.status = "Verified Return" self.dao.deleteRelationship(r) r.status = "Damaged Lost" self.dao.deleteRelationship(r) r.status = "Pending Return" self.dao.deleteRelationship(r)
def testInsertStatusNotValid(self): """ Test that we cannot add a status that is not: Checked Out | Pending Return | Verified Return | Damaged Lost """ r = Relationship("*****@*****.**", "101010", "TEST WRONG STATUS", "2021-01-01 01:01:01", None, None) self.dao = RelationshipDAO() rc, insertRelationship = self.dao.insertRelationship(r) self.assertFalse(rc) """ Test that we cannot add a status that is over 45 characters long """ r = Relationship("*****@*****.**", "101010", "Checked out xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "2021-01-01 01:01:01", None, None) self.dao = RelationshipDAO() rc, insertRelationship = self.dao.insertRelationship(r) self.assertFalse(rc)
def testInsertDescTooLong(self): """ Test that we cannot add a description that is more than 128 characters long. """ r = Relationship( "*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", "L043", "paloeklslslslslslslslslslslslslslslslslslslslaeowlsosjdoskejepspsosdksdkfjsldkflaksdjflkjasdkfjaskjdflkjasdfljsadkfjkasndfklasjndfkaskjldflsadfnlkajsndfknasldkjfnalksjdnflkjasndlkfjnsakjdnfkaslndfkljsandfkjnka" ) self.dao = RelationshipDAO() rc, insertRelationship = self.dao.insertRelationship(r) self.assertFalse(rc)
def unidirectional_network(redditor: str, reddit_interactions: DataFrame) -> nx.Graph: ''' Construct unidirectional reddit reply network. Edge exists between two users if either has interacted with the other (A replied to B, B replied to A, or A replied to B and B replied to A. ''' G = nx.Graph(user=redditor) for index, row in reddit_interactions.iterrows(): author = row['author'] subreddit = row['subreddit'] date = row['date'].to_pydatetime() replying_to = row['replyingTo'] polarity = row['polarity'] subjectivity = row['subjectivity'] reply_count = int(row['replyCount']) # Node if not G.has_node(author): G.add_node(author, membership=Membership()) elif not 'membership' in G.node[author]: G.node[author]['membership'] = Membership() G.node[author]['membership'].append(subreddit, date) # Edge # If not replying to anyone (submission is used in membership attribute but not relationship attribute) if replying_to is None: continue # Don't put self loops in graph if replying_to == author: continue # If edge is new: add edge to graph and construct Relationship object if not G.has_edge(author, replying_to): G.add_edge(author, replying_to, relationship=Relationship()) # Append comment data to Relationship attribute of edge G[author][replying_to]['relationship'].append(author, replying_to, subreddit, date, polarity, subjectivity, reply_count) # Remove nodes on periphery of network (not connected to central user) G.remove_nodes_from([ user for user, membership in G.nodes(data='membership') if membership is None ]) return G
def updateRelationship(self, r): try: myresult = self.checkStatus(r) if (myresult[0] == False): return myresult logging.info("Entering updateRelationship") #r.statusUpdateTime = (r.statusUpdateTime + timedelta(seconds = 2)).strftime('%Y-%m-%d %H:%M:%S') #if status is Pending Return, call updatePoints() result = r.relationshipToList() #sql = "SELECT * from hascontainer WHERE email = '" + result[0] + "' and qrcode = '" + result[1] + "' and status <> 'Verified Return'" + " ORDER BY statusUpdateTime DESC" sql = "SELECT * from hascontainer WHERE qrcode = '" + result[ 1] + "' and status != 'Verified Return'" myresult = self.handleSQL(sql, True, None) #print(myresult,"here") if (myresult[0] == False): return myresult myresult = myresult[1][0] myresult = list(myresult) myresult[3] = str(myresult[3]) r1 = Relationship(myresult[0], myresult[1], myresult[2], myresult[3], myresult[4], myresult[5]) #if(r1.status=="Damaged Lost"): #return False, "Container has been marked as Damaged Lost" #if(r.status == "Damaged Lost" and r.description == None): #return False, "Damaged Lost Container lacks description" sql = "UPDATE hascontainer SET status = '" + str( r.status) + "', location_qrcode = '" + str( r.location_qrcode) + "', statusUpdateTime = '" + str( r.statusUpdateTime) + "', description = '" + str( r.description) + "' WHERE email = '" + str( r1.email) + "' and " + "qrcode = '" + str( r1.qrcode ) + "'" " and statusUpdateTime = '" + str( r1.statusUpdateTime) + "'" myresult = self.handleSQL(sql, False, None) if (myresult[0] == False): return myresult return True, "" except Exception as e: logging.error("Error in updateRelationship") logging.error(str(e)) return self.handleError(e)
def addRelationship(self, request, containerDao, relationshipDAO): userContainer = None hasAuth = True if "/checkoutContainer" in str(request): keys = [ 'email', 'qrcode', 'status', 'auth_token', 'location_qrcode' ] func = "self.checkoutContainer(userContainer)" # ask the database team if they are check for pendings that will switch to returned for older user elif "/secretCheckout" in str(request): keys = ['email'] func = "self.secretCheckout(userContainer)" hasAuth = False try: userContainer = self.helperHandler.handleRequestAndAuth( request=request, keys=keys, hasAuth=hasAuth) userContainer = eval(func) userContainer['statusUpdateTime'] = datetime.now().strftime( '%Y-%m-%d %H:%M:%S') old_code = relationshipDAO.getRecentUser(userContainer['qrcode']) #If user has already checked out the container they cannot check it out if "/checkoutContainer" in str(request): logging.info("Entering isCheckedOut testing") try: containerStatus = relationshipDAO.isCheckedOut( userContainer['email'], userContainer['qrcode']) if (containerStatus[0] == True): logging.info("Container is checked out already") return json.dumps({ "success": False, "message": "You already have this container Checked Out" }) except Exception as e: logging.info("Exiting checked out testing") relationship = Relationship() relationship.dictToRelationship(userContainer) res = self.relationdao.insertRelationship(relationship) self.helperHandler.falseQueryCheck(res) except Exception as e: return json.dumps({"success": False, "message": str(e)}) # send notification if old_code[0] is True: self.notificationHelper.sendNotification(old_code[1]) return self.helperHandler.handleResponse(res)
def relations(): for pair in itertools.permutations(entities, r=2): ent1 = pair[0] ent2 = pair[1] figure = ent1.name ground = ent2.name r = Relationship(scene_name, figure, ground) ## Get convex hulls # convexhull1 = Entity(ent1.convexhull) # convexhull2 = Entity(ent2.convexhull) ### Get some distance measure r.set_of_relations['distance'] = dist_obj(ent1, ent2) ### Measure the shortest distance between the meshes r.set_of_relations['contact'] = closest_mesh_distance(ent1, ent2) r.set_of_relations['contact_scaled'] = closest_mesh_distance_scaled( ent1, ent2) ### Measure distance between highest point of entity 2 and lowest point of entity 1 ### Positive => ent1 is above ent2 r.set_of_relations['above_measure'] = ent1.span[4] - ent2.span[5] ### Measure the degree of containment #### Currently simple version using bounding boxes r.set_of_relations['shared_volume'] = get_bbox_intersection(ent1, ent2) ### Proportion is divided by the figure volume i.e. if f in g then proportion = 1 if ent1.volume == 0: r.set_of_relations['containment'] = r.set_of_relations[ 'shared_volume'] / (ent1.volume + 0.0001) else: r.set_of_relations['containment'] = r.set_of_relations[ 'shared_volume'] / ent1.volume if ent2.volume != 0: r.set_of_relations['ins'] = inside(ent1, ent2) else: r.set_of_relations['ins'] = 0 r.save_to_csv(output_path)
def setUp(self): self.client = Redis(decode_responses=True) self.client.flushdb() # user self.peter = Relationship(self.client, "peter") # targets self.jack = Relationship(self.client, "jack") self.tom = Relationship(self.client, "tom") self.mary = Relationship(self.client, "mary") self.david = Relationship(self.client, "david") self.sam = Relationship(self.client, "sam") # user follow targets self.peter.follow("jack") self.peter.follow("tom") self.peter.follow("mary") self.peter.follow("david") self.peter.follow("sam") # create ten following user for each target self.jack_following_set = set() self.tom_following_set = set() self.mary_following_set = set() self.david_following_set = set() self.sam_following_set = set() for i in range(10): self.jack_following_set.add("J{0}".format(i)) self.tom_following_set.add("T{0}".format(i)) self.mary_following_set.add("M{0}".format(i)) self.david_following_set.add("D{0}".format(i)) self.sam_following_set.add("S{0}".format(i)) for target in list(self.jack_following_set): self.jack.follow(target) for target in list(self.tom_following_set): self.tom.follow(target) for target in list(self.mary_following_set): self.mary.follow(target) for target in list(self.david_following_set): self.david.follow(target) for sam in list(self.sam_following_set): self.sam.follow(target) # self.peter_recommend_follow = RecommendFollow(self.client, "peter")
def testGetRecentUser(self): rc, msg = self.testInsertRelationshipSmoke() self.assertTrue(rc) rc, msg = self.dao.getRecentUser("101010") self.assertTrue(rc) self.assertTrue(msg == "*****@*****.**") rc, msg = self.dao.getRecentUser("16546456") self.assertFalse(rc) r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None, None) rc, msg = self.dao.insertRelationship(r) self.assertTrue(rc) rc, msg = self.dao.getRecentUser("101010") self.assertTrue(rc) self.assertTrue(msg == "*****@*****.**") rc, msg = self.dao.deleteRelationship(r) self.assertTrue(rc)
def changeOldRelationship(self, result): try: logging.info("Entering changeOldRelationship") sql = "SELECT * from hascontainer WHERE qrcode = '" + result[ 1] + "' and status <> 'Verified Return' ORDER BY statusUpdateTime DESC" myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult if (myresult[1] != [] and myresult[1] is not None): oldEmail = myresult[1][0] tempR = Relationship(oldEmail[0], oldEmail[1], oldEmail[2], oldEmail[3], oldEmail[4], None) if (tempR.status == "Damaged Lost"): tempR.description = "" #return False, "Container has been marked as Damaged Lost" #if(result[2] != "Damaged Lost"): tempR.status = "Verified Return" self.updateRelationship(tempR) except Exception as e: logging.error("Error in changeOldRelationship") logging.error(str(e)) return self.handleError(e)
def selectRelationship(self, email, qrcode): try: logging.info("Entering selectRelationship") sql = "SELECT * from hascontainer WHERE email = '" + email + "' and qrcode = '" + qrcode + "' ORDER BY statusUpdateTime DESC" myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult myresult = myresult[1][0] email = myresult[0] qrcode = myresult[1] status = myresult[2] statusUpdateTime = str(myresult[3]) location_qrcode = myresult[4] descrption = myresult[5] x = Relationship(email, qrcode, status, statusUpdateTime, location_qrcode, descrption) logging.info("selectRelationship successful") return True, x except Exception as e: logging.error("Error in selectRelationship") logging.error(str(e)) return self.handleError(e)
from redis import Redis from relationship import Relationship from recommend_follow import RecommendFollow client = Redis() # user peter = Relationship(client, "peter") # targets jack = Relationship(client, "jack") tom = Relationship(client, "tom") mary = Relationship(client, "mary") david = Relationship(client, "david") sam = Relationship(client, "sam") # user follow targets peter.follow("jack") peter.follow("tom") peter.follow("mary") peter.follow("david") peter.follow("sam") for i in range(10): jack.follow("J{0}".format(i)) tom.follow("T{0}".format(i)) mary.follow("M{0}".format(i)) david.follow("D{0}".format(i)) sam.follow("S{0}".format(i))
def testInsertRelationshipSmoke(self): r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None, None) return self.dao.insertRelationship(r)
def main(args): codes = args.codes start = args.start end = args.end market = args.market steps = args.steps user_number = args.user_number init_fund = args.init_fund transfer_deep = args.transfer_deep T = Tradengine(codes, start, end, **{"market": market, "seq_length": 5}) U = [] for i in range(user_number): # same stratigy U.append(User(i, codes, init_fund, T.get_ori_data(), 0)) R = Relationship(user_number, 10) degree = R.net.degree() his_close = [] his_p_change = [] assets = np.ndarray(user_number) ass_deg = np.ndarray(user_number, dtype=[('assets', float), ('degree', int)]) for step in range(steps): order_num = 0 # generate random news info_value = np.random.normal(0, 1) # pass the news to user for i in range(user_number): if np.random.random() < U[i].get_receive_rate(): U[i].update_info(step, info_value) # transfer the news along network for transfer_deep times for __ in range(transfer_deep): for i, to in R.net.adj.items(): info_h = U[i].get_info() for to, _eattr in to.items(): if np.random.random() < U[i].get_transfer_rate(): for k in info_h: U[to].update_info(k, info_h[k]) # decide and add order for i in range(user_number): d = U[i].decide(T.get_new_data(), T.get_scare_para()) if not (d['action_id'] == 2 or d['volume'] == 0): T.add_order(d['code'], d['price'], d['action_id'], d['volume'], i) order_num += 1 # call auction T.auction() # conclude transactions r = T.get_result() for it in r: U[it[0]].action_by_code(it[3])(it[1], it[2], it[4]) last_data = T.get_last_data() # update everyones assets for i in range(user_number): U[i].status_update(last_data) # results for i in range(user_number): assets[i] = U[i].assets ass_deg[i] = (U[i].assets, degree[i]) his_close.append(last_data[0]['close']) his_p_change.append(last_data[0]['p_change']) # if (step+1) % 25 == 0: # plot_distribution(assets) # plot_imitate_market(his_close) print("step: ", step, last_data[0]['close'], last_data[0]['p_change']) plot_rank(ass_deg) plot_distribution(assets) plot_imitate_market(his_close)
def addRelationship(self, direct, column=None, helperColumn=None): self.relationships.append(Relationship(direct, column, helperColumn))
cobb_end = cobb_initial else: object_details = bounds(figure) ### lowest point in z-axis z_min_end = object_details.z.min z_max_end = object_details.z.max cobb_end = blender_utils.get_bbox_centre(figure)[2] ### Results z_min_change = round(z_min_initial - z_min_end, 4) z_max_change = round(z_max_initial - z_max_end, 4) cobb_change = round(cobb_initial - cobb_end, 4) values.append( [figure.name, z_min_change, cobb_change, z_max_change]) return values values = support_1(ground) for value in values: figure_name = value[0] r = Relationship(scene_name, figure_name, ground.name) r.set_of_relations['raw_support:top_change'] = value[3] r.set_of_relations['raw_support:cobb_change'] = value[2] r.set_of_relations['raw_support:bottom_change'] = value[1] r.save_to_csv(output_path)
#导入relationship库中的Relationship类 from relationship import Relationship #自定义节点词典(小说中人物角色) dictpath = r'角色名单.txt' #小说路径,只能是编码方式为utf-8的txt文件 datapath = r'人民的名义.txt' #程序运行生成的角色关系图保存地址 pic = r'人物关系图.png' Re = Relationship(dictpath, datapath) relation = Re.relationship() graph = Re.network_digraph(relation, pic)
dir = os.path.dirname(path + "src/") if not dir in sys.path: sys.path.append(dir) from read_data import Parser from relationship import Relationship from data import Data from optimization import Optimization # extraction d = [] for i in range(1, 5): prior_data = Parser() prior_data._parserData(path + "/positive_examples/room_" + str(i) + ".txt") obj_relation = Relationship(prior_data.model, prior_data.pair) d.append(obj_relation) # integrate prior data data = Data() data._integrateData(d) # optimization op = Optimization(data) # Set unfeasible space for a robot op._setUnfeasibleSpace() # Find unfeasible objects op._findUnfeasibleObjects()