def railLocate(numOfRails, x, y, img_rgb): x = float(x) y = float(y) rect = pickle.load(open("approx.p", "rb")) u2 = float(rect[0, 0, 0]) - 25 v2 = float(rect[0, 0, 1]) u1 = float(rect[1, 0, 0]) + 15 v1 = float(rect[1, 0, 1]) distTot = np.sqrt((v2 - v1)**2 + (u2 - u1)**2) ##### LINE EQUATION ######## ## Line perpendicular to y=(m1)*x+(b1) and passes through (x,y) m1 = (v1 - v2) / (u1 - u2) b1 = v1 - m1 * u1 mp = -(1 / m1) bp = y - mp * x xint = (b1 - bp) / (mp - m1) yint = mp * xint + bp cv2.line(img_rgb, (int(u1), int(v1)), (int(u2), int(v2)), (255, 0, 255), 5) cv2.line(img_rgb, (int(xint), int(yint)), (int(x), int(y)), (250, 100, 0), 5) cv2.circle(img_rgb, (int(xint), int(yint)), 10, (200, 200, 0), 10) cv2.imshow("preview", img_rgb) cv2.waitKey(0) now = datetime.datetime.now() fileName = 'rail' + now.strftime("%Y-%m-%d %H%M%S") completeName = os.path.join(figSavePath, fileName + '.png') snapshot(completeName, True, img_rgb) ## Distance between xint yint and a1 b1 distint = np.sqrt((u1 - xint)**2 + (v1 - yint)**2) railReturn = np.ceil(numOfRails * (distint / distTot)) return railReturn
def create(self, username, sim_proj_dir, sim_file, handle_name='sim', params=None, make_snapshot=True): logger.info("Creating Simulation for "+username) code_path = join(config['SIM_STORAGE_DIR'], 'users', username, sim_proj_dir) obj = Pyro.core.ObjBase() self._sims_in_creation.append(obj.GUID()) try: if make_snapshot: logger.info("Making snapshot of " + code_path) snap_name = gen_snap_name(username, sim_proj_dir, sim_file, int(time.time()), params) snapshot(code_path, snap_name) old_code_path = code_path code_path = join(config['SIM_STORAGE_DIR'], 'sim_snapshots', snap_name) else: logger.info("Skipping snapshot, using " + code_path + " directly") s = Sim(obj.GUID(), code_path, sim_file, handle_name=handle_name, init_params=params, username=username) s.start_engine() obj.delegateTo(s) pyro_daemon.connect(obj,'s:'+obj.GUID()) self.simulations[obj.GUID()] = obj finally: self._sims_in_creation.remove(obj.GUID()) return s.to_dict()
def sync_folders(self): for pairs in self.folders: snap1 = snapshot.snapshot() snap1.add_dir(pairs[0]) snap2 = snapshot.snapshot() snap2.add_dir(pairs[1]) snapshot.sync(snap1, snap2)
def act(): """ Arguments: None Returns: degrees to be twisted by the bot """ snapshot() pin_code = str(barcode(imgPath)) degrees,amount = angle(degrees,pin_code) return pin_code
def _scan_once(context): context.step += 1 counts = {} scan_dir = os.path.join("scans", str(int(time.time()))) sys.stderr.write("Scan #%i\n" % context.step) os.makedirs(scan_dir) for name in sorted(context.cameras): camera = context.cameras[name] snapshot_path = os.path.join(scan_dir, name + ".jpg") snapshot.snapshot(camera, snapshot_path) counts["scans/" + name] = context.detector.detect( snapshot_path, context.model, context.object_class) counts["scans/total"] = sum(counts.values()) context.events.add_scalars(counts.items(), context.step) context.events.flush()
def main(argv): ''' main for standalone usage interprete parameters snaps a picture if requested to a given filename loads a picture from a file calls nameit for the picture using a hint if given prints the result ''' import os import sys import argparse parser = argparse.ArgumentParser(description='Take Pictures and ask Google to name them') parser.add_argument('-s', '--snap', action='store_true', help='take a snapshot') parser.add_argument('-c', '--cam', nargs='?', type=int, help='use cam Number N defaults to 0', default=0) parser.add_argument('-b', '--config', nargs='?', type=str, help='JSON configuration string \'{"stopwordfilter":false,"Nimgres":60,"NThreads":5,"NTop":10}\'') parser.add_argument('-a', '--hint', nargs='?', type=str, help='give an interpretation hin', default=None) parser.add_argument('NAME', nargs='?', help='Filename defaults to snap.jpg', default="snap.jpg") cmdline_args = parser.parse_args(sys.argv[1:]) #cut the program-name off the list if cmdline_args.config: loadconfig(cmdline_args.config) print (config) picture_file=cmdline_args.NAME hint = cmdline_args.hint if cmdline_args.snap: from snapshot import snapshot snapshot(picture_file,cmdline_args.cam) if not os.path.exists(picture_file): print ("missing " + picture_file + " you may want to capture it using -s (-h for Help)") sys.exit(-1) image_file = open(picture_file,'rb') image_buffer=image_file.read() ret = nameit(image_buffer,hint) image_file.close() for j in ret: for i in j: print (i) print ("" , len(j), "################################################################")
def OnKeyPress(event): global low, high global sensitivity global algo global track_player if event.Key == "Shift_L": print "" time1 = datetime.now() os.system("xinput set-prop " + mouseid + " \"Device Enabled\" 0") print "disable mouse: " + str( (datetime.now() - time1).microseconds / 1000) + " ms" time1 = datetime.now() #algo1() algo() #mouse.click() time2 = datetime.now() time3 = time2 - time1 print "total: " + str(time3.microseconds / 1000.0) + " ms" for i in range(4): time.sleep(0.025) img = snapshot.snapshot(constants.screen, constants.window, constants.imp) #calc.getCenter(numpy.array(img), low, high) #time.sleep(0.1) time1 = datetime.now() os.system("xinput set-prop " + mouseid + " \"Device Enabled\" 1") print "enable mouse: " + str( (datetime.now() - time1).microseconds / 1000) + " ms" elif event.Key == "apostrophe": sensitivity += 0.05 print "\nsensitivity: " + str(sensitivity) elif event.Key == "semicolon": sensitivity -= 0.05 print "\nsensitivity: " + str(sensitivity) elif event.Key == "bracketleft": algo = algo2 print "\n**** Setting algo2 ****" elif event.Key == "bracketright": algo = algo3 print "\n**** Setting algo3 ****" elif event.Key == "minus": print "\n**** Now targetting BLUE team ****" low = constants.low_blue high = constants.high_blue elif event.Key == "equal": print "\n**** Now targetting RED team ****" low = constants.low_red high = constants.high_red elif event.Key == "x": track_player = not track_player if track_player: print "turning on tracking..." trackPlayer() else: print "turning off tracking..."
def detect(curr): if True: #time.time() - curr > secondInterval: snapshot.snapshot() results = parseData.parse("snapshot.jpg") reservationLicense = "" #print "Requesting plate from parent" socket.send("1".encode("utf8")) #print "Waiting for response" reservationLicense = socket.recv().decode("utf8") #print "Received response from parent: " + reservationLicense if len(results) > 0: print "Detected vehicle, seeing if it matches a reservation" for result in results: print "Comparing " + result + " with " + reservationLicense if result == reservationLicense: print "Found match" socket.send(result.encode("utf8")) try: response = socket.recv().decode("utf8") except: sys.exit() #sys.stdout.flush() return result print "No match found" socket.send("NA".encode("utf8")) try: response = socket.recv().decode("utf8") except: sys.exit() #sys.stdout.flush() else: print "No detections" #print("No vehicle detected") socket.send("NA".encode("utf8")) try: response = socket.recv().decode("utf8") except: sys.exit() #sys.stdout.flush() return "NA"
def algo2(): global sensitivity frame1 = 0 frame2 = 0 time1 = datetime.now() img1 = snapshot.snapshot(constants.screen, constants.window, constants.imp) diff = (datetime.now() - time1).microseconds frame1 = frame1 + diff / 2.0 print "snapshot: " + str(diff / 1000.0) + " ms" time1 = datetime.now() retval = calc.getCenter(numpy.array(img1), low, high) diff = (datetime.now() - time1).microseconds frame1 = frame1 + diff print "getCenter: " + str(diff / 1000.0) + " ms" time1 = datetime.now() if retval: (center1, rectpos, rectsize) = retval center1 = map(operator.add, center1, constants.diff) rectpos = map(operator.add, rectpos, constants.diff) rectpos = map(operator.sub, rectpos, constants.window) rectpos = map(operator.add, rectpos, constants.screen) else: return #img2 = snapshot.snapshot(constants.screen, constants.window, constants.imp) img2 = snapshot.screenshot(rectpos, rectsize) diff = (datetime.now() - time1).microseconds frame2 = frame2 + diff print "snapshot: " + str(diff / 1000.0) + " ms" time1 = datetime.now() retval = calc.getCenter(numpy.array(img2), low, high) if retval: (center2, rectpos2, rectsize2) = retval else: return diff = (datetime.now() - time1).microseconds frame2 = frame2 + diff print "getCenter: " + str(diff / 1000.0) + " ms" time1 = datetime.now() if center2: center2 = map(operator.add, center2, rectpos) center2 = map(operator.add, center2, constants.window) center2 = map(operator.sub, center2, constants.screen) #print center multiplier = (frame2 + 25000.0) / frame1 print "Using multiplier: " + str(multiplier) if center1 and center2: offset = [q - p for (p, q) in zip(center1, center2)] new_center = (multiplier * offset[0] + center2[0], multiplier * offset[1] + center2[1]) mouse.shoot(new_center, constants.screen, constants.window, sensitivity) print "shoot: " + str( (datetime.now() - time1).microseconds / 1000.0) + " ms"
def load_snapshot(): global s if s is None: s = snapshot({ "--accounts": None, "--update": False, "--verbose": False, "--positions": True, "--recent": True, "--months": True, "--years": True, })
def test_snapshot(url): import snapshot as ss import bag_ofwords as bow import corpus as cs import re html_tag = re.compile(r"<.*?>") stopwords = re.compile("[!-/:-@\[-`{-~]|nbsp|amp|[0-9]") snapshot = ss.snapshot(url) corpus = cs.Corpus() for docid, doc in snapshot: raw_desc = html_tag.sub("", doc) desc_bow = bow.to_bagofwords("\"%s\"" % raw_desc, ["名詞", "未知語"]) try: del(desc_bow[desc_bow.index("Permalink"):]) except ValueError as e: print(e.message) doc_words = [w for w in desc_bow if not stopwords.search(w)] corpus.append(doc_words, docid) cowords = {} docs = corpus.docs() for link, words in docs.items(): for node in words: if not cowords.has_key(node): cowords.setdefault(node, {}) for to in words: if not cowords[node].has_key(to): cowords[node].setdefault(to, 1) else: cowords[node][to] += 1 for n, m in cowords.items(): print(n) for w, f in m.items(): print("\t%s %s" % (w, f)) break
def trackPlayer(): global sensitivity global track_player center1 = [p - q / 2 for (p, q) in zip(constants.screen, constants.window)] frame1 = 0 frame2 = 0 while track_player: time1 = datetime.now() img1 = snapshot.snapshot(constants.screen, constants.window, constants.imp) diff = (datetime.now() - time1).microseconds frame2 = frame2 + diff / 2.0 print "snapshot: " + str(diff / 1000.0) + " ms" time1 = datetime.now() retval = calc.getCenter(numpy.array(img1), low, high) diff = (datetime.now() - time1).microseconds frame2 = frame2 + diff print "getCenter: " + str(diff / 1000.0) + " ms" time1 = datetime.now() if retval: (center2, rectpos, rectsize) = retval diff = [p - q for (p, q) in zip(center2, center1)] dist = math.sqrt(diff[0] * diff[0] + diff[1] * diff[1]) if dist < 3 and frame1 > 0: multiplier = (frame2 + 25000.0) / frame1 print "Using multiplier: " + str(multiplier) new_center = (multiplier * diff[0] + center1[0], multiplier * diff[1] + center1[1]) new_center = [int(p) for p in new_center] new_center = map(operator.add, new_center, constants.diff) print new_center mouse.shoot(new_center, constants.screen, constants.window, sensitivity) break center1 = center2 frame1 = frame2 else: break if center1: mouse.move(center1, constants.screen, constants.window, constants.imp, sensitivity) print "move: " + str( (datetime.now() - time1).microseconds / 1000.0) + " ms" time.sleep(0.025) track_player = False
def signage(): num_of_person = personcount() people = num_of_person[0] print('The number of people =', people) if people > 10: img_url = snapshot() ages_list = face.detectface(img_url[0]) print('The age of people =', ages_list) age_c = Counter(ages_list) age_str = [str(int(i / 10)) for i in age_c] age_d = Counter(age_str) age = int(age_d.most_common()[0][0]) msg = '' if age < 1: msg = teams.message() else: msg = '' age = 10 return render_template("signage.html", msg=msg, people=people, age=age)
def algo1(): time1 = datetime.now() img = snapshot.snapshot(constants.screen, constants.window, constants.imp) print "snapshot: " + str( (datetime.now() - time1).microseconds / 1000.0) + " ms" time1 = datetime.now() retval = calc.getCenter(numpy.array(img), low, high) if retval: (center, rectpos, rectsize) = retval center = map(operator.add, center, constants.diff) else: return print "getCenter: " + str( (datetime.now() - time1).microseconds / 1000.0) + " ms" time1 = datetime.now() #print center if center: mouse.shoot(center, constants.screen, constants.window) time2 = datetime.now() print "shoot: " + str( (datetime.now() - time1).microseconds / 1000.0) + " ms"
def genDF(self): self.f = open(self.trjfn, 'r+') # self.tslist will store timesteps. # Each timestep contains the dataframe snapshot.AtomAll for atomic info, # snapshot.boxhi, snapshot.boxlo for box info, # snapshot.ts for timestep value. # # Read the trj file fbody = self.f.readlines() indx = 0 # Read trj is stored in a huge list named fbody. for line in fbody: fbody[indx] = line.split(' ') indx += 1 self.f.close() # # split the huge list, for every line. # separate each time step by while loop. indx = 0 while indx < len(fbody): # # Do some var type conversion first. c_df, ctimestep, cNatom, cboxlo, cboxhi = trj_list2numpy(fbody, indx) # Create a snapshot object to store all information for a timestep. snap_one = snapshot() snap_one.ts = ctimestep snap_one.setbox(cboxlo, cboxhi) snap_one.AtomAll = c_df snap_one.setbox(cboxlo, cboxhi) # # Mount the single time step to timestep list self.tslist. # Local variable names such as c_df, snap_one, etc will be automatically deleted. # Data will not be lost. Stay carm. # Python interpreter will handle the data and name ref properly. # All data will be callable through the self.tslist and its attributes. # Iterate to the next timestep indx = indx + cNatom + 9
def fullmap(): img_url = snapshot() num_of_person = personcount() if num_of_person[0] < 10: icon_i = 'static/images/p1.png' discount_i = '<a href=http://127.0.0.1:5000/coupon>You can get a discount coupon now!!!</a>' else: icon_i = 'static/images/p2.png' discount_i = 'Come here now!' if num_of_person[1] < 10: icon_s = 'static/images/p1.png' discount_s = '<a href=http://127.0.0.1:5000/coupon>You can get a discount coupon now!!!</a>' else: icon_s = 'static/images/p2.png' discount_s = 'Come here now!' fullmap = Map( identifier="fullmap", varname="fullmap", style=( "height:60%;" "width:90%;" "top:10;" "left:60;" "position:absolute;" "z-index:200;" ), lat=35.6295, lng=139.7942, markers=[ { "icon": icon_i, "title": str(num_of_person[0]) + ' people here', "lat": 35.6293, "lng": 139.7942, "infobox": ( '\"<h1>Italian Restaurant <p> (' + str(num_of_person[0]) + ' people here!)</p></h1>\"' '\"<h2>' + discount_i + '</h2>\"' '\"<img src=\"' + img_url[0] + '\" width=\"50%\" height=\"50%\">\"' ), }, { "icon": icon_s, "title": str(num_of_person[1]) + ' people here', "lat": 35.6294, "lng": 139.7942, "infobox": ( '\"<h1>Sushi Tokyo <p> (' + str(num_of_person[1]) + ' people here!)</p></h1>\"' '\"<h2>' + discount_s + '</h2>\"' '\"<img src=\"' + img_url[1] + '\" width=\"50%\" height=\"50%\">\"' ), }, ], # maptype = "HYBRID", zoom="20" ) return render_template( "map.html", fullmap=fullmap, )
def algo3(): global sensitivity frame1 = 0 frame2 = 0 time1 = datetime.now() img1 = snapshot.snapshot(constants.screen, constants.window, constants.imp) diff = (datetime.now() - time1).microseconds frame1 = frame1 + diff / 2.0 print "snapshot: " + str(diff / 1000.0) + " ms" time1 = datetime.now() retval = calc.getCenter(numpy.array(img1), low, high) diff = (datetime.now() - time1).microseconds frame1 = frame1 + diff print "getCenter: " + str(diff / 1000.0) + " ms" time1 = datetime.now() if retval: (center1, rectpos, rectsize) = retval center1 = map(operator.add, center1, constants.diff) rectpos = map(operator.add, rectpos, constants.diff) rectpos = map(operator.sub, rectpos, constants.window) rectpos = map(operator.add, rectpos, constants.screen) else: return #img2 = snapshot.snapshot(constants.screen, constants.window, constants.imp) x = [] y = [] t = [] totaltime = 0 interval = 0.01 sleeptime = interval for i in range(3): retval = get_diff(rectpos, rectsize, center1) if retval: (rectpos, center2, time2) = retval else: continue sleeptime = time2 / (1000.0 * 1000.0) if sleeptime > interval: sleeptime = interval print sleeptime time.sleep(interval - sleeptime) totaltime = totaltime + time2 + (interval - sleeptime) * 1000.0 * 1000.0 x.append(center2[0]) y.append(center2[1]) t.append(totaltime) center1 = center2 if len(x) == 0: return time1 = datetime.now() print x, y, t z = numpy.polyfit(t, x, 1) f = numpy.poly1d(z) v = numpy.polyfit(t, y, 1) g = numpy.poly1d(v) totaltime = totaltime + (datetime.now() - time1).microseconds + 25000 new_center = (round(f(totaltime)), round(g(totaltime))) print totaltime print new_center mouse.shoot(new_center, constants.screen, constants.window, sensitivity)
or implied. """ import requests import json from snapshot import snapshot from config import settings from collections import Counter import time def detectface(url): face_api_url = 'https://cisco.cognitiveservices.azure.com/face/v1.0/detect' headers = {'Ocp-Apim-Subscription-Key': settings.subscription_key} params = { 'returnFaceId': 'false', 'returnFaceLandmarks': 'false', 'returnFaceAttributes': 'age', #'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', } time.sleep(5) response = requests.post(face_api_url, params=params, headers=headers, json={"url": url}) list = [] for i in response.json(): list.append(i['faceAttributes']['age']) return list if __name__ == '__main__': img_url = snapshot() ages_list = detectface(img_url[0]) print('The Age of people = ', ages_list)
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': logger.info("GET request recieved on port responding") return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WORKING</title> </head> <body> <p> <strong>WORKING</strong> </p> </body> </html> """) elif request.method == 'POST': logger.info("POST messaged received on port with the following details") json_data = request.json logger.info(str(json_data)) # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) logger.debug("NEW MESSAGE IN ROOM '{}'".format(room.title)) logger.debug("FROM '{}'".format(person.displayName)) logger.debug("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. logger.info("checked message but it was from me") return 'OK' else: # Message was sent by someone else; parse message and respond. if message.files: print(message.files) camsnapshots = snapshot.snapshot() newmessage = camsnapshots[0] print(camsnapshots[0]) api.messages.create(room.id, text="Mugshot Taken") headers= { 'Authorization': "Bearer ZTlhN2Y3YWYtOWYwNC00YWIzLTk0YjktMWY1Y2UxMjI4ODY0ZTNhN2FiN2QtMWRi_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f", 'cache-control': "no-cache", 'Postman-Token': "7c9aaad4-88a7-4206-9a7d-28fd442dc59d" } webex_attachment_start_fetch_time = datetime.now() ################ print(webex_attachment_start_fetch_time) dstresponse = requests.get(message.files[0], headers=headers) webex_attachment_finish_fetch_time = datetime.now() ################ print(webex_attachment_finish_fetch_time) webex_attachement_response_time = webex_attachment_finish_fetch_time - webex_attachment_start_fetch_time ################################ print(webex_attachement_response_time) print("################GOT DST") if dstresponse.status_code == 200: imageTarget = BytesIO(dstresponse.content) print("################GOT DST Content") print(type(imageTarget)) recognition = AppDynamicsHackathon2019_AWS.get_images_from_LOCAL_and_URL(imageTarget,camsnapshots[0]) api.messages.create(room.id, text=recognition) #try: # print(str(int(webex_attachement_response_time.microseconds))) # AppDController.Get_image(int(webex_attachement_response_time.microseconds), "WebEx") # print(str(int(meraki_snapshot_url_creation_time.microseconds))) # AppDController.Meraki_snap(int(meraki_snapshot_url_creation_time.microseconds), "Meraki_snap") # AppDController.Pull_Meraki() # AppDController.Upload_AWS() #except Exception as e: # return "error hit was " + str(e) elif "HELP" in str(message.text).upper() or "?" in message.text: return_messsage = """Welcome to the Cisco AppD Who the F**k are you bot!!!! The Bot will respond to the following commands: 'help' - displays this text '?' - displays this text 'Go' - Will initiate a snapshot of Imposter and Identity """ # Post the fact to the room where the request was received api.messages.create(room.id, text=return_messsage) # Post a message to the tracking/debug room # api.messages.create(TRACKING_ROOM_ID, text=str(room.id + " - " + # webhook_obj.data.personEmail + " - " + # message.text)) return 'OK' else: lookup_go = re.split(' |\n', str(message.text).upper()) for go in lookup_go: normalised_sku = go.upper().strip(" ").strip("\n") if normalised_sku == "GO" or \ normalised_sku == "go" : camsnapshots = snapshot.snapshot() newmessage=camsnapshots[0] print(camsnapshots[0]) recognition = AppDynamicsHackathon2019_AWS.get_images_from_URL(camsnapshots[0], camsnapshots[1]) api.messages.create(room.id, text=str(recognition)) continue return 'OK'
def acceptMessages(self, clientSocket): # Create the BranchMessage receivedMessage = bank_pb2.BranchMessage() while True: # Receive a message from the clientSocket message = clientSocket.recv(4096) print "(acceptMessages) Received a message !" receivedMessage.ParseFromString(message) typeOfMessage = receivedMessage.WhichOneof("branch_message") if (typeOfMessage == "init_branch"): print "(acceptMessages) Receieved InitBranch message" self.InitBranch(receivedMessage.init_branch.balance, receivedMessage.init_branch.all_branches) elif (typeOfMessage == "transfer"): # ============== Outer Critical Section Begin ================== threadLock.acquire(1) # ============== Inner Critical Section Begin ================= snapDictionaryLock.acquire(1) sourceBranch = receivedMessage.transfer.src_branch print "(acceptMessages) Receieved Transfer message" # TODO : After debugging, these two print statements should only occur # when self.numberOfMilliseconds >= 1000 #if (self.numberOfMilliseconds >= 1000): print "(acceptMessages) Received", receivedMessage.transfer.money, \ "from " + sourceBranch self.balance = self.balance + receivedMessage.transfer.money print "\tNew Balance of This Branch:", self.balance # Update channel states for all snapshot objects for key in self.snapshots: snapshotObj = self.snapshots[key] channel = snapshotObj.markerChannelState[sourceBranch] if (channel[1]): channel[0] = channel[0] + receivedMessage.transfer.money print "\tAdding", receivedMessage.transfer.money, "to " + \ "channel from " + sourceBranch + " to " + self.branch_name + \ " for snapshotID", snapshotObj.snapshotId # ============== Inner Critical Section End =================== snapDictionaryLock.release() threadLock.release() # =============== Outer Critical Section End ===================== elif (typeOfMessage == "init_snapshot"): # ============= Critical Section Begin ===================== snapDictionaryLock.acquire(1) print "(acceptMessages) Receieved InitSnapshot message" snapId = receivedMessage.init_snapshot.snapshot_id print "\tSnapshotId:", snapId newSnapObj = snapshot(self, snapId) self.snapshots[snapId] = newSnapObj newSnapObj.initSnapshot() snapDictionaryLock.release() # ============= Critical Section End ===================== elif (typeOfMessage == "marker"): # ============= Critical Section Begin ===================== snapDictionaryLock.acquire(1) print "(acceptMessages) Receieved Marker message" snapId = receivedMessage.marker.snapshot_id print "\tSnapshotId:", snapId otherBranch = receivedMessage.marker.src_branch # Received a marker message for a snapshot id that we're already # recording channels for this snapshot if (snapId in self.snapshots.keys()): self.snapshots[snapId].processSecondMarker() # Create new snapshot object for this snapshot else: newSnapObj = snapshot(self, snapId) self.snapshots[snapId] = newSnapObj newSnapObj.processFirstMarker(otherBranch) snapDictionaryLock.release() # ============= Critical Section End ===================== elif (typeOfMessage == "retrieve_snapshot"): snapId = int(receivedMessage.retrieve_snapshot.snapshot_id) while True: # ============= Critical Section Begin ===================== snapDictionaryLock.acquire(1) # If the requested snapshot hasn't been recorded by this branch, # then release the lock, sleep for a second, and continue this # loop if (not snapId in self.snapshots.keys()): snapDictionaryLock.release() time.sleep(1) continue # Otherwise, exit the loop else: break print "(acceptMessages) Receieved RetrieveSnapshot message" print "\tSnapshotId:", snapId snapObject = self.snapshots[snapId] returnSnapMessage = bank_pb2.BranchMessage() returnSnapMessage.return_snapshot.local_snapshot.snapshot_id = snapId returnSnapMessage.return_snapshot.local_snapshot.balance = \ snapObject.markerBalance channelStates = [] snapDictionaryLock.release() # ============= Critical Section End ===================== # Get the states of all of the channels. Need this while loop because we # must release the lock and try again while True: # ================ Critical Section Begin ================= snapDictionaryLock.acquire(1) for branchName in sorted(snapObject.markerChannelState.keys()): channelStateArray = snapObject.markerChannelState[branchName] # If channel is closed, then record the channel state if (channelStateArray[1] == False): channelStates.append(channelStateArray[0]) # Otherwise, release the lock, reset channelStates, sleep for a second, # and break this loop else: print "\t\tReleasing the lock and retrying because " + branchName + "'s" +\ " channel is still open" snapDictionaryLock.release() channelStates = [] time.sleep(1) break # If channelStates is filled (i.e., not = []), then we can break out # of this while loop if (channelStates != []): break returnSnapMessage.return_snapshot.local_snapshot.channel_state.extend(channelStates) clientSocket.sendall(returnSnapMessage.SerializeToString()) snapDictionaryLock.release() # ============= Critical Section End ===================== elif (typeOfMessage == "return_snapshot"): print "(acceptMessages) Receieved ReturnSnapshot message" else: assert typeOfMessage is None print "(acceptMessages) Error: Receieved message has unknown type" sys.exit(1) # Clear the BranchMessage (receivedMessage) receivedMessage.Clear()
vc.release() break if key == 98: #pause the video #key2=cv2.waitKey(0) subFlag = 0 if key == 99: subFlag = 1 time.sleep(3) rval, frame = vc.read() fgmask = fgbg.apply(frame) from snapshot import snapshot now = datetime.datetime.now() fileName = 'fig' + now.strftime("%Y-%m-%d %H%M%S") completeNameB = os.path.join(figPathB, fileName + 'B.png') completeNameR = os.path.join(figPathR, fileName + 'R.png') snapshot(completeNameB, rval, fgmask) snapshot(completeNameR, rval, frame) count = count + 1 ### Detect Components in frame cv2.destroyAllWindows() resTemp = r'C:\Python27\shape-detection\shape-detection\templates\resistors' resMat = [] capMat = [] ledMat = [] icMat = [] resCount = 0 capCount = 0 ledCount = 0 icCount = 0 capTemp = r'C:\Python27\shape-detection\shape-detection\templates\caps'
def watch(root, tol=float("inf"), maxiter=float("inf")): """ :param root: Prefix of MultiNest output filenames (root) :type root: string :param tol: MultiNest evidence tolerance factor (tol) :type tol: float :param maxiter: MultiNest maximum number of iterations (maxiter) :type maxiter: int :returns: All information about MultiNest scan :rtype: dict """ # Find folder containing MultiNest output files folder = dirname(root) assert isdir(folder), "Cannot find: %s" % folder live_name = basename(root + "live.points") # Watch folder containing MultiNest output files watch_ = inotify.Inotify(block_duration_s=10) watch_.add_watch(folder) # Data-holders time_data = [] ln_delta_data = [] time_start = datetime.now() print("Start time: %s" % time_start) for event in watch_.event_gen(): if event and event[3] == live_name: # Snap MultiNest scan try: snap_time = datetime.now() snap = snapshot(root, tol, maxiter) except Exception as error: warn(error.message) continue # Record data about delta time_data.append(snap_time) ln_delta = [mode["ln_delta"] for mode in snap["modes"].values()] ln_delta_data.append(ln_delta) else: # Make plot of progress fig = plt.figure() ax = fig.add_subplot(1, 1, 1) # ax.set_yscale('symlog') plt.gcf().autofmt_xdate() plt.xlabel(r'Time') plt.ylabel(r'$\ln \Delta \mathcal{Z}$') # Extrapolate time-remaining and plot, if possible time_float = [(t - time_start).total_seconds() for t in time_data] for n_mode, ln_delta in enumerate(map(list, zip(*ln_delta_data))): fit = np.polyfit(ln_delta, time_float, 10) time_func = np.poly1d(fit) time_seconds = time_func(log(tol)) guess_time_end = time_start + timedelta(seconds=time_seconds) estimate_seconds = [time_func(x) for x in ln_delta] estimate_time = [time_start + timedelta(seconds=e) for e in estimate_seconds] plt.plot(estimate_time + [guess_time_end], ln_delta + [log(tol)]) plt.plot(time_data, ln_delta, "*") plt.axhline(log(tol), color="r") print("Mode: %s. Estimated end time: %s" %(n_mode, guess_time_end)) plt.savefig("progress.png") plt.close() # Quit watching if MultiNest scan has stopped try: if snap["global"]["stop"]: print_snapshot(root, tol, maxiter) time_end = datetime.now() delta_time = time_end - time_start print("End time: %s" % time_end) print("Total time: %s" % delta_time) break except NameError: continue
if quiesce: qproc = VoltProcedure(vclient, '@Quiesce', []) q = qproc.call() if q.status != 1: sys.stderr.write(q.statusString + '\n') sys.exit('Quiesce failed, aborting shutdown') sdproc = VoltProcedure(vclient, '@Shutdown', []) # Far as I know, there aren't any failure cases for the @Shutdown # proc. Saying this is going to bite me in the ass in the future. sdproc.call([]) if __name__ == '__main__': args = progargs() client = FastSerializer(args.voltleader, args.port, args.user, args.password) if args.snapshot is not None: import snapshot snapshot.snapshot(client, args.snapshot_path, args.snapshot, 1) if args.no_quiesce: shutdown(client, quiesce=False) else: shutdown(client, quiesce=True)
def lambda_handler(event, context): bucket = os.environ["BUCKET"] account_passin = configure_parser() # initiate logging logger = logging.getLogger() logger.setLevel(logging.INFO) # collects date info for s3 placement today = date.today() year = today.year month = today.month region = os.environ["REGION"] method_list = ["elb", "alb", "eip", "stopped_ec2", "cloudtrail", "ebs"] result = [] accountInfo = org_accounts() if account_passin is not None: accountInfo = [{ "Accounts": [{ "Id": "%s" % account_passin, "Status": "ACTIVE" }] }] else: pass for method in tqdm(method_list): for response in accountInfo: for account in response["Accounts"]: account_id = account["Id"] # check not closed as connot access this if account["Status"] == "ACTIVE": try: if method == "eip": client = assume_role(account_id, "ec2", region) result.append( eip.free_elastic_ip(account_id, client)) # works elif method == "stopped_ec2": client = assume_role(account_id, "ec2", region) result.append(ec2.stopped_ec2(account_id, client)) # works elif method == "elb": client = assume_role(account_id, "elb", region) result.append(elb.classic_elb(account_id, client)) # works elif method == "alb": client = assume_role(account_id, "elbv2", region) result.append(elb.app_elb(account_id, client)) # works elif method == "cloudtrail": client = assume_role(account_id, "cloudtrail", region) result.append( cloudtrail.extra_cloudtrail( account_id, client)) # works elif method == "ebs": client = assume_role(account_id, "ec2", region) result.append(ebs.ebs(account_id, client)) # works elif method == "snapshot": client = assume_role(account_id, "ec2", region) result.append(snapshot.snapshot( account_id, client)) except Exception as e: pass logging.warning("%s" % e) else: logger.info("%s is not active in org" % account_id) test = [] for item in result: for item2 in item: item2.update({"Info": "waste"}) item2.update( {"Date": datetime.datetime.now().strftime("%Y-%m-%d")}) item2.update({"Month": month}) item2.update({"Year": year}) test.append(item2) # writes per item in list of data with open("/tmp/FOF.json", "w") as outfile: for result in test: json.dump(result, outfile) outfile.write("\n") # uploads to s3 s3 = boto3.resource("s3") s3.meta.client.upload_file( "/tmp/FOF.json", bucket, "FinOpsFinder/year=%s/month=%s/FOF_%s_%s.json" % (year, month, month, year), )
#findcluster.py # This script is to run a single snapshot. import numpy as np from snapshot import snapshot from format_conversion import trj_list2numpy if __name__ == '__main__': f = open('../input/test.lammpstrj', 'r+') body = f.readlines() indx = 0 f.close() for line in body: body[indx] = line.split(' ') indx += 1 ss1 = snapshot() ss1.AtomAll, ss1.ts, ss1.Natom, cboxlo, cboxhi = trj_list2numpy(body, 0) ss1.setbox(cboxlo, cboxhi) print 'atomall loaded' print len(ss1.AtomAll) ss1.selectatoms('7') print 'total selected:' print len(ss1.sel) ss1.findcluster(1.) #np.savetxt(str(ss1.ts)+'snap_out.csv', result, fmt = '%8s', delimiter='\t', header='ITEM: ATOMS id mol type x y z ix iy iz cluster') np.savetxt(str(ss1.ts) + 'stats.csv', ss1.stats().T, fmt='%6d', delimiter=',') ss1.savesel() ss1.saveclusersizelist()
from snapshot import snapshot for i in range(1,2000): print 'ok ' + str(i) snapshot("C:\\Users\\sikkak\\Desktop\\DemoSim\\", 'demosim%d'%i)
f.close() except IOError: sys.exit('Error opening deployment. Does the file exist?') del f client = FastSerializer(args.voltleader, args.port, args.user, args.password) if args.suspend: pokerlife.suspend(client, 0, verbose=args.verbose) if args.snapshot is not None: success = snapshot.snapshot(client, args.snappath, args.snapshot, 1) if success[0] != 0: sys.stderr.write(success[1] + '\n') sys.exit(success[0]) try: update(client, catalog, deployment, verbose=args.verbose) except SystemExit: if args.suspend: sys.exit(' Poker not resumed.') else: sys.exit() if args.suspend: pokerlife.restart(client, verbose=args.verbose)