How to use data method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

freePlay.py

Source:freePlay.py Github

copy

Full Screen

1####################################2#Description:3 #Main file. Contains all code for "free play" mode where user can play virtual keyboard. Uses modes to different parts of application.4'''All notes on keyboard can be played with fingers and with mouse.5Keys are only momentarily highlighted after you press them. If your hands are not on the keyboard, then no keys will be highlighted. 6You can click a button in order to show the names of all the notes on the keyboard.7You can record melodies and play them back. You can also save melodies that you record and name them whatever you would like. All recorded melodies are stored even after the program is closed and reopened.'''8####################################9import threading10import pyaudio11import wave12from array import array13from struct import pack14import numpy as np15import time16import Leap17from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture18import os, sys, inspect, thread, time19sys.path.insert(0, "C:/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/LeapDeveloperKit_2.3.1+31549_mac/LeapSDK/lib/x86")20import random, math21import os, sys, inspect, thread, time22'''sys.path.insert(0, "C:\Users\ahanamukhopadhyay\Downloads\LeapDeveloperKit_2.3.1+31549_mac\LeapSDK\lib/x86")'''23from Tkinter import *24import tkFont25from PIL import Image26from image_util import *27import copy28from graphics import drawBackground29'''30CITATIONS: 31112 website for tkinter starter code32Leap motion starter code from Johnathan's Google Drive folder33Threads basic code: https://pymotw.com/2/threading/34PyAudio starter code: Google Drive folder shared with us from 15-11235https://freesound.org/people/pinkyfinger/sounds/68438/ Piano notes wav files36makeRecording() function --> altered code from here https://stackoverflow.com/questions/2890703/how-to-join-two-wav-files-using-python37https://www.clipartmax.com/middle/m2i8G6K9A0i8K9Z5_jazz-pianist-man-playing-piano-silhouette/ (citing image)38roundRectangles(): https://stackoverflow.com/questions/44099594/how-to-make-a-tkinter-canvas-rectangle-with-rounded-corners'''39####################################40# PyAudio41####################################42def play(file):43 44 CHUNK = 102445 wf = wave.open(file, 'rb')46 p = pyaudio.PyAudio()47 stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),48 channels=wf.getnchannels(),49 rate=wf.getframerate(),50 output=True)51 data = wf.readframes(CHUNK)52 while len(data) > 0:53 stream.write(data)54 data = wf.readframes(CHUNK)55 56 stream.stop_stream()57 stream.close()58 p.terminate()59def worker(file):60 print threading.currentThread().getName(), 'Starting'61 play(file)62 print threading.currentThread().getName(), 'Exiting'63####################################64# Leap Motion65####################################66def init(data):67 68 ###HOME VARIABLES69 data.whiteCircles = []70 for i in range(15):71 x0 = random.randint(10, data.width - 10)72 y0 = random.randint(10, data.width - 10)73 r = 1574 if i < 5:75 dir = (1,1)76 elif i < 10:77 dir = (-1,1)78 else:79 dir = (1,-1)80 data.whiteCircles.append([x0, y0, x0+r, y0+r, dir, r])81 82 #big circles83 data.bigCircles = []84 for i in range(12):85 x0 = random.randint(10, data.width - 10)86 y0 = random.randint(10, data.width - 10)87 r = 10088 if i < 5:89 dir = (1,1)90 elif i < 10:91 dir = (-1,1)92 else:93 dir = (1,-1)94 data.bigCircles.append([x0, y0, x0+r, y0+r, dir, r])95 96 data.speed1 = 1.597 data.speed2 = 1.198 data.timerDelay = 10099 data.secs = 0100 101 data.boxRadius = 120102 data.x0FreePlayButton = data.width/2 - data.boxRadius103 data.x1FreePlayButton = data.width/2 + data.boxRadius104 data.y0FreePlayButton = data.height/3105 data.y1FreePlayButton = data.height/3 + 60106 107 108 ###FREE PLAY VARIABLES109 data.mode = "home"110 111 data.controller = Leap.Controller()112 data.frame = data.controller.frame()113 data.fingerNames = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']114 data.boneNames = ['Metacarpal', 'Proximal', 'Intermediate', 'Distal']115 data.rPointerPos = (data.width//2, data.height//2)116 data.lPointerPos = (data.width//2, data.height//2)117 data.lHandOnScreen = False118 data.rHandOnScreen = False119 data.rFingerLst = [(0,0,0),(0,0,0),(0,0,0),(0,0,0),(0,0,0)]120 121 #piano variables122 data.wKeyWidth = 90123 data.wKeyLength = 320124 data.bKeyWidth = 60125 data.bKeyLength = 170126 data.yMargin = 300127 data.xMargin = 30128 data.bKeyShift = 60129 data.numWhiteKeys = 0130 data.selection = [0,"nothing", 0] #key index, color, time131 data.selectionHand = [[0,"nothing"], [0,"nothing"], [0,"nothing"], [0,"nothing"], [0,"nothing"]]132 133 data.keysPlayed = []134 135 data.keyToSound = dict({\136 (0, "white"): "pianoNotes/C.wav", \137 (1, "white"): "pianoNotes/D.wav",\138 (2, "white"): "pianoNotes/E.wav",\139 (3, "white"): "pianoNotes/F.wav",\140 (4, "white"): "pianoNotes/G.wav",\141 (5, "white"): "pianoNotes/A.wav",\142 (6, "white"): "pianoNotes/B.wav",\143 (7, "white"): "pianoNotes/C2.wav",\144 (8, "white"): "pianoNotes/D2.wav",\145 (9, "white"): "pianoNotes/E2.wav",\146 (0, "black"): "pianoNotes/C#.wav",\147 (1, "black"): "pianoNotes/Eb.wav",\148 (3, "black"): "pianoNotes/F#.wav",\149 (4, "black"): "pianoNotes/Ab.wav",\150 (5, "black"): "pianoNotes/Bb.wav",\151 (7, "black"): "pianoNotes/C#2.wav",\152 (8, "black"): "pianoNotes/Eb2.wav"})153 154 data.playedOnce = False155 156 data.tap_point = (0,0)157 158 data.timerDelay = 100159 data.clock = 0160 data.notePressedTime = [0, 0, 0, 0, 0]161 162 data.indexFingerMvmts = []163 data.lastTime = 0164 #stores all finger movements165 data.fingerMvmts0 = dict()166 data.fingerMvmts1 = dict()167 data.fingerMvmts2 = dict()168 data.fingerMvmts3 = dict()169 data.fingerMvmts4 = dict()170 171 data.prevTime = [0,0,0,0,0]172 173 #contains elements like [(0, "black"), 12]174 data.notePlayed = []175 data.showNoteNames = False176 177 data.x0NamesButton = 357178 data.x1NamesButton = 459179 data.y0NamesButton = 101180 data.y1NamesButton = 147181 182 data.x0RecordButton = data.width/2-50183 data.y0RecordButton = 225184 data.x1RecordButton = data.width/2+10185 data.y1RecordButton = 285186 187 data.x0PlayButton = data.width/2+30188 data.x1PlayButton = data.width/2+90189 data.y0PlayButton = 225190 data.y1PlayButton = 285191 192 data.x0BackButton = 20193 data.x1BackButton = 80194 data.y0BackButton = 30195 data.y1BackButton = 90196 197 data.x0ForwardButton = data.width-80198 data.x1ForwardButton = data.width-20199 data.y0ForwardButton = 30200 data.y1ForwardButton = 90201 202 data.x0DialogBox = data.width/2-150,203 data.x1DialogBox = data.width/2+150204 data.y0DialogBox = 175205 data.y1DialogBox = 210206 207 data.notesPlayed = []208 data.record = False209 data.enterTxt = False210 data.recordingName = ""211 data.recordings = []212 data.numTimesRecordPressed = 0213 data.stopClockFP = False214 data.sleepTime = 0215 data.greyBg = False216 217 data.x0SeeRecordingsButton = 296218 data.x1SeeRecordingsButton = 702219 data.y0SeeRecordingsButton = 643220 data.y1SeeRecordingsButton = 679221 222 data.programOpened = False223 data.contentsRead = ""224 225 data.x0SaveRecordingsButton = 840226 data.x1SaveRecordingsButton = 930227 data.y0SaveRecordingsButton = 225228 data.y1SaveRecordingsButton = 285229 230 data.x0SBox = 0231 data.y0SBox = 0232 data.x1SBox = 0233 234 ###MELODY PLAYBACK VARIABLES235 data.melodies = dict({\236 0: ["pianoNotes/E.wav", "pianoNotes/F.wav", "pianoNotes/D.wav", "pianoNotes/E.wav", "pianoNotes/C.wav"], \237 1: ["pianoNotes/G.wav", "pianoNotes/E.wav", "pianoNotes/F#.wav", "pianoNotes/G.wav", "pianoNotes/A.wav", "pianoNotes/G.wav"]})238 239 rectWidth = 100240 gap = 40241 242 data.x0NextMelButton = data.width/2-gap*1.5-2*rectWidth243 data.x1NextMelButton = data.width/2-gap*1.5-1*rectWidth244 data.y0NextMelButton = 215245 data.y1NextMelButton = 275246 247 data.x0ReplayMelButton = data.width/2-120248 data.x1ReplayMelButton = data.width/2-20249 data.y0ReplayMelButton = 215250 data.y1ReplayMelButton = 275251 252 data.x0DoneButton = data.width/2+gap/2253 data.x1DoneButton = data.width/2+gap/2+1*rectWidth254 data.y0DoneButton = 215255 data.y1DoneButton = 275256 257 data.x0AnswerMelButton = data.width/2+gap*1.5+rectWidth258 data.x1AnswerMelButton = data.width/2+gap*1.5+2*rectWidth259 data.y0AnswerMelButton = 215260 data.y1AnswerMelButton = 275261 262 data.x0ShowAnsMelButton = 418263 data.x1ShowAnsMelButton = 508264 data.y0ShowAnsMelButton = 646265 data.y1ShowAnsMelButton = 675266 267 data.currMelody = None268 data.notesPlayed = []269 data.correctMelody = None270 271 data.recMel = False272 data.firstNoteMel = (0,0)273 data.playAnswer = None274 data.stopClock = False275 276 ###INTERVALS277 data.intervals = dict({\278 "m2": [["C", "C#"], ["E", "F#"], ["G", "Ab"], ["B", "C2"]],\279 "M2": [["C", "D"], ["D", "E"], ["E", "F#"], ["F", "G"]],\280 "m3": [["C", "Eb"], ["E", "G"], ["D", "F"], ["C2", "Eb2"]],\281 "M3": [["C", "E"], ["D", "F#"], ["C2", "E2"], ["G", "B"]],\282 "P4": [["E", "A"], ["D", "G"], ["C#", "F#"], ["Eb", "Ab"]],\283 "P5": [["C", "G"], ["E", "B"], ["A", "E2"], ["Eb", "Bb"]],\284 "M6": [["C", "A"], ["D", "B"], ["E", "C#2"], ["C#", "Bb"]],\285 "m6": [["C", "Ab"], ["D", "Bb"], ["E", "C2"], ["C#", "B"]],\286 "M7": [["C", "B"], ["C#", "C2"], ["D", "C#2"], ["E", "Eb2"]],\287 "m7": [["C", "Bb"], ["C#", "B"], ["D", "C2"], ["E", "D2"]],\288 "P8": [["C", "C2"], ["D", "D2"], ["E", "E2"], ["C#", "C#2"]]})289 290 data.intervalsIndex = dict({\291 (1,1): "M2", (2,1): "M3", (3,1): "M6", (4,1): "M7",\292 (1,2): "m2", (2,2): "m3", (3,2): "m6", (4,2): "m7",\293 (1,3): "P4", (2,3): "P5", (3,3): "P8"})294 295 data.y0Interval = 0296 data.y1Interval = 0297 data.y0Major = 0298 data.y1Major = 0299 data.y0Minor = 0300 data.y1Minor = 0301 data.y0Perfect = 0302 data.y1Perfect = 0303 304 data.x0Intervals = 0305 data.x1Intervals = 0306 307 data.lBoxHeight = 50308 data.lBoxWidth = 75309 data.bBoxWidth = 200310 data.gap = 25311 312 data.currSel = [-1,0]313 data.allSel = set()314 315 #mainPg variables316 data.currSelMP = [-1,0]317 data.currIntervalIndex = (-1,-1)318 data.currIntervalNote1 = None319 data.currIntervalNote2 = None320 321 data.x0NextIntervalButton = data.width*5/6322 data.x1NextIntervalButton = data.width*5/6 + 100323 data.y0NextIntervalButton = 30324 data.y1NextIntervalButton = 90325 326 data.x0ReplayIntervalButton = data.width*5/6327 data.x1ReplayIntervalButton = data.width*5/6 + 100328 data.y0ReplayIntervalButton = 110329 data.y1ReplayIntervalButton = 170330 331 data.x0ResetIntervalButton = data.x0ReplayIntervalButton332 data.x1ResetIntervalButton = data.x1ReplayIntervalButton333 data.y0ResetIntervalButton = data.y0ReplayIntervalButton + 180334 data.y1ResetIntervalButton = data.y1ReplayIntervalButton + 180335 336 data.correctIntervals = 0337 data.wrongIntervals = 0338 339 340 341####################################342# mode dispatcher343####################################344def mousePressed(event, data):345 if (data.mode == "home"): homeMousePressed(event, data)346 elif (data.mode == "freePlay"): freePlayMousePressed(event, data)347 elif (data.mode == "pickInterval"): pickIntervalMousePressed(event, data)348 elif (data.mode == "mainPg"): mainPgMousePressed(event, data)349 elif (data.mode == "help"): helpMousePressed(event, data)350 elif (data.mode == "melodyPlaybackMain"): melodyPlaybackMainMousePressed(event, data)351def keyPressed(event, data):352 if (data.mode == "home"): homeKeyPressed(event, data)353 elif (data.mode == "freePlay"): freePlayKeyPressed(event, data)354 elif (data.mode == "pickInterval"): pickIntervalKeyPressed(event, data)355 elif (data.mode == "mainPg"): mainPgKeyPressed(event, data)356 elif (data.mode == "help"): helpKeyPressed(event, data)357 elif (data.mode == "melodyPlaybackMain"): melodyPlaybackMainKeyPressed(event, data)358def timerFired(data):359 if (data.mode == "home"): homeTimerFired(data)360 elif (data.mode == "freePlay"): freePlayTimerFired(data)361 elif (data.mode == "pickInterval"): pickIntervalTimerFired(data)362 elif (data.mode == "mainPg"): mainPgTimerFired(data)363 elif (data.mode == "help"): helpTimerFired(data)364 elif (data.mode == "melodyPlaybackMain"): melodyPlaybackMainTimerFired(data)365def redrawAll(canvas, data):366 drawBackground(canvas, data)367 if (data.mode == "home"): homeRedrawAll(canvas, data)368 elif (data.mode == "freePlay"): freePlayRedrawAll(canvas, data)369 elif (data.mode == "pickInterval"): pickIntervalRedrawAll(canvas, data)370 elif (data.mode == "mainPg"): mainPgRedrawAll(canvas, data)371 elif (data.mode == "help"): helpRedrawAll(canvas, data)372 elif (data.mode == "melodyPlaybackMain"): melodyPlaybackMainRedrawAll(canvas, data)373 374####################################375# home mode376####################################377from graphics import timerFired1 as homeTF378from graphics import redrawAll1 as homeRA379from graphics import roundRectangle380from intervals import roundRectangleButtons381def homeMousePressed(event, data):382 if event.x > data.x0FreePlayButton and event.x < data.x1FreePlayButton:383 #freePlay384 if event.y > data.y0FreePlayButton and event.y < data.y1FreePlayButton:385 data.mode = "freePlay"386 #pickInterval387 elif event.y > data.y0FreePlayButton +90 and event.y < data.y1FreePlayButton +90:388 data.mode = "pickInterval"389 #melodyPlayback390 elif event.y > data.y0FreePlayButton +180 and event.y < data.y1FreePlayButton +180:391 data.mode = "melodyPlaybackMain"392 393def homeKeyPressed(event, data):394 pass395 396def homeTimerFired(data):397 homeTF(data)398def homeRedrawAll(canvas, data):399 homeRA(canvas, data)400####################################401# freePlay mode402####################################403def freePlayMousePressed(event, data):404 #plays notes that are clicked with mouse405 getKeyMouse(data, event.x, event.y)406 if data.selection[1] != "nothing":407 note = data.keyToSound[(data.selection[0], data.selection[1])]408 t = threading.Thread(name='worker', target=worker, args=(note,))409 t.start()410 411 #clicked show note names412 if event.x > data.x0NamesButton and event.x < \413 data.x1NamesButton and event.y > data.y0NamesButton and \414 event.y < data.y1NamesButton:415 if data.showNoteNames:416 data.showNoteNames = False417 elif not data.showNoteNames:418 data.showNoteNames = True419 420 #stores key press421 if data.record:422 getKeyMouse(data, event.x, event.y)423 if data.selection[1] != "nothing":424 data.notesPlayed.append([(data.selection[0], data.selection[1]), data.clock])425 426 #clicked record427 if event.x > data.x0RecordButton and event.x < \428 data.x1RecordButton and event.y > data.y0RecordButton and \429 event.y < data.y1RecordButton:430 data.numTimesRecordPressed += 1431 if data.numTimesRecordPressed % 2 == 1 and data.numTimesRecordPressed != 1:432 data.notesPlayed = []433 if data.record and len(data.notesPlayed) != 0:434 pass435 if data.record:436 data.record = False437 data.enterTxt = True438 elif not data.record:439 data.record = True440 441 #if play back recording button is pressed442 if event.x > data.x0PlayButton and event.x < \443 data.x1PlayButton and event.y > data.y0PlayButton and \444 event.y < data.y1PlayButton:445 for i in range(len(data.notesPlayed)):446 t = threading.Thread(name='worker', target=worker, args=(data.keyToSound[data.notesPlayed[i][0]],))447 t.start()448 if i != len(data.notesPlayed) - 1:449 data.sleepTime = (data.notesPlayed[i+1][1]-data.notesPlayed[i][1])/8.0450 data.stopClockFP = True451 freePlayTimerFired(data)452 time.sleep(0.01)453 454 #if back button is pressed 455 if event.x > data.x0BackButton and event.x < \456 data.x1BackButton and event.y > data.y0BackButton and \457 event.y < data.y1BackButton:458 #pressed on normal screen459 if not data.greyBg:460 if data.mode == "freePlay":461 data.mode = "home"462 print data.mode463 #back button pressed on recordings screen464 else:465 data.greyBg = False466 467 #If dialog box is clicked in 468 if event.x > data.x0DialogBox and event.x < \469 data.x1DialogBox and event.y > data.y0DialogBox and \470 event.y < data.y1DialogBox:471 data.enterTxt = True472 473 #If see recordings button is clicked474 if event.x > data.x0SeeRecordingsButton and event.x < \475 data.x1SeeRecordingsButton and event.y > data.y0SeeRecordingsButton and \476 event.y < data.y1SeeRecordingsButton:477 data.greyBg = True478 479 #Read in previous recordings480 if not data.programOpened: 481 data.contentsRead = readFile("recordingsFile.txt")482 #only happens once when opening up the program for the first time483 oldContents = data.contentsRead.split(" ")484 for i in range(len(oldContents)):485 data.recordings.append(oldContents[i])486 data.programOpened = True487 488 #saves recordings to file489 if event.x > data.x0SaveRecordingsButton and event.x < \490 data.x1SaveRecordingsButton and event.y > data.y0SaveRecordingsButton and \491 event.y < data.y1SaveRecordingsButton:492 contentsToWrite = ""493 for i in range(len(data.recordings)):494 if i != len(data.recordings) - 1:495 contentsToWrite = contentsToWrite + data.recordings[i] + " "496 else:497 contentsToWrite = contentsToWrite + data.recordings[i]498 499 writeFile("recordingsFile.txt", contentsToWrite)500 501 #plays back a selected recording502 if data.greyBg:503 boxHeight = 35504 if event.x > data.x0SBox and event.x < data.x1SBox:505 index = (event.y - data.y0SBox) // boxHeight506 if index < len(data.recordings):507 song = data.recordings[index]508 print song509 t = threading.Thread(name='worker', target=worker, args=(song,))510 t.start()511 512def readFile(path):513 with open(path, "rt") as f:514 return f.read()515def writeFile(path, contents):516 with open(path, "wt") as f:517 f.write(contents)518def makeRecording(data):519 notes = []520 for i in range(len(data.notesPlayed)):521 note = data.keyToSound[data.notesPlayed[i][0]]522 notes.append(note)523 infiles = notes524 outfile = data.recordingName + ".wav"525 526 data = []527 for infile in infiles:528 w = wave.open(infile, 'rb')529 data.append( [w.getparams(), w.readframes(w.getnframes())] )530 w.close()531 532 output = wave.open(outfile, 'wb')533 output.setparams(data[0][0])534 for i in range(len(notes)):535 output.writeframes(data[i][1])536 output.close()537 538def freePlayKeyPressed(event, data):539 if event.keysym == "Return":540 data.enterTxt = False541 makeRecording(data)542 data.recordings.append(data.recordingName + ".wav")543 data.recordingName = ""544 if data.enterTxt:545 if event.keysym.isalnum():546 data.recordingName = data.recordingName + event.keysym547def freePlayTimerFired(data):548 data.clock += 1549 if data.stopClockFP:550 time.sleep(data.sleepTime)551 data.stopClockFP = False552 553 updateLeapMotionData(data)554 printLeapMotionData(data)555 556 #unhighlights a key that was played after 1 second557 notePlayedCopy = copy.deepcopy(data.notePlayed)558 for i in range(len(notePlayedCopy)):559 if data.clock - notePlayedCopy[i][1] >= 10:560 data.notePlayed.pop(i)561 562 if data.clock - data.selection[2] > 10:563 data.selection[1] = "nothing"564 565 566def noteToPlay(file):567 time.sleep(0.1)568 play(file)569def playNotes(data):570 for i in range(len(data.keysPlayed)):571 note = tuple(data.keysPlayed[i])572 if note in data.keyToSound:573 noteToPlay(data.keyToSound[note])574 575def updateLeapMotionData(data):576 data.frame = data.controller.frame()577def printLeapMotionData(data):578 frame = data.frame579 '''print "Frame id: %d, timestamp: %d, hands: %d, fingers: %d" % (580 frame.id, frame.timestamp, len(frame.hands), len(frame.fingers))'''581 # Get hands582 for hand in frame.hands:583 if hand.grab_strength == 1.0:584 print hand.grab_strength585 #play("maybe-next-time.wav")586 handType = "Left hand" if hand.is_left else "Right hand"587 588 #palm position for generating pointer589 if handType == "Left hand":590 data.lPointerPos = hand.palm_position591 data.lHandOnScreen = True592 #print "HERE", data.lPointerPos593 else:594 data.rPointerPos = hand.palm_position595 data.rHandOnScreen = True596 597 data.lHandOnScreen, data.rHandOnScreen = False, False598 '''print " %s, id %d, position: %s" % (599 handType, hand.id, hand.palm_position[1])'''600 # Get the hand's normal vector and direction601 normal = hand.palm_normal602 direction = hand.direction603 # Get arm bone604 arm = hand.arm605 606 # Get fingers607 for finger in hand.fingers:608 print " %s finger" % (609 data.fingerNames[finger.type]), finger.tip_position[1]610 611 #stores tip positions on fingers in Leap coordinates (y is opposite)612 if data.fingerNames[finger.type] == "Thumb":613 data.rFingerLst[0] = finger.tip_position614 elif data.fingerNames[finger.type] == "Index":615 data.rFingerLst[1] = finger.tip_position616 elif data.fingerNames[finger.type] == "Middle":617 data.rFingerLst[2] = finger.tip_position 618 elif data.fingerNames[finger.type] == "Ring":619 data.rFingerLst[3] = finger.tip_position620 elif data.fingerNames[finger.type] == "Pinky":621 data.rFingerLst[4] = finger.tip_position622 623 for i in range(5):624 d = {0:13, 1:20, 2:20, 3:17, 4:13}625 isKeyPlayed(data, d[i], i)626 627def isKeyPlayedList(data, finger):628 #checks if finger plays key629 thresholds = {0:27, 1:35, 2:35, 3:30, 4:27}630 if data.rPointerPos[1] - data.rFingerLst[finger][1] > thresholds[finger]:631 getKeyHand(data, data.rFingerLst[finger][0], data.rFingerLst[finger][1]-15, 1)632 if tuple(data.selectionHand[finger]) in data.keyToSound:633 if data.clock - data.notePressedTime[finger] > 4:634 data.notePressedTime[finger] = data.clock635 note = data.keyToSound[tuple(data.selectionHand[finger])]636 a = threading.Thread(name='worker', target=worker, \637 args=(note,))638 a.start()639 time.sleep(0.01)640 641def isKeyPlayed(data, lowerBound, finger):642 d = {0: data.fingerMvmts0, 1: data.fingerMvmts1, 2: data.fingerMvmts2, 3: data.fingerMvmts3, 4: data.fingerMvmts4}643 print finger644 dic = d[finger]645 #dictionary of yCoor: time646 dic[int(data.rFingerLst[finger][1])] = data.clock647 648 #loops through possible range of y movements that count as key being pressed649 for i in range(lowerBound, 45):650 #checks finger is on piano651 if data.rFingerLst[finger][1] < 135 and data.rFingerLst[finger][1] > 40:652 if int(data.rFingerLst[finger][1]) + i in dic:653 #check downwards movement was quick enough654 if dic[int(data.rFingerLst[finger][1])] - \655 dic[int(data.rFingerLst[finger][1]) + i] <= 2 and\656 dic[int(data.rFingerLst[finger][1])] - \657 dic[int(data.rFingerLst[finger][1]) + i] >= 0:658 #check if movements are far enough apart timewise659 if data.clock - data.prevTime[finger] > 2:660 data.prevTime[finger] = data.clock661 getKeyHand(data, data.rFingerLst[finger][0], \662 (data.rFingerLst[finger][1] + \663 int(data.rFingerLst[finger][1]) + i)/2, 1)664 #plays note665 if tuple(data.selectionHand[finger]) in data.keyToSound:666 note = data.keyToSound[tuple(data.selectionHand[finger])]667 data.notePlayed.append([tuple(data.selectionHand[finger]), data.clock])668 a = threading.Thread(name='worker', target=worker, \669 args=(note,))670 a.start()671 time.sleep(0.01)672 break673def getKeyMouse(data, x, y):674 #updates where user presses675 wKeyIndex = (x - data.xMargin) // data.wKeyWidth676 #bottom half of key677 if y > data.yMargin + data.bKeyLength and y < data.yMargin + data.wKeyLength:678 data.selection[0] = (x - data.xMargin) // data.wKeyWidth 679 data.selection[1] = "white"680 data.selection[2] = data.clock681 #top half of key682 elif y > data.yMargin and y < data.yMargin + data.bKeyLength:683 #left half of key684 if x < data.xMargin + data.wKeyWidth*wKeyIndex + data.bKeyWidth//2:685 if wKeyIndex not in {0, 3, 7}:686 data.selection[0], data.selection[1] = wKeyIndex-1, "black"687 else:688 data.selection[0], data.selection[1] = wKeyIndex, "white"689 #right half of key690 elif x > data.xMargin + data.wKeyWidth*(wKeyIndex+1) - data.bKeyWidth//2:691 if wKeyIndex not in {2, 6, 9}:692 data.selection[0], data.selection[1] = wKeyIndex, "black"693 else:694 data.selection[0], data.selection[1] = wKeyIndex, "white"695 #white part of key696 else:697 data.selection[0], data.selection[1] = wKeyIndex, "white"698 data.selection[2] = data.clock699 else:700 data.selection[1] = "nothing"701 data.selection[2] = data.clock702 703 data.keysPlayed.append([data.selection[0], data.selection[1]])704 705def getKeyHand(data, x, y, finger):706 i = finger707 #updates where user presses708 wKeyIndex = (x - data.xMargin) // data.wKeyWidth709 #bottom half of key710 if y > data.yMargin + data.bKeyLength and y < data.yMargin + data.wKeyLength:711 data.selectionHand[i][0] = (x - data.xMargin) // data.wKeyWidth 712 data.selectionHand[i][1] = "white"713 #top half of key714 elif y > data.yMargin and y < data.yMargin + data.bKeyLength:715 #left half of key716 if x < data.xMargin + data.wKeyWidth*wKeyIndex + data.bKeyWidth//2:717 if wKeyIndex not in {0, 3, 7}:718 data.selectionHand[i][0], data.selectionHand[i][1] = wKeyIndex-1, "black"719 else:720 data.selectionHand[i][0], data.selectionHand[i][1] = wKeyIndex, "white"721 #right half of key722 elif x > data.xMargin + data.wKeyWidth*(wKeyIndex+1) - data.bKeyWidth//2:723 if wKeyIndex not in {2, 6, 9}:724 data.selectionHand[i][0], data.selectionHand[i][1] = wKeyIndex, "black"725 else:726 data.selectionHand[i][0], data.selectionHand[i][1] = wKeyIndex, "white"727 #white part of key728 else:729 data.selectionHand[i][0], data.selectionHand[i][1] = wKeyIndex, "white"730 731def drawPiano(canvas, data):732 #draw keyBoard733 wKeyWidth = 90734 wKeyLength = 320735 bKeyWidth = 60736 bKeyLength = 170737 startYOnScreen = 300738 margin = 30739 bKeyShift = 60740 wSelectedIndexes = set()741 bSelectedIndexes = set()742 wPlayedIndexes = set()743 bPlayedIndexes = set()744 wNoteNames = {0:"C", 1:"D", 2:"E", 3:"F", 4:"G", 5:"A", 6:"B", 7:"C", 8:"D", 9:"E"}745 bNoteNames = {0:"C#", 1:"Eb", 3:"F#", 4:"Ab", 5:"Bb", 7:"C#", 8:"Eb"}746 747 for i in range(len(data.notePlayed)):748 if data.notePlayed[i][0][1] == "white":749 wPlayedIndexes.add(data.notePlayed[i][0][0])750 elif data.notePlayed[i][0][1] == "black":751 bPlayedIndexes.add(data.notePlayed[i][0][0])752 753 #stores locations of fingers754 for i in range(len(data.selectionHand)):755 if data.selectionHand[i][1] == "white":756 wSelectedIndexes.add(data.selectionHand[i][0])757 elif data.selectionHand[i][1] == "black":758 bSelectedIndexes.add(data.selectionHand[i][0])759 760 #print wSelectedIndexes761 for i in range(10):762 #draw white keys763 if i == data.selection[0] and data.selection[1] == "white": #mouse on key764 rgb2 = (113, 169, 247)765 color = "#%02x%02x%02x" % rgb2766 elif i in wPlayedIndexes:767 color = "green"768 else:769 color = "white"770 canvas.create_rectangle(wKeyWidth*i+margin, startYOnScreen,\771 margin+wKeyWidth*(i+1), startYOnScreen + wKeyLength, outline = "black", fill=color)772 if data.showNoteNames:773 canvas.create_text((wKeyWidth*i+margin + margin+wKeyWidth*(i+1))*1/2, (startYOnScreen + startYOnScreen + wKeyLength)*1/2+100, text=wNoteNames[i], font="Palatino 20 bold")774 775 for i in range(10):776 #draw black keys777 if i == data.selection[0] and data.selection[1] == "black":778 rgb2 = (113, 169, 247)779 color = "#%02x%02x%02x" % rgb2780 elif i in bPlayedIndexes:781 color = "green"782 else:783 color = "black"784 785 if i != 2 and i!= 6 and i != 9 and i != 11:786 canvas.create_rectangle(wKeyWidth*i+margin+bKeyShift, startYOnScreen,\787 wKeyWidth*i+margin+bKeyShift+bKeyWidth, startYOnScreen + bKeyLength,\788 fill = color)789 if data.showNoteNames:790 canvas.create_text((wKeyWidth*i+margin+bKeyShift + wKeyWidth*i+margin+bKeyShift+bKeyWidth)*1/2, (2*startYOnScreen + bKeyLength)*1/2+50, text = bNoteNames[i], font="Palatino 20 bold", fill="white")791 792def drawMainPointers(canvas, data):793 #draw RH pointer794 data.yRCoor = data.height - ((data.rPointerPos[1]-40) * data.height/160)795 data.xRCoor = (data.rPointerPos[0] - (-70))*data.width/140796 #draw LH pointer797 data.yLCoor = data.height - ((data.lPointerPos[1]-40) * data.height/160)798 data.xLCoor = (data.lPointerPos[0] - (-70))*data.width/140799 canvas.create_oval(data.xLCoor-10, data.yLCoor-10, data.xLCoor+10,\800 data.yLCoor+10, outline = "blue")801 802def getFingerPointerCoords(data, x, y):803 xCoor = (x - (-100))*data.width/250804 yCoor = data.height - ((y-40) * data.height/160)805 return xCoor, yCoor806 807def drawFingerPointers(canvas, data):808 #print data.rFingerLst809 for i in range(len(data.rFingerLst)):810 xCoor = (data.rFingerLst[i][0] - (-100))*data.width/250811 yCoor = data.height - ((data.rFingerLst[i][1]-40) * data.height/160)812 getKeyHand(data, xCoor, yCoor, i)813 canvas.create_oval(xCoor-10, yCoor-10, xCoor+10, \814 yCoor+10, outline = "green")815 816 817def freePlayRedrawAll(canvas, data):818 drawPiano(canvas, data)819 drawMainPointers(canvas, data)820 drawFingerPointers(canvas, data)821 #forwardArrow(canvas, data)822 backArrow(canvas, data)823 824 #Show note names825 if data.showNoteNames:826 rgb2 = (85, 50, 211)827 color = "#%02x%02x%02x" % rgb2828 canvas.create_line(data.x0NamesButton+15, data.y1NamesButton-25, data.x1NamesButton+10, data.y1NamesButton-25, width=4, fill=color)829 830 #Record and stop recording buttons831 if not data.record:832 canvas.create_oval(data.width/2-50,225,data.width/2+10,285,fill='', width=4)833 canvas.create_oval(data.width/2-40,235,data.width/2,275,fill="red")834 elif data.record:835 canvas.create_oval(data.width/2-50,225,data.width/2+10,285,fill='', width=4)836 roundRectangle(canvas, data, data.width/2-40,235,data.width/2,275,2,20,"red")837 838 #Playback recording839 canvas.create_oval(data.width/2+30, 225, data.width/2+90,285, width=4, fill='')840 canvas.create_polygon(data.width/2+45,235,data.width/2+45,275,data.width/2+80,255)841 842 rgb = (76, 16, 54)843 f = "#%02x%02x%02x" % rgb844 #Text845 if not data.greyBg:846 canvas.create_text(data.width/2, 60, text="Press a note to get started!", font="Palatino 40 bold", fill="#%02x%02x%02x" % rgb)847 canvas.create_text(data.width/2, 110, text="Confuzzled? Click here to learn the names of the notes", font="Palatino 20 bold", fill="#%02x%02x%02x" % rgb)848 canvas.create_text(data.width/2, 140, text="Feeling good? Click the buttons to record yourself and play it back", font="Palatino 20 bold", fill="#%02x%02x%02x" % rgb)849 850 #if user has finished a recording851 if data.enterTxt:852 if data.recordingName == "":853 txt = "Enter recording name"854 col = "gray"855 else:856 txt = data.recordingName857 col = "black"858 canvas.create_rectangle(data.width/2-150, 175, data.width/2+150, 210, outline="black", fill="white")859 canvas.create_text(data.width/2, 193, text=txt, fill=col)860 861 canvas.create_text(data.width/2, 659, text="Click here to view your recordings", font="Palatino 25 bold", fill="#%02x%02x%02x" % rgb)862 863 #shows screen when user wants to see all recordings they've made864 if data.greyBg:865 showRecordings(canvas, data)866 867 #draws save recording button868 if not data.greyBg:869 roundRectangleButtons(canvas, data, data.x0SaveRecordingsButton, data.y0SaveRecordingsButton, data.x1SaveRecordingsButton, data.y1SaveRecordingsButton)870 canvas.create_text((data.x0SaveRecordingsButton+data.x1SaveRecordingsButton)/2, (data.y0SaveRecordingsButton+data.y1SaveRecordingsButton)/2, text="Save", font='Palatino 20', fill='white')871 872def showRecordings(canvas, data):873 rgb = (238, 108, 77)874 f = "#%02x%02x%02x" % rgb875 x0BigBox = data.width/2-150876 x1BigBox = data.width/2+150877 878 #draws big box879 canvas.create_rectangle(x0BigBox, 125, x1BigBox, 542, fill=f, outline = "white", width = 4)880 canvas.create_text(data.width/2, 150, text="Recordings", fill="white", font="Palatino 30 bold")881 canvas.create_line(data.width/2-150, 170, data.width/2+150, 170, fill="white", width=3)882 883 #draws small box884 data.x0SBox = x0BigBox + 15885 data.x1SBox = x1BigBox - 15886 data.y0SBox = 185887 boxHeight = 35888 pbWidth = 20889 pbYPad = 7.5890 if '' in data.recordings or ' ' in data.recordings:891 data.recordings.remove('')892 for i in range(len(data.recordings)):893 recName = data.recordings[i].split(".")[0]894 canvas.create_rectangle(data.x0SBox, data.y0SBox+boxHeight*(i), data.x1SBox, data.y0SBox+boxHeight*(i+1), fill="white")895 canvas.create_text(data.x0SBox + 10,\896 (data.y0SBox+boxHeight*(i+1)+data.y0SBox+boxHeight*i)/2, text=recName, anchor=W, font="Palatino 15")897 y0 = data.y0SBox+pbYPad+boxHeight*(i)898 canvas.create_oval(data.x1SBox-10-pbWidth, y0, data.x1SBox-10,y0+pbWidth, width=2, fill='')899 900def forwardArrow(canvas, data):901 #forward arrow902 rgb = (238, 108, 77)903 f = "#%02x%02x%02x" % rgb904 canvas.create_oval(data.width-20, 30, data.width-80,90, width=4, outline = 'white', fill=f)905 canvas.create_oval(60,38,63,41,outline='white',fill='white')906 canvas.create_oval(data.width-37,58,data.width-34,61,outline='white',fill='white')907 canvas.create_oval(data.width-61,77,data.width-58,80,outline='white',fill='white')908 canvas.create_oval(data.width-61,39,data.width-58,42,outline='white',fill='white')909 canvas.create_line(data.width-60,40,data.width-35,60, width = 4, fill='white')910 canvas.create_line(data.width-35,60,data.width-60,80, width = 4, fill='white')911 912def backArrow(canvas, data):913 #back arrow914 rgb = (238, 108, 77)915 f = "#%02x%02x%02x" % rgb916 canvas.create_oval(22, 30, 82,90, width=4, outline = 'white', fill=f)917 canvas.create_oval(60,38,63,41,outline='white',fill='white')918 canvas.create_oval(35,58,38,61,outline='white',fill='white')919 canvas.create_oval(60,78,63,81,outline='white',fill='white')920 canvas.create_line(62,40,37,60, width = 4, fill='white')921 canvas.create_line(37,60,62,80, width = 4, fill='white')922####################################923# Intervals pickInterval mode924####################################925from intervals import pickIntervalMousePressed as pickIntervalMP926from intervals import pickIntervalKeyPressed as pickIntervalKP927from intervals import pickIntervalTimerFired as pickIntervalTF928from intervals import pickIntervalRedrawAll as pickIntervalRA929from intervals import getButtonPressed, getButtonPressedMP930def pickIntervalMousePressed(event, data):931 #clicked back932 if event.x > data.x0BackButton and event.x < \933 data.x1BackButton and event.y > data.y0BackButton and \934 event.y < data.y1BackButton:935 data.mode = "home"936 #clicked forward937 elif event.x > data.x0ForwardButton and event.x < \938 data.x1ForwardButton and event.y > data.y0ForwardButton and \939 event.y < data.y1ForwardButton:940 data.mode = "mainPg"941 942 pickIntervalMP(event, data)943 944def pickIntervalKeyPressed(event, data):945 pickIntervalKP(event, data)946 947def pickIntervalTimerFired(data):948 pickIntervalTF(data)949 950def pickIntervalRedrawAll(canvas, data):951 backArrow(canvas, data)952 forwardArrow(canvas, data)953 pickIntervalRA(canvas, data)954####################################955# Intervals mainPg mode956####################################957from intervals import mainPgMousePressed as mainPgMP958from intervals import mainPgRedrawAll as mainPgRA959from intervals import mainPgTimerFired as mainPgTF960def mainPgMousePressed(event, data):961 #clicked back962 if event.x > data.x0BackButton and event.x < \963 data.x1BackButton and event.y > data.y0BackButton and \964 event.y < data.y1BackButton:965 data.mode = "pickInterval"966 967 mainPgMP(event, data)968 969def mainPgRedrawAll(canvas, data):970 backArrow(canvas, data)971 mainPgRA(canvas, data)972 973def mainPgTimerFired(data):974 mainPgTF(data)975 976def mainPgKeyPressed(event, data):977 pass978 979####################################980# melodyPlaybackMain mode981####################################982from melodyPlayback import mousePressed as melodyPlaybackMP983from melodyPlayback import redrawAll as melodyPlaybackRA984from melodyPlayback import timerFired as melodyPlaybackTF985def melodyPlaybackMainMousePressed(event, data):986 #clicked back987 if event.x > data.x0BackButton and event.x < \988 data.x1BackButton and event.y > data.y0BackButton and \989 event.y < data.y1BackButton:990 data.mode = "home"991 992 melodyPlaybackMP(event, data)993 994def melodyPlaybackMainRedrawAll(canvas, data):995 backArrow(canvas, data)996 melodyPlaybackRA(canvas, data)997 998def melodyPlaybackMainTimerFired(data):999 melodyPlaybackTF(data)1000 1001def melodyPlaybackMainKeyPressed(event, data):1002 pass1003####################################1004# use the run function as-is1005####################################1006def run(width=300, height=300):1007 def redrawAllWrapper(canvas, data):1008 canvas.delete(ALL)1009 canvas.create_rectangle(0, 0, data.width, data.height,1010 fill='white', width=0)1011 redrawAll(canvas, data)1012 canvas.update() 1013 def mousePressedWrapper(event, canvas, data):1014 mousePressed(event, data)1015 redrawAllWrapper(canvas, data)1016 def keyPressedWrapper(event, canvas, data):1017 keyPressed(event, data)1018 redrawAllWrapper(canvas, data)1019 def timerFiredWrapper(canvas, data):1020 timerFired(data)1021 redrawAllWrapper(canvas, data)1022 # pause, then call timerFired again1023 canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)1024 # Set up data and call init1025 class Struct(object): pass1026 data = Struct()1027 data.width = width1028 data.height = height1029 data.timerDelay = 20 # milliseconds1030 init(data)1031 # create the root and the canvas1032 root = Tk()1033 canvas = Canvas(root, width=data.width, height=data.height)1034 canvas.pack()1035 # set up events1036 root.bind("<Button-1>", lambda event:1037 mousePressedWrapper(event, canvas, data))1038 root.bind("<Key>", lambda event:1039 keyPressedWrapper(event, canvas, data))1040 timerFiredWrapper(canvas, data)1041 # and launch the app1042 root.mainloop() # blocks until window is closed1043 print("bye!")...

Full Screen

Full Screen

data_detect_end.py

Source:data_detect_end.py Github

copy

Full Screen

...96 dataMat = DataFrame(pd.read_csv(file_name, names=O_COLUMNS_E), dtype=float).round(8).drop(['ER', 'ACC'],97 axis=1)98 print(dataMat.shape)99 actionDataWindow = DataFrame(columns=O_COLUMNS)100 actionDataWindow = dealwithdynamicdata(dataMat, actionDataWindow)101 print(actionDataWindow.shape)102 print('提取动作{0}完毕'.format(toCsvFileSuffix.split('.')[0]))103 if len(actionDataWindow) < ACTION_WINDOW_SIZE: continue104 # 计算右手手腕10号传感器(对应2组数据)在每个采样时刻 t 所对应的三轴加速度合成加速度,确定击球点105 # actionDataWindow['ACC'] = actionDataWindow.apply(lambda row:106 # (float(row['bAX']) + float(row['bAY']) + float(row['bAZ'])),107 # axis=1)108 actionDataWindow['ACC'] = actionDataWindow.apply(109 lambda row: math.sqrt(float(row['bAX']) ** 2 + float(row['bAY']) ** 2 + float(row['bAZ'] ** 2)), axis=1)110 if not os.path.exists(write_dir_name):111 os.mkdir(write_dir_name)112 # 保存提取后的数据113 actionDataWindow.to_csv(os.path.join(write_dir_name, 'action_data_' + toCsvFileSuffix))114 # end for115 print('动作窗口提取完毕')116# 获得正则化函数117# def get_normalize():118# """119# 用于dnn_train正则化数据,和测试集的处理,以及基神经网络服务器程序的处理120# :return:121# """122# file_list = glob.glob('D:\\temp\\action_windows\\*.csv')123#124# action_array = np.zeros(shape=(0, 63))125# for filename in file_list:126# df = np.array(pd.read_csv(filename, dtype=float)).round(6)[1:, 1:-1]127# df = df[:int(len(df) / ACTION_WINDOW_SIZE) * ACTION_WINDOW_SIZE, :]128#129# # 纵向累加数据130# action_array = np.concatenate([action_array, df], axis=0)131#132# # print(action_array.shape) # (127980, 63)133# # 对数据进行正则化处理134# scaler = preprocessing.Normalizer().fit(action_array)135# # print(scaler)136# scaler_path = 'src/greater/pre/normalize.pkl'137# if os.path.exists(scaler_path):138# os.remove(scaler_path)139# joblib.dump(scaler, scaler_path)140# print('正则化建模完毕')141def characteristicFunction(COMPONENTS, read_dir, write_all_feature_file, write_x_de_file):142 file_list = []143 for maindir, subdir, file_name_list in os.walk(read_dir):144 for filename in file_name_list:145 apath = os.path.join(maindir, filename)146 file_list.append(apath)147 print(f'特征提取文件{file_list}')148 all_feature_data = DataFrame(columns=N_COLUMNS_SPE) # 保存全部(动作)的特征变量149 for file_name in file_list:150 print('{}开始提取特征'.format(file_name))151 # 对应动作类别 1.csv ,2.csv ^ 10.csv152 action_spe = str(file_name.split('\\')[-1]).split('_')[-1].split('.')[0]153 dataMat = DataFrame(pd.read_csv(file_name, names=O_COLUMNS_E)[1:],154 dtype=float).round(8).drop(['ER', 'ACC'], axis=1)155 # 特征提取156 X = Feature_process(dataMat, ACTION_WINDOW_SIZE, action=str(action_spe))157 # 对特征进行归一化处理158 x_columns = X.columns.values.tolist()159 x_spe = np.array(X.SPE)160 X = preprocessing.normalize(X)161 X = DataFrame(X, columns=x_columns)162 X['SPE'] = x_spe163 # 获取全部的特征数据,然后训练归一化模型函数164 all_feature_data = all_feature_data.append(X, ignore_index=True).round(6)165 # end for166 all_feature_data.to_csv(write_all_feature_file)167 # 特征降维168 X_de = decomposition(all_feature_data, de_str='PCA', n_components=COMPONENTS).round(6)169 X_de.to_csv(write_x_de_file)170 print('特征提取完毕')171def dealwithdynamicdata(dataMat, actionDataWindow):172 # df = pd.read_csv('src/test/origin_data.csv', names=O_COLUMNS)173 count = 1174 # 第一层窗口175 action_data_window_queue = DataFrame(columns=O_COLUMNS_ACC)176 # 第二层窗口177 second_action_data_queue = DataFrame(columns=O_COLUMNS_ACC)178 isActionDetectStart = False # 动作是否开始179 isActionDetectEnd = False # 动作是否结束180 actionDetectEndCounter = 0 # 动作结束计数器181 actionCount = 0182 with tqdm(total=len(dataMat)) as pbar: # 设置进度条183 # begin while184 while count < len(dataMat):185 pbar.update(1) # 更新进度条...

Full Screen

Full Screen

data_detect.py

Source:data_detect.py Github

copy

Full Screen

...96 dataMat = DataFrame(pd.read_csv(file_name, names=O_COLUMNS_E), dtype=float).round(8).drop(['ER', 'ACC'],97 axis=1)98 print(dataMat.shape)99 actionDataWindow = DataFrame(columns=O_COLUMNS)100 actionDataWindow = dealwithdynamicdata(dataMat, actionDataWindow)101 print(actionDataWindow.shape)102 print('提取动作{0}完毕'.format(toCsvFileSuffix.split('.')[0]))103 if len(actionDataWindow) < ACTION_WINDOW_SIZE: continue104 # 计算右手手腕10号传感器(对应2组数据)在每个采样时刻 t 所对应的三轴加速度合成加速度,确定击球点105 # actionDataWindow['ACC'] = actionDataWindow.apply(lambda row:106 # (float(row['bAX']) + float(row['bAY']) + float(row['bAZ'])),107 # axis=1)108 actionDataWindow['ACC'] = actionDataWindow.apply(109 lambda row: math.sqrt(float(row['bAX']) ** 2 + float(row['bAY']) ** 2 + float(row['bAZ'] ** 2)), axis=1)110 if not os.path.exists(write_dir_name):111 os.mkdir(write_dir_name)112 # 保存提取后的数据113 actionDataWindow.to_csv(os.path.join(write_dir_name, 'action_data_' + toCsvFileSuffix))114 # end for115 print('动作窗口提取完毕')116# 获得正则化函数117# def get_normalize():118# """119# 用于dnn_train正则化数据,和测试集的处理,以及基神经网络服务器程序的处理120# :return:121# """122# file_list = glob.glob('D:\\temp\\action_windows\\*.csv')123#124# action_array = np.zeros(shape=(0, 63))125# for filename in file_list:126# df = np.array(pd.read_csv(filename, dtype=float)).round(6)[1:, 1:-1]127# df = df[:int(len(df) / ACTION_WINDOW_SIZE) * ACTION_WINDOW_SIZE, :]128#129# # 纵向累加数据130# action_array = np.concatenate([action_array, df], axis=0)131#132# # print(action_array.shape) # (127980, 63)133# # 对数据进行正则化处理134# scaler = preprocessing.Normalizer().fit(action_array)135# # print(scaler)136# scaler_path = 'src/greater/pre/normalize.pkl'137# if os.path.exists(scaler_path):138# os.remove(scaler_path)139# joblib.dump(scaler, scaler_path)140# print('正则化建模完毕')141def characteristicFunction(COMPONENTS, read_dir, write_all_feature_file, write_x_de_file):142 file_list = []143 for maindir, subdir, file_name_list in os.walk(read_dir):144 for filename in file_name_list:145 apath = os.path.join(maindir, filename)146 file_list.append(apath)147 print(f'特征提取文件{file_list}')148 all_feature_data = DataFrame(columns=N_COLUMNS_SPE) # 保存全部(动作)的特征变量149 for file_name in file_list:150 print('{}开始提取特征'.format(file_name))151 # 对应动作类别 1.csv ,2.csv ^ 10.csv152 action_spe = str(file_name.split('\\')[-1]).split('_')[-1].split('.')[0]153 dataMat = DataFrame(pd.read_csv(file_name, names=O_COLUMNS_E)[1:],154 dtype=float).round(8).drop(['ER', 'ACC'], axis=1)155 # 特征提取156 X = Feature_process(dataMat, ACTION_WINDOW_SIZE, action=str(action_spe))157 # 对特征进行归一化处理158 x_columns = X.columns.values.tolist()159 x_spe = np.array(X.SPE)160 X = preprocessing.normalize(X)161 X = DataFrame(X, columns=x_columns)162 X['SPE'] = x_spe163 # 获取全部的特征数据,然后训练归一化模型函数164 all_feature_data = all_feature_data.append(X, ignore_index=True).round(6)165 # end for166 all_feature_data.to_csv(write_all_feature_file)167 # 特征降维168 X_de = decomposition(all_feature_data, de_str='PCA', n_components=COMPONENTS).round(6)169 X_de.to_csv(write_x_de_file)170 print('特征提取完毕')171def dealwithdynamicdata(dataMat, actionDataWindow):172 # df = pd.read_csv('src/test/origin_data.csv', names=O_COLUMNS)173 count = 1174 # 第一层窗口175 action_data_window_queue = DataFrame(columns=O_COLUMNS_ACC)176 # 第二层窗口177 second_action_data_queue = DataFrame(columns=O_COLUMNS_ACC)178 isActionDetectStart = False # 动作是否开始179 actionCount = 0180 with tqdm(total=len(dataMat)) as pbar: # 设置进度条181 # begin while182 while count < len(dataMat):183 pbar.update(1) # 更新进度条184 if len(action_data_window_queue) == FIRST_ACTION_DATA_WINDOW_SIZE:185 action_data_window_queue = action_data_window_queue[MOVIE_SIZE:]...

Full Screen

Full Screen

piglow.py

Source:piglow.py Github

copy

Full Screen

...25 else:26 print "Unable to determine Raspberry Pi revision."27 exit28 self.bus = SMBus(i2c_bus)29 self.bus.write_i2c_block_data(0x54, 0x00, [0x01])30 self.bus.write_byte_data(0x54, 0x13, 0xFF)31 self.bus.write_byte_data(0x54, 0x14, 0xFF)32 self.bus.write_byte_data(0x54, 0x15, 0xFF)33 def white(self, value):34 self.bus.write_byte_data(0x54, 0x0A, value)35 self.bus.write_byte_data(0x54, 0x0B, value)36 self.bus.write_byte_data(0x54, 0x0D, value)37 self.bus.write_byte_data(0x54, 0x16, 0xFF)38 def blue(self, value):39 self.bus.write_byte_data(0x54, 0x05, value)40 self.bus.write_byte_data(0x54, 0x0C, value)41 self.bus.write_byte_data(0x54, 0x0F, value)42 self.bus.write_byte_data(0x54, 0x16, 0xFF)43 def green(self, value):44 self.bus.write_byte_data(0x54, 0x06, value)45 self.bus.write_byte_data(0x54, 0x04, value)46 self.bus.write_byte_data(0x54, 0x0E, value)47 self.bus.write_byte_data(0x54, 0x16, 0xFF)48 def yellow(self, value):49 self.bus.write_byte_data(0x54, 0x09, value)50 self.bus.write_byte_data(0x54, 0x03, value)51 self.bus.write_byte_data(0x54, 0x10, value)52 self.bus.write_byte_data(0x54, 0x16, 0xFF)53 def orange(self, value):54 self.bus.write_byte_data(0x54, 0x08, value)55 self.bus.write_byte_data(0x54, 0x02, value)56 self.bus.write_byte_data(0x54, 0x11, value)57 self.bus.write_byte_data(0x54, 0x16, 0xFF)58 def red(self, value):59 self.bus.write_byte_data(0x54, 0x07, value)60 self.bus.write_byte_data(0x54, 0x01, value)61 self.bus.write_byte_data(0x54, 0x12, value)62 self.bus.write_byte_data(0x54, 0x16, 0xFF)63 def all(self, value):64 v = value65 self.bus.write_i2c_block_data(66 0x54, 0x01, [v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v])67 self.bus.write_byte_data(0x54, 0x16, 0xFF)68 def arm(self, arm, value):69 if arm == 1:70 self.bus.write_byte_data(0x54, 0x07, value)71 self.bus.write_byte_data(0x54, 0x08, value)72 self.bus.write_byte_data(0x54, 0x09, value)73 self.bus.write_byte_data(0x54, 0x06, value)74 self.bus.write_byte_data(0x54, 0x05, value)75 self.bus.write_byte_data(0x54, 0x0A, value)76 self.bus.write_byte_data(0x54, 0x16, 0xFF)77 elif arm == 2:78 self.bus.write_byte_data(0x54, 0x0B, value)79 self.bus.write_byte_data(0x54, 0x0C, value)80 self.bus.write_byte_data(0x54, 0x0E, value)81 self.bus.write_byte_data(0x54, 0x10, value)82 self.bus.write_byte_data(0x54, 0x11, value)83 self.bus.write_byte_data(0x54, 0x12, value)84 self.bus.write_byte_data(0x54, 0x16, 0xFF)85 elif arm == 3:86 self.bus.write_byte_data(0x54, 0x01, value)87 self.bus.write_byte_data(0x54, 0x02, value)88 self.bus.write_byte_data(0x54, 0x03, value)89 self.bus.write_byte_data(0x54, 0x04, value)90 self.bus.write_byte_data(0x54, 0x0F, value)91 self.bus.write_byte_data(0x54, 0x0D, value)92 self.bus.write_byte_data(0x54, 0x16, 0xFF)93 else:94 print "Unknown number, expected only 1, 2 or 3"95 def arm1(self, value):96 self.bus.write_byte_data(0x54, 0x07, value)97 self.bus.write_byte_data(0x54, 0x08, value)98 self.bus.write_byte_data(0x54, 0x09, value)99 self.bus.write_byte_data(0x54, 0x06, value)100 self.bus.write_byte_data(0x54, 0x05, value)101 self.bus.write_byte_data(0x54, 0x0A, value)102 self.bus.write_byte_data(0x54, 0x16, 0xFF)103 def arm2(self, value):104 self.bus.write_byte_data(0x54, 0x0B, value)105 self.bus.write_byte_data(0x54, 0x0C, value)106 self.bus.write_byte_data(0x54, 0x0E, value)107 self.bus.write_byte_data(0x54, 0x10, value)108 self.bus.write_byte_data(0x54, 0x11, value)109 self.bus.write_byte_data(0x54, 0x12, value)110 self.bus.write_byte_data(0x54, 0x16, 0xFF)111 def arm3(self, value):112 self.bus.write_byte_data(0x54, 0x01, value)113 self.bus.write_byte_data(0x54, 0x02, value)114 self.bus.write_byte_data(0x54, 0x03, value)115 self.bus.write_byte_data(0x54, 0x04, value)116 self.bus.write_byte_data(0x54, 0x0F, value)117 self.bus.write_byte_data(0x54, 0x0D, value)118 self.bus.write_byte_data(0x54, 0x16, 0xFF)119 def colour(self, colour, value):120 if colour == 1 or colour == "white":121 self.bus.write_byte_data(0x54, 0x0A, value)122 self.bus.write_byte_data(0x54, 0x0B, value)123 self.bus.write_byte_data(0x54, 0x0D, value)124 self.bus.write_byte_data(0x54, 0x16, 0xFF)125 elif colour == 2 or colour == "blue":126 self.bus.write_byte_data(0x54, 0x05, value)127 self.bus.write_byte_data(0x54, 0x0C, value)128 self.bus.write_byte_data(0x54, 0x0F, value)129 self.bus.write_byte_data(0x54, 0x16, 0xFF)130 elif colour == 3 or colour == "green":131 self.bus.write_byte_data(0x54, 0x06, value)132 self.bus.write_byte_data(0x54, 0x04, value)133 self.bus.write_byte_data(0x54, 0x0E, value)134 self.bus.write_byte_data(0x54, 0x16, 0xFF)135 elif colour == 4 or colour == "yellow":136 self.bus.write_byte_data(0x54, 0x09, value)137 self.bus.write_byte_data(0x54, 0x03, value)138 self.bus.write_byte_data(0x54, 0x10, value)139 self.bus.write_byte_data(0x54, 0x16, 0xFF)140 elif colour == 5 or colour == "orange":141 self.bus.write_byte_data(0x54, 0x08, value)142 self.bus.write_byte_data(0x54, 0x02, value)143 self.bus.write_byte_data(0x54, 0x11, value)144 self.bus.write_byte_data(0x54, 0x16, 0xFF)145 elif colour == 6 or colour == "red":146 self.bus.write_byte_data(0x54, 0x07, value)147 self.bus.write_byte_data(0x54, 0x01, value)148 self.bus.write_byte_data(0x54, 0x12, value)149 self.bus.write_byte_data(0x54, 0x16, 0xFF)150 else:151 print "Only colours 1 - 6 or color names are allowed"152 def led(self, led, value):153 leds = [154 "0x00", "0x07", "0x08", "0x09", "0x06", "0x05", "0x0A", "0x12", "0x11",155 "0x10", "0x0E", "0x0C", "0x0B", "0x01", "0x02", "0x03", "0x04", "0x0F", "0x0D"]156 self.bus.write_byte_data(0x54, int(leds[led], 16), value)157 self.bus.write_byte_data(0x54, 0x16, 0xFF)158 def led1(self, value):159 self.bus.write_byte_data(0x54, 0x07, value)160 self.bus.write_byte_data(0x54, 0x16, 0xFF)161 def led2(self, value):162 self.bus.write_byte_data(0x54, 0x08, value)163 self.bus.write_byte_data(0x54, 0x16, 0xFF)164 def led3(self, value):165 self.bus.write_byte_data(0x54, 0x09, value)166 self.bus.write_byte_data(0x54, 0x16, 0xFF)167 def led4(self, value):168 self.bus.write_byte_data(0x54, 0x06, value)169 self.bus.write_byte_data(0x54, 0x16, 0xFF)170 def led5(self, value):171 self.bus.write_byte_data(0x54, 0x05, value)172 self.bus.write_byte_data(0x54, 0x16, 0xFF)173 def led6(self, value):174 self.bus.write_byte_data(0x54, 0x0A, value)175 self.bus.write_byte_data(0x54, 0x16, 0xFF)176 def led7(self, value):177 self.bus.write_byte_data(0x54, 0x12, value)178 self.bus.write_byte_data(0x54, 0x16, 0xFF)179 def led8(self, value):180 self.bus.write_byte_data(0x54, 0x11, value)181 self.bus.write_byte_data(0x54, 0x16, 0xFF)182 def led9(self, value):183 self.bus.write_byte_data(0x54, 0x10, value)184 self.bus.write_byte_data(0x54, 0x16, 0xFF)185 def led10(self, value):186 self.bus.write_byte_data(0x54, 0x0E, value)187 self.bus.write_byte_data(0x54, 0x16, 0xFF)188 def led11(self, value):189 self.bus.write_byte_data(0x54, 0x0C, value)190 self.bus.write_byte_data(0x54, 0x16, 0xFF)191 def led12(self, value):192 self.bus.write_byte_data(0x54, 0x0B, value)193 self.bus.write_byte_data(0x54, 0x16, 0xFF)194 def led13(self, value):195 self.bus.write_byte_data(0x54, 0x01, value)196 self.bus.write_byte_data(0x54, 0x16, 0xFF)197 def led14(self, value):198 self.bus.write_byte_data(0x54, 0x02, value)199 self.bus.write_byte_data(0x54, 0x16, 0xFF)200 def led15(self, value):201 self.bus.write_byte_data(0x54, 0x03, value)202 self.bus.write_byte_data(0x54, 0x16, 0xFF)203 def led16(self, value):204 self.bus.write_byte_data(0x54, 0x04, value)205 self.bus.write_byte_data(0x54, 0x16, 0xFF)206 def led17(self, value):207 self.bus.write_byte_data(0x54, 0x0F, value)208 self.bus.write_byte_data(0x54, 0x16, 0xFF)209 def led18(self, value):210 self.bus.write_byte_data(0x54, 0x0D, value)...

Full Screen

Full Screen

backbone.py

Source:backbone.py Github

copy

Full Screen

1#! /usr/bin/env python2# coding=utf-83"""4Khởi tạo các mô hình darknet trong yolo5"""6import tensorflow as tf7import core.common as common8def darknet53(input_data):9 input_data = common.convolutional(input_data, (3, 3, 3, 32))10 input_data = common.convolutional(11 input_data, (3, 3, 32, 64), downsample=True)12 for i in range(1):13 input_data = common.residual_block(input_data, 64, 32, 64)14 input_data = common.convolutional(15 input_data, (3, 3, 64, 128), downsample=True)16 for i in range(2):17 input_data = common.residual_block(input_data, 128, 64, 128)18 input_data = common.convolutional(19 input_data, (3, 3, 128, 256), downsample=True)20 for i in range(8):21 input_data = common.residual_block(input_data, 256, 128, 256)22 route_1 = input_data23 input_data = common.convolutional(24 input_data, (3, 3, 256, 512), downsample=True)25 for i in range(8):26 input_data = common.residual_block(input_data, 512, 256, 512)27 route_2 = input_data28 input_data = common.convolutional(29 input_data, (3, 3, 512, 1024), downsample=True)30 for i in range(4):31 input_data = common.residual_block(input_data, 1024, 512, 1024)32 return route_1, route_2, input_data33def cspdarknet53(input_data):34 input_data = common.convolutional(35 input_data, (3, 3, 3, 32), activate_type="mish")36 input_data = common.convolutional(37 input_data, (3, 3, 32, 64), downsample=True, activate_type="mish")38 route = input_data39 route = common.convolutional(route, (1, 1, 64, 64), activate_type="mish")40 input_data = common.convolutional(41 input_data, (1, 1, 64, 64), activate_type="mish")42 for i in range(1):43 input_data = common.residual_block(44 input_data, 64, 32, 64, activate_type="mish")45 input_data = common.convolutional(46 input_data, (1, 1, 64, 64), activate_type="mish")47 input_data = tf.concat([input_data, route], axis=-1)48 input_data = common.convolutional(49 input_data, (1, 1, 128, 64), activate_type="mish")50 input_data = common.convolutional(51 input_data, (3, 3, 64, 128), downsample=True, activate_type="mish")52 route = input_data53 route = common.convolutional(route, (1, 1, 128, 64), activate_type="mish")54 input_data = common.convolutional(55 input_data, (1, 1, 128, 64), activate_type="mish")56 for i in range(2):57 input_data = common.residual_block(58 input_data, 64, 64, 64, activate_type="mish")59 input_data = common.convolutional(60 input_data, (1, 1, 64, 64), activate_type="mish")61 input_data = tf.concat([input_data, route], axis=-1)62 input_data = common.convolutional(63 input_data, (1, 1, 128, 128), activate_type="mish")64 input_data = common.convolutional(65 input_data, (3, 3, 128, 256), downsample=True, activate_type="mish")66 route = input_data67 route = common.convolutional(route, (1, 1, 256, 128), activate_type="mish")68 input_data = common.convolutional(69 input_data, (1, 1, 256, 128), activate_type="mish")70 for i in range(8):71 input_data = common.residual_block(72 input_data, 128, 128, 128, activate_type="mish")73 input_data = common.convolutional(74 input_data, (1, 1, 128, 128), activate_type="mish")75 input_data = tf.concat([input_data, route], axis=-1)76 input_data = common.convolutional(77 input_data, (1, 1, 256, 256), activate_type="mish")78 route_1 = input_data79 input_data = common.convolutional(80 input_data, (3, 3, 256, 512), downsample=True, activate_type="mish")81 route = input_data82 route = common.convolutional(route, (1, 1, 512, 256), activate_type="mish")83 input_data = common.convolutional(84 input_data, (1, 1, 512, 256), activate_type="mish")85 for i in range(8):86 input_data = common.residual_block(87 input_data, 256, 256, 256, activate_type="mish")88 input_data = common.convolutional(89 input_data, (1, 1, 256, 256), activate_type="mish")90 input_data = tf.concat([input_data, route], axis=-1)91 input_data = common.convolutional(92 input_data, (1, 1, 512, 512), activate_type="mish")93 route_2 = input_data94 input_data = common.convolutional(95 input_data, (3, 3, 512, 1024), downsample=True, activate_type="mish")96 route = input_data97 route = common.convolutional(98 route, (1, 1, 1024, 512), activate_type="mish")99 input_data = common.convolutional(100 input_data, (1, 1, 1024, 512), activate_type="mish")101 for i in range(4):102 input_data = common.residual_block(103 input_data, 512, 512, 512, activate_type="mish")104 input_data = common.convolutional(105 input_data, (1, 1, 512, 512), activate_type="mish")106 input_data = tf.concat([input_data, route], axis=-1)107 input_data = common.convolutional(108 input_data, (1, 1, 1024, 1024), activate_type="mish")109 input_data = common.convolutional(input_data, (1, 1, 1024, 512))110 input_data = common.convolutional(input_data, (3, 3, 512, 1024))111 input_data = common.convolutional(input_data, (1, 1, 1024, 512))112 input_data = tf.concat([tf.nn.max_pool(input_data, ksize=13, padding='SAME', strides=1), tf.nn.max_pool(113 input_data, ksize=9, padding='SAME', strides=1), tf.nn.max_pool(input_data, ksize=5, padding='SAME', strides=1), input_data], axis=-1)114 input_data = common.convolutional(input_data, (1, 1, 2048, 512))115 input_data = common.convolutional(input_data, (3, 3, 512, 1024))116 input_data = common.convolutional(input_data, (1, 1, 1024, 512))117 return route_1, route_2, input_data118def cspdarknet53_tiny(input_data):119 input_data = common.convolutional(120 input_data, (3, 3, 3, 32), downsample=True)121 input_data = common.convolutional(122 input_data, (3, 3, 32, 64), downsample=True)123 input_data = common.convolutional(input_data, (3, 3, 64, 64))124 route = input_data125 input_data = common.route_group(input_data, 2, 1)126 input_data = common.convolutional(input_data, (3, 3, 32, 32))127 route_1 = input_data128 input_data = common.convolutional(input_data, (3, 3, 32, 32))129 input_data = tf.concat([input_data, route_1], axis=-1)130 input_data = common.convolutional(input_data, (1, 1, 32, 64))131 input_data = tf.concat([route, input_data], axis=-1)132 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)133 input_data = common.convolutional(input_data, (3, 3, 64, 128))134 route = input_data135 input_data = common.route_group(input_data, 2, 1)136 input_data = common.convolutional(input_data, (3, 3, 64, 64))137 route_1 = input_data138 input_data = common.convolutional(input_data, (3, 3, 64, 64))139 input_data = tf.concat([input_data, route_1], axis=-1)140 input_data = common.convolutional(input_data, (1, 1, 64, 128))141 input_data = tf.concat([route, input_data], axis=-1)142 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)143 input_data = common.convolutional(input_data, (3, 3, 128, 256))144 route = input_data145 input_data = common.route_group(input_data, 2, 1)146 input_data = common.convolutional(input_data, (3, 3, 128, 128))147 route_1 = input_data148 input_data = common.convolutional(input_data, (3, 3, 128, 128))149 input_data = tf.concat([input_data, route_1], axis=-1)150 input_data = common.convolutional(input_data, (1, 1, 128, 256))151 route_1 = input_data152 input_data = tf.concat([route, input_data], axis=-1)153 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)154 input_data = common.convolutional(input_data, (3, 3, 512, 512))155 return route_1, input_data156def darknet53_tiny(input_data):157 input_data = common.convolutional(input_data, (3, 3, 3, 16))158 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)159 input_data = common.convolutional(input_data, (3, 3, 16, 32))160 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)161 input_data = common.convolutional(input_data, (3, 3, 32, 64))162 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)163 input_data = common.convolutional(input_data, (3, 3, 64, 128))164 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)165 input_data = common.convolutional(input_data, (3, 3, 128, 256))166 route_1 = input_data167 input_data = tf.keras.layers.MaxPool2D(2, 2, 'same')(input_data)168 input_data = common.convolutional(input_data, (3, 3, 256, 512))169 input_data = tf.keras.layers.MaxPool2D(2, 1, 'same')(input_data)170 input_data = common.convolutional(input_data, (3, 3, 512, 1024))...

Full Screen

Full Screen

decryptionUtils.py

Source:decryptionUtils.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import pyDes3import urllib4import re5from regexUtils import parseTextToGroups6from javascriptUtils import JsFunctions, JsUnpacker, JsUnpackerV2, JsUnpacker95High, JsUnwiser, JsUnIonCube, JsUnFunc, JsUnPP, JsUnPush7def encryptDES_ECB(data, key):8 data = data.encode()9 k = pyDes.des(key, pyDes.ECB, IV=None, pad=None, padmode=pyDes.PAD_PKCS5)10 d = k.encrypt(data)11 assert k.decrypt(d, padmode=pyDes.PAD_PKCS5) == data12 return d13def gAesDec(data, key):14 import mycrypt15 return mycrypt.decrypt(key,data)16def aesDec(data, key):17 from base64 import b64decode18 try:19 from Crypto.Cipher import AES20 except ImportError:21 import pyaes as AES22 iv = 16 * '\x00'23 cipher = AES.new(b64decode(key), AES.MODE_CBC, IV=iv)24 padded_plaintext = cipher.decrypt(b64decode(data))25 padding_len = ord(padded_plaintext[-1])26 return padded_plaintext[:-padding_len]27def wdecode(data):28 from itertools import chain29 30 in_data = re.split('\W+',data)31 pos = in_data.index(max(in_data,key=len))32 codec = "".join(chain(*zip(in_data[pos][:5], in_data[pos+1][:5], in_data[pos+2][:5])))33 data = "".join(chain(*zip(in_data[pos][5:], in_data[pos+1][5:], in_data[pos+2][5:])))34 35 ring = 036 res = []37 for i in xrange(0,len(data),2):38 modifier = -139 if (ord(codec[ring]) % 2):40 modifier = 141 res.append( chr( int(data[i:i+2],36) - modifier ) )42 43 ring = ring + 144 if ring >= len(codec):45 ring = 046 return ''.join(res)47def encryptJimey(data):48 result = encryptDES_ECB(data,"PASSWORD").encode('base64').replace('/','').strip()49 return result50# used by 24cast51def destreamer(s):52 #remove all but[0-9A-Z]53 string = re.sub("[^0-9A-Z]", "", s.upper())54 result = ""55 nextchar = ""56 for i in range(0,len(string)-1):57 nextchar += string[i]58 if len(nextchar) == 2:59 result += ntos(int(nextchar,16))60 nextchar = ""61 return result62def ntos(n):63 n = hex(n)[2:]64 if len(n) == 1:65 n = "0" + n66 n = "%" + n67 return urllib.unquote(n)68def doDemystify(data):69 escape_again=False70 71 #init jsFunctions and jsUnpacker72 jsF = JsFunctions()73 jsU = JsUnpacker()74 jsUV2 =JsUnpackerV2()75 jsUW = JsUnwiser()76 jsUI = JsUnIonCube()77 jsUF = JsUnFunc()78 jsUP = JsUnPP()79 jsU95 = JsUnpacker95High()80 JsPush = JsUnPush()81 # replace NUL82 data = data.replace('\0','')83 # unescape84 r = re.compile('a1=["\'](%3C(?=[^\'"]*%\w\w)[^\'"]+)["\']')85 while r.findall(data):86 for g in r.findall(data):87 quoted=g88 data = data.replace(quoted, urllib.unquote_plus(quoted))89 90 91 r = re.compile('unescape\(\s*["\']((?=[^\'"]*%\w\w)[^\'"]+)["\']')92 while r.findall(data):93 for g in r.findall(data):94 quoted=g95 data = data.replace(quoted, urllib.unquote_plus(quoted))96 97 r = re.compile('unescape\(\s*["\']((?=[^\'"]*\\u00)[^\'"]+)["\']')98 while r.findall(data):99 for g in r.findall(data):100 quoted=g101 data = data.replace(quoted, quoted.decode('unicode-escape'))102 r = re.compile('(\'\+dec\("\w+"\)\+\')')103 while r.findall(data):104 for g in r.findall(data):105 r2 = re.compile('dec\("(\w+)"\)')106 for dec_data in r2.findall(g):107 res = ''108 for i in dec_data:109 res = res + chr(ord(i) ^ 123)110 data = data.replace(g, res)111 112 r = re.compile('(eval\(decodeURIComponent\(atob\([\'"][^\'"]+[\'"]\)\)\);)')113 while r.findall(data):114 for g in r.findall(data):115 r2 = re.compile('eval\(decodeURIComponent\(atob\([\'"]([^\'"]+)[\'"]\)\)\);')116 for base64_data in r2.findall(g):117 data = data.replace(g, urllib.unquote(base64_data.decode('base-64')))118 119 r = re.compile('(base\([\'"]*[^\'"\)]+[\'"]*\))')120 while r.findall(data):121 for g in r.findall(data):122 r2 = re.compile('base\([\'"]*([^\'"\)]+)[\'"]*\)')123 for base64_data in r2.findall(g):124 data = data.replace(g, urllib.unquote(base64_data.decode('base-64')))125 escape_again=True126 127 r = re.compile('(eval\\(function\\(\w+,\w+,\w+,\w+.*?join\\(\'\'\\);*}\\(.*?\\))', flags=re.DOTALL)128 for g in r.findall(data):129 try:130 data = data.replace(g, wdecode(g))131 escape_again=True132 except:133 pass134 # n98c4d2c135 if 'function n98c4d2c(' in data:136 gs = parseTextToGroups(data, ".*n98c4d2c\(''\).*?'(%[^']+)'.*")137 if gs != None and gs != []:138 data = data.replace(gs[0], jsF.n98c4d2c(gs[0]))139 # o61a2a8f140 if 'function o61a2a8f(' in data:141 gs = parseTextToGroups(data, ".*o61a2a8f\(''\).*?'(%[^']+)'.*")142 if gs != None and gs != []:143 data = data.replace(gs[0], jsF.o61a2a8f(gs[0]))144 # RrRrRrRr145 if 'function RrRrRrRr(' in data:146 r = re.compile("(RrRrRrRr\(\"(.*?)\"\);)</SCRIPT>", re.IGNORECASE + re.DOTALL)147 gs = r.findall(data)148 if gs != None and gs != []:149 for g in gs:150 data = data.replace(g[0], jsF.RrRrRrRr(g[1].replace('\\','')))151 # hp_d01152 if 'function hp_d01(' in data:153 r = re.compile("hp_d01\(unescape\(\"(.+?)\"\)\);//-->")154 gs = r.findall(data)155 if gs:156 for g in gs:157 data = data.replace(g, jsF.hp_d01(g))158 # ew_dc159 if 'function ew_dc(' in data:160 r = re.compile("ew_dc\(unescape\(\"(.+?)\"\)\);</SCRIPT>")161 gs = r.findall(data)162 if gs:163 for g in gs:164 data = data.replace(g, jsF.ew_dc(g))165 # pbbfa0166 if 'function pbbfa0(' in data:167 r = re.compile("pbbfa0\(''\).*?'(.+?)'.\+.unescape")168 gs = r.findall(data)169 if gs:170 for g in gs:171 data = data.replace(g, jsF.pbbfa0(g))172 # util.de173 if 'Util.de' in data:174 r = re.compile("Util.de\(unescape\(['\"](.+?)['\"]\)\)")175 gs = r.findall(data)176 if gs:177 for g in gs:178 data = data.replace(g,g.decode('base64'))179 # 24cast180 if 'destreamer(' in data:181 r = re.compile("destreamer\(\"(.+?)\"\)")182 gs = r.findall(data)183 if gs:184 for g in gs:185 data = data.replace(g, destreamer(g))186 # JS P,A,C,K,E,D187 if jsU.containsPacked(data):188 data = jsU.unpackAll(data)189 escape_again=True190 #if still exists then apply v2191 if jsUV2.containsPacked(data):192 data = jsUV2.unpackAll(data)193 escape_again=True194 195 if jsU95.containsPacked(data):196 data = jsU95.unpackAll(data)197 escape_again=True198 # JS W,I,S,E199 if jsUW.containsWise(data):200 data = jsUW.unwiseAll(data)201 escape_again=True202 # JS IonCube203 if jsUI.containsIon(data):204 data = jsUI.unIonALL(data)205 escape_again=True206 207 # Js unFunc208 if jsUF.cointainUnFunc(data):209 data = jsUF.unFuncALL(data)210 escape_again=True211 212 if jsUP.containUnPP(data):213 data = jsUP.UnPPAll(data)214 escape_again=True215 216 if JsPush.containUnPush(data):217 data = JsPush.UnPush(data)218 # unescape again219 if escape_again:220 data = doDemystify(data)...

Full Screen

Full Screen

app.py

Source:app.py Github

copy

Full Screen

1# git - https://github.com/2ujin/theteams_project2# language - azure, azure storage, excel, nodejs, python, html, css, javascript3# 2019.07.27 - 2019.08.014# 30분에 한번씩 가격을 크롤링 (azure - timetrigger 함수 사용)5# 크롤링 한 값 -> azure storage에 저장6# azure storage -> excel로 export7# excel에 저장되어 있는 가격 값을 python 배열에 저장8# python flask를 사용해서 chart html에 값 넘겨서 차트완성 !!!! 910from flask import Flask, render_template, request11from openpyxl import load_workbook12app = Flask(__name__)1314load_wb = load_workbook("/Users/Mirim/Desktop/priceTbl.xlsx", data_only=True) #엑셀 파일 갖고오기15load_ws = load_wb['priceTbl'] # 시트 이름으로 불러오기1617#30분 주기로 크롤링 한 가격 값18data_arr1 = [load_ws.cell(2, 4).value, load_ws.cell(2, 5).value, load_ws.cell(2, 6).value, load_ws.cell(2, 7).value, load_ws.cell(2, 8).value]; #119data_arr2 = [load_ws.cell(3, 4).value, load_ws.cell(3, 5).value, load_ws.cell(3, 6).value, load_ws.cell(3, 7).value, load_ws.cell(3, 8).value];20data_arr3 = [load_ws.cell(4, 4).value, load_ws.cell(4, 5).value, load_ws.cell(4, 6).value, load_ws.cell(4, 7).value, load_ws.cell(4, 8).value];21data_arr4 = [load_ws.cell(5, 4).value, load_ws.cell(5, 5).value, load_ws.cell(5, 6).value, load_ws.cell(5, 7).value, load_ws.cell(5, 8).value];22data_arr5 = [load_ws.cell(6, 4).value, load_ws.cell(6, 5).value, load_ws.cell(6, 6).value, load_ws.cell(6, 7).value, load_ws.cell(6, 8).value];23data_arr6 = [load_ws.cell(7, 4).value, load_ws.cell(7, 5).value, load_ws.cell(7, 6).value, load_ws.cell(7, 7).value, load_ws.cell(7, 8).value];24data_arr7 = [load_ws.cell(8, 4).value, load_ws.cell(8, 5).value, load_ws.cell(8, 6).value, load_ws.cell(8, 7).value, load_ws.cell(8, 8).value];25data_arr8 = [load_ws.cell(9, 4).value, load_ws.cell(9, 5).value, load_ws.cell(9, 6).value, load_ws.cell(9, 7).value, load_ws.cell(9, 8).value];26data_arr9 = [load_ws.cell(10, 4).value, load_ws.cell(10, 5).value, load_ws.cell(10, 6).value, load_ws.cell(10, 7).value, load_ws.cell(10, 8).value];27data_arr10 = [load_ws.cell(11, 4).value, load_ws.cell(11, 5).value, load_ws.cell(11, 6).value, load_ws.cell(11, 7).value, load_ws.cell(11, 8).value];2829date1 = [load_ws.cell(2, 2).value[20:24], load_ws.cell(3, 2).value[19:24], load_ws.cell(4, 2).value[20:24], load_ws.cell(5, 2).value[19:24], load_ws.cell(6, 2).value[20:24],30 load_ws.cell(7, 2).value[19:24], load_ws.cell(8, 2).value[20:24], load_ws.cell(9, 2).value[19:24], load_ws.cell(10, 2).value[20:24], load_ws.cell(11, 2).value[19:24]];313233@app.route('/') #test라는 루트34def main():35 return render_template('game_chart.html',36 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)3738@app.route('/game1.html')39def game1():40 return render_template('game1.html',41 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)4243@app.route('/game2.html')44def game2():45 return render_template('game2.html',46 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)4748@app.route('/game3.html')49def game3():50 return render_template('game3.html',51 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)525354@app.route('/game4.html')55def game4():56 return render_template('game4.html',57 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)5859@app.route('/game5.html')60def game5():61 return render_template('game5.html',62 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)6364@app.route('/game_chart.html')65def game_chart():66 return render_template('game_chart.html',67 data_arr1=data_arr1, data_arr2=data_arr2, data_arr3=data_arr3, data_arr4=data_arr4, data_arr5=data_arr5, data_arr6=data_arr6, data_arr7=data_arr7, data_arr8=data_arr8, data_arr9=data_arr9, data_arr10=data_arr10, date1=date1)6869if __name__ == '__main__': ...

Full Screen

Full Screen

model.py

Source:model.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""3Created on Tue May 19 19:14:07 202045@author: Sanjeev Reddy6"""7import numpy as np8import pandas as pd9from statistics import mode10import sklearn11from sklearn import tree12from sklearn.tree import DecisionTreeClassifier13from sklearn.model_selection import train_test_split14from flask import Flask,render_template,url_for,request15import pickle16data=pd.read_csv(r'C:\Users\Sanjeev Reddy\Desktop\chronic_kidney_disease_flask\kidney_disease.csv')17data.drop('id',axis=1,inplace=True)18data['rbc']=data['rbc'].fillna(value=data['rbc'].mode().iloc[0])19data['pc']=data['pc'].fillna(value=data['pc'].mode().iloc[0])20data['pcc']=data['pcc'].fillna(value=data['pcc'].mode().iloc[0])21data['ba']=data['ba'].fillna(value=data['ba'].mode().iloc[0])22data['htn']=data['htn'].fillna(value=data['htn'].mode().iloc[0])23data['dm']=data['dm'].fillna(value=data['dm'].mode().iloc[0])24data['cad']=data['cad'].fillna(value=data['cad'].mode().iloc[0])25data['appet']=data['appet'].fillna(value=data['appet'].mode().iloc[0])26data['pe']=data['pe'].fillna(value=data['pe'].mode().iloc[0])27data['ane']=data['ane'].fillna(value=data['ane'].mode().iloc[0])28data['age']=data['age'].fillna(value=data['age'].mean())29data['bp']=data['bp'].fillna(value=data['bp'].mean())30data['sg']=data['sg'].fillna(value=data['sg'].mean())31data['al']=data['al'].fillna(value=data['al'].mean())32data['su']=data['su'].fillna(value=data['su'].mean())33data['bgr']=data['bgr'].fillna(value=data['bgr'].mean())34data['bu']=data['bu'].fillna(value=data['bu'].mean())35data['sc']=data['sc'].fillna(value=data['sc'].mean())36data['sod']=data['sod'].fillna(value=data['sod'].mean())37data['pot']=data['pot'].fillna(value=data['pot'].mean())38data['hemo']=data['hemo'].fillna(value=data['hemo'].mean())39data['pcv']=data['pcv'].fillna(value=data['pcv'].mode().iloc[0])40data['wc']=data['wc'].fillna(value=data['wc'].mode().iloc[0])41data['rc']=data['rc'].fillna(value=data['rc'].mode().iloc[0])42data.wc=data.wc.replace("\t6200",6200)43data.wc=data.wc.replace("\t8400",8400)44data.wc=data.wc.replace("\t?",8800)45data.pcv=data.pcv.replace("\t?",41)46data.rc=data.rc.replace("\t?",5.2)47data.pcv=data.pcv.astype(int)48data.wc=data.wc.astype(int)49data.rc=data.rc.astype(float)50data.classification=data.classification.replace('ckd\t','ckd')51data.classification=[1 if each=="ckd" else 0 for each in data.classification]52data.rbc=[1 if each=="abnormal" else 0 for each in data.rbc]53data.pc=[1 if each=="abnormal" else 0 for each in data.pc]54data.pcc=[1 if each=="present" else 0 for each in data.pcc]55data.ba=[1 if each=="present" else 0 for each in data.ba]56data.pcc=[1 if each=="present" else 0 for each in data.pcc]57data.htn=[1 if each=="present" else 0 for each in data.htn]58data.dm=[1 if each=="present" else 0 for each in data.dm]59data.cad=[1 if each=="present" else 0 for each in data.cad]60data.appet=[1 if each=="present" else 0 for each in data.appet]61data.pe=[1 if each=="present" else 0 for each in data.pe]62data.ane=[1 if each=="present" else 0 for each in data.ane]63x=data.iloc[:,1:5]64print(x)65y=data.iloc[:,24:]66x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=1)67dt=DecisionTreeClassifier(criterion='entropy',random_state=0)68dt.fit(x_train,y_train)69pickle.dump(dt,open('model.pkl','wb'))70model=pickle.load(open('model.pkl','rb')) ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Matchers } = require("@pact-foundation/pact");2const { somethingLike } = Matchers;3const { like } = Matchers;4const getLoginRequest = {5 withRequest: {6 headers: {7 },8 body: {9 },10 },11};12const getLoginResponse = {13 willRespondWith: {14 headers: {15 },16 body: {17 token: like("authToken"),18 },19 },20};21module.exports = {22};23const { Matchers } = require("@pact-foundation/pact");24const { somethingLike } = Matchers;25const { like } = Matchers;26const getLoginRequest = {27 withRequest: {28 headers: {29 },30 body: {31 },32 },33};34const getLoginResponse = {35 willRespondWith: {36 headers: {37 },38 body: {39 token: like("authToken"),40 },41 },42};43module.exports = {44};45const { Matchers } = require("@pact-foundation/pact");46const { somethingLike } = Matchers;47const { like } = Matchers;48const getLoginRequest = {49 withRequest: {50 headers: {51 },52 body: {53 },54 },55};56const getLoginResponse = {57 willRespondWith: {58 headers: {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pact-foundation-pact automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful