def __init__(self, extraction_dest='/tmp/tidzam/opus', extraction_rules={}, dd=True): threading.Thread.__init__(self) self.lock = threading.Lock() self.socketIO = None self.socketio_address = App.socketIOanalyzerAdress self.stopFlag = threading.Event() self.buffer = [] self.label_dic = [] self.queue_fifo = collections.OrderedDict() self.queue_fifo_length = 600 self.dd = dd self.extraction_dest = extraction_dest self.extraction_rules = extraction_rules self.database_info = {} self.dynamic_distribution = [] self.dynamic_distribution_prev = [] self.dynamic_distribution_inc = 0 if not os.path.exists(self.extraction_dest): os.makedirs(self.extraction_dest) if not os.path.exists(self.extraction_dest + '/unchecked/'): os.makedirs(self.extraction_dest + '/unchecked/') App.log(1, "Destination folder: " + extraction_dest) self.start()
class testAcceptance(unittest.TestCase): def setUp(self): storage = Storage() users = Users() formatter = Formatter() self.sut = App(storage, users, formatter) def test_1(self): Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 5)) self.sut.post("Marcel", "Hello World!") Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 5, 5)) self.sut.post("Marcel", "How is everyone?") Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 6, 5)) lines = self.sut.get("Marcel") self.assertEquals(2, len(lines)) self.assertEquals("How is everyone? (1 minute ago)", lines[0]) self.assertEquals("Hello World! (2 minutes ago)", lines[1]) Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 6, 5)) self.sut.post("Anca", "We're doing great!") self.sut.follows("Marcel", "Anca") Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 6, 10)) lines = self.sut.wall("Marcel") self.assertEquals(3, len(lines)) self.assertEquals("Anca: We're doing great! (5 seconds ago)", lines[0]) self.assertEquals("Marcel: How is everyone? (1 minute ago)", lines[1]) self.assertEquals("Marcel: Hello World! (2 minutes ago)", lines[2])
def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] app = App() app.run()
def main(): try: import setproctitle setproctitle.setproctitle("pyTumblrDisplay") except ImportError: pass random.seed() #centers the pygame window in the middle of the monitor - HANDY :) os.environ["SDL_VIDEO_CENTERED"] = "1" #can pre-set the mixer init arguments: pre_init(frequency=0, size=0, stereo=0, buffer=0) #pygame.mixer.pre_init(44100, -16, 2, 4096) pygame.init() #pygame.mouse.set_visible(0) app = App() app_controller = AppController(app) model = BlogModel('rekall') view = BlogView(model) controller = BlogCrawlController(view) app_controller.setRoot(model, view, controller) app.app_controller = app_controller app.mainLoop()
def user(): if request.method == 'GET': users = App.getUsers() data = [] for user in users: b = {'id': user[0], 'name': user[1]} data.append(b) response = flask.jsonify(data) response.headers.add('Access-Control-Allow-Origin', '*') return response elif request.method == 'POST': hash_ = generate_password_hash(request.form['psw']) res = False try: res = App.registration(request.form['name'], hash_, request.form['login'], request.form['email']) except Exception as e: print('Exception', str(e)) if res: return jsonify({"success": True}) else: return jsonify({"success": False, "error": 'res - false'}) return jsonify({'success': False})
def main(): # Read in the data cards = pd.read_csv('data/cards.csv') heroes = pd.read_csv('data/heroes.csv') # Initialize a database manager and establish connection to the database db = HSDB() db.connect('data/hs.sqlite') # Drop all tables db.drop_table("Cards") db.drop_table("Classes") db.drop_table("Heroes") db.drop_table("minions") db.drop_table("spells") db.drop_table("weapons") db.drop_table("class_cards") db.drop_table("keywords") db.drop_table("keyword_cards") # this fn will generate and populate Heroes, Classes, Cards, and other related tables # for use from the cards/classes/heroes csv files. db.create_tables_from_data(cards, heroes) # Start the application app = App(db) app.run()
def pick_samples(self, files, cl_list, size, parent_cl=None): output_files = [] cl_list = cl_list + ([] if parent_cl is None else [parent_cl]) count = math.ceil(size / len(cl_list)) for i, cl in enumerate(cl_list): if isinstance(cl, str): try: files_cl = files[cl] except: App.log(0, "Error : The class {0} does not exist".format(cl)) else: if cl["name"] in files: output_files += self.pick_samples(files, cl["classes"], count, cl["name"]) else: output_files += self.pick_samples(files, cl["classes"], count) continue idx = np.arange(len(files_cl)) np.random.shuffle(idx) idx = idx[:count] files_list = [[cl, index] for index in idx] output_files += files_list return output_files
def delete_app_configs(self, section, key=None): """delete application configurations""" # Creates or opens a file called mydb with a SQLite3 DB dbPath = self.get_app_db_path() with sqlite3.connect(dbPath) as conn: try: conn.execute('PRAGMA foreign_keys = ON') # Get a cursor object cursor = conn.cursor() if key is not None: sql = "delete from configuration where section='{}' and key='{}'".format( section, key) else: sql = "delete from configuration where section='{}'".format( section) cursor.execute(sql) conn.commit() # Catch the exception except Exception as ex: from App import App # Roll back any change if something goes wrong conn.rollback() message = 'error occurred({}) in {}:{}'.format( ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno) App.main_wnd().addMessage.emit(MessageType.Error, message)
def test_view__all_classes(self): a = App(Login(DjangoInterface()), UserEdits(), CourseEdit()) result = a.command("LoggedInUser") # Error cases self.assertEqual("Not enrolled in any classes", result) # Success self.assertEqual("List of classes: ", result)
def check_of_received_data(): user_id = request.cookies.get('user_id') sector_id = request.form['sector_id'] if not check_cookies(): return jsonify({'error': 'in cookies'}) # if not App.auth(user_id, code): # return jsonify( {"success": False, "error": "unauthorized"} ) if sector_id_check(sector_id): if not is_user_in_any_sector(user_id): App.addUserCreaturesAmount(sector_id, user_id, 1) return jsonify({"success": True}) else: return jsonify({ "success": False, "error": "user is in some sector(not neighbor)" }) if has_user_enough_amount_in_neighbors(sector_id, user_id): App.addUserCreaturesAmount(sector_id, user_id, 1) return jsonify({"success": True}) else: return jsonify({ "success": False, "error": "not enough amount in neighbors" }) else: return jsonify({"success": False, "error": "sector is not defined"}) return jsonify({"success": False, "error": "cannot add user to sector"})
def setUp(self): root = tk.Tk() self.app = App(master=root) auto_clicker_1 = AutoClickers('Factory', 5.0, 15.0, 0) auto_clicker_2 = AutoClickers('Farm', 15.0, 45.0, 3) self.purchase_button_1 = PurchaseButton(self.app, auto_clicker_1) self.purchase_button_2 = PurchaseButton(self.app, auto_clicker_2)
def save_configs(self, configs): """save configurations""" # Creates or opens a file called mydb with a SQLite3 DB with sqlite3.connect(self.activeDrawing.path) as conn: try: conn.execute('PRAGMA foreign_keys = ON') # Get a cursor object cursor = conn.cursor() for config in configs: value = config.value if type(value) is str and "'" in value: value = value.replace("'", "''") sql = "insert or replace into configuration(Section,Key,Value) values(?,?,?)" param = (config.section, config.key, value) cursor.execute(sql, param) conn.commit() # Catch the exception except Exception as ex: from App import App # Roll back any change if something goes wrong conn.rollback() message = 'error occurred({}) in {}:{}'.format( ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno) App.main_wnd().addMessage.emit(MessageType.Error, message)
def evaluate(self, batch_x, batch_y, session, dic=None): App.log(0, "* Generation of #" +str(batch_x.shape[0])+ " embeddings for " + self.embedding_var.name) try: session.run( [self.assign.op], feed_dict={self.input: batch_x, self.dropout: 1.0}) self.build_metadatafile(batch_y, dic=dic, out_file=self.checkpoint_dir+'/metadata-'+self.embedding_var.name.replace('/','-')+'.tsv') except: App.log(0, "Embeddings computation error")
def del_stream(self, id): found = False for s in self.streams: if s.id == id: App.log(1, "Delete live stream " + str(id)) s.terminate() self.streams.remove(s)
def get_configs(self, section, key=None): """get configurations""" res = [] with sqlite3.connect(self.activeDrawing.path) as conn: try: conn.execute('PRAGMA foreign_keys = ON') # Get a cursor object cursor = conn.cursor() if key is not None: sql = "select Section, Key, Value from configuration where section=? and key=?" param = (section, key) else: sql = "select Section, Key, Value from configuration where section=?" param = (section, ) cursor.execute(sql, param) rows = cursor.fetchall() for row in rows: res.append(Config(row[0], row[1], row[2])) # Catch the exception except Exception as ex: from App import App # Roll back any change if something goes wrong conn.rollback() message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \ f"{sys.exc_info()[-1].tb_lineno}" App.main_wnd().addMessage.emit(MessageType.Error, message) return res
def push(self, device, sensor, time): devices_coll = self.site.rels['ch:devices'] found = False for dev in devices_coll.rels['items']: if dev.name == str(device): found = True break # If the device doesn t exist, we create it if found is False: App.log(1, "Create new device: " + str(device)) dev = devices_coll.create({'name': device}, auth=self.auth) found = False for sens_r in dev.rels['ch:sensors'].rels['items']: if sens_r.metric == sensor: found = True break # If the sensor doesn't exist, we create it if found is False: App.log(1, "Create new sensor: " + sensor + " on " + str(device)) sens_r = dev.rels['ch:sensors'].create( { "sensor-type": "scalar", "metric": sensor, "unit": "boolean" }, auth=self.auth) sens_r.rels['ch:dataHistory'].create( { "value": 1, "timestamp": time.replace("T", " ") }, auth=self.auth)
def record_audiofile(self, index, channel_id, length, dst='unchecked'): # Audio stream reconstruction by concatenating sample audio_file = [] overlap = self.queue_fifo[0][channel_id]["overlap"] time = self.queue_fifo[index][channel_id]["time"] detected_as = self.queue_fifo[index][channel_id]["detections"] samplerate = int(self.queue_fifo[index][channel_id]["samplerate"]) channel_name = self.queue_fifo[index][channel_id]["mapping"][ 0].replace(":", "-") a = int(length * (1 + overlap)) for i in range(index - a, index + a + 1): sample_audio = self.queue_fifo[i][channel_id]["audio"] if len(audio_file) == 0: b = len(sample_audio) else: b = int(len(sample_audio) * (1 - overlap)) audio_file.append(sample_audio[:b]) audio_file = [item for sublist in audio_file for item in sublist] self.recording_channels[channel_name] = a + 1 # Store the audio file pathlib.Path(self.extraction_dest + '/' + dst + '/').mkdir( parents=True, exist_ok=True) path = self.extraction_dest + '/' + dst + '/' + str( detected_as) + '(' + str(channel_name) + ')_' + time + '.wav' sf.write(path, audio_file, samplerate) App.log(1, "Recording " + path + " (" + str(samplerate) + " Hz) saved.")
def __init__(self, net, conf_data): classes_name = conf_data["classes_list"] nb_classes = len(classes_name) self.net = net self.sunnaries_op = [] self.class_evaluation_summaries = [] App.log(0, "Build summaries") #correct_prediction = tf.equal(tf.argmax(self.net.labels, 1), tf.argmax(self.net.out, 1)) #self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #correct_prediction = tf.equal(tf.round(self.outputs), tf.round(self.net.labels)) #true_positive = tf.multiply(tf.cast(correct_prediction , tf.float32) , self.net.labels)#tf.where(tf.cast(tf.multiply(tf.cast(correct_prediction , tf.float32) , self.net.labels) , tf.bool), tf.ones_like(self.outputs) , tf.zeros_like(self.outputs)) self.outputs = tf.placeholder_with_default(np.zeros((1, nb_classes)), shape=[None, nb_classes], name="summaries-output") self.labels = tf.placeholder_with_default(np.zeros((1, nb_classes)), shape=[None, nb_classes], name="summaries-labels") true_positive = tf.reduce_sum( tf.multiply(tf.round(self.outputs), self.labels), 0) false_positive = tf.reduce_sum( tf.multiply(tf.round(self.outputs), 1.0 - self.labels), 0) false_negative = tf.reduce_sum( tf.multiply(1.0 - tf.round(self.outputs), self.labels), 0) #self.true_positive_accuracy_by_class = tf.divide(tf.reduce_sum(tf.cast(true_positive , tf.float32) , 0) , tf.reduce_sum(self.net.labels , 0)) #self.outputs_examples = tf.random_shuffle(self.outputs)[:5,:] #self.net.labels_true = tf.reduce_min(tf.cast(correct_prediction, tf.float32), 1) #self.accuracy = tf.reduce_mean(self.net.labels_true) #correct_prediction = tf.equal(tf.argmax(self.net.labels, 1), tf.argmax(self.net.out, 1)) #self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) self.precision = true_positive / (true_positive + false_positive) self.recall = true_positive / (true_positive + false_negative) self.f1_score = 2.0 * (self.precision * self.recall) / (self.precision + self.recall) self.precisions = [self.precision[i] for i in range(nb_classes)] self.recalls = [self.recall[i] for i in range(nb_classes)] self.f1_scores = [ 2.0 * (self.precisions[i] * self.recalls[i]) / (self.precisions[i] + self.recalls[i]) for i in range(nb_classes) ] for i in range(nb_classes): tf.summary.scalar(classes_name[i].upper() + "_Precision", self.precisions[i]) tf.summary.scalar(classes_name[i].upper() + "_Recall", self.recalls[i]) tf.summary.scalar(classes_name[i].upper() + "_F1_score", self.f1_scores[i]) tf.summary.scalar('Cost', self.net.cost) tf.summary.scalar('dropout_probability', self.net.keep_prob) '''
def has_user_enough_amount_in_neighbors(sector_id, user_id): sectors = App.getSectors() adjacents = get_possible_neighbors(sector_id) for adj in adjacents: amount = App.getUserAmountInNeighbors(adj['id'], user_id) if amount and int(amount[0]) >= THRESHOLD_AMOUNT: return True return False
def connect(self, site_url, auth=None): self.site_url = site_url self.auth = auth try: self.site = chainclient.get(self.site_url) App.ok(0, "Connected to " + self.site_url) except chainclient.ChainException: App.error(0, "Unable to connect to site " + self.site_url)
def test_ViewDatabase(self): a = App(Login(DjangoInterface()), UserEdits(), CourseEdit()) result = a.command("LoggedInUser") # Error cases self.assertEqual("Illegal permissions to do this activity", result) self.assertEqual("Error while connecting to the database", result) # Success self.assertEqual("Data gathered", result)
def callback_port_connection(self, port_in, port_out, state): if state is True: App.log(2, "This link is created: " + port_in.name + " -> " + port_out.name) if "analyzer" in port_out.name: self.channels_state[port_in.name] = state else: App.log(2, "This link is broke: " + port_in.name + " -> " + port_out.name) if "analyzer" in port_in.name: self.mustReload = True
def send_email(self): a = App(Login(DjangoInterface()), UserEdits(), CourseEdit()) result = a.command("From To Subject Body User UpdatedUser") # Error cases self.assertEqual("From user does not exist", result) self.assertEqual("To user does not exist", result) self.assertEqual("Illegal email subject", result) self.assertEqual("Illegal email body", result) # Success self.assertEqual("Email successfully sent", result)
def test_send__TA_email(self): a = App(Login(DjangoInterface()), UserEdits(), CourseEdit()) result = a.command("From To Subject Body TA UpdatedUser") # Error cases self.assertEqual("Illegal permissions to do this activity", result) self.assertEqual("TA(s) do not exist", result) self.assertEqual("Illegal email subject", result) self.assertEqual("Illegal email body", result) # Success self.assertEqual("Email sent to TA(s) successfully", result)
def test(): a = App() w = Widget() w.text = 'moshe' w.font_size.final=50 a.add_widget(w) a.run()
def add_stream(self, id, samplerate): App.log(1, "New live stream " + str(id)) if len(self.streams) < self.available_ports: self.streams.append( Stream(id, samplerate, self.buffer_jack_size, self.database_path)) else: App.warning( 0, "Unable to allocate a new live stream (already full).")
def run(self): for audiofilename in self.filenames: with sf.SoundFile(audiofilename, 'r') as f: if self.channel is None: channels = range(0,f.channels) else: channels = range(self.channel,self.channel+1) sources = [] mapping = [] for ch in channels: sources.append({"name":str(ch),"starting_time":datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")}) mapping.append([str(ch), str(ch)]) while f.tell() < len(f): data = f.read(int(f.samplerate/2)) if (len(data) < int(f.samplerate/2)): break for i in channels: if f.channels > 1: fs, t, Sxx, size = database.get_spectrogram(data[:,i], f.samplerate, i, cutoff=self.cutoff) else: fs, t, Sxx, size = database.get_spectrogram(data, f.samplerate, i, cutoff=self.cutoff) if i == 0: Sxxs = Sxx fss = fs ts = t else: Sxxs = np.concatenate((Sxxs, Sxx), axis=0) fss = np.concatenate((fss, fs), axis=0) ts = np.concatenate((ts, t), axis=0) for obj in self.callable_objects: obj.execute({ "ffts":{ "data":Sxxs, "time_scale":ts, "freq_scale":fss, "size":size }, "samplerate":f.samplerate, "sources":sources, "audio":data, "overlap":self.overlap, "mapping":mapping }) f.seek(int(-int(f.samplerate/2)*self.overlap), whence=sf.SEEK_CUR) App.log(0, "End of stream ...") os._exit(0)
def run(self): while not self.stopFlag.wait(0.1): msg = self.sio_redis.get_message() if msg: try: if msg['type']=="message": data = pickle.loads(msg["data"]) if data.get('method')=="emit" and data.get('event') == "JackSource": self.count_run = 0 except Exception as e: App.error(0, "Redis message" + str(e) + "------\n" + str(data))
def main(): # Command line arguments if len(sys.argv) != 3 or (sys.argv[2] != "gui" and sys.argv[2] != "console"): print("usage: " + sys.argv[0] + " <input sudoku filename> <gui/console>") return sudoku_file = sys.argv[1] gui_active = (sys.argv[2] == "gui") app = App(gui_active, sudoku_file) app.run()
def callback_port_connection(self, port_in, port_out, state): if state is True: App.log( 2, "This link is created: " + port_in.name + " -> " + port_out.name + " " + str(state)) else: App.log( 2, "This link has been destroyed: " + port_in.name + " -> " + port_out.name + " " + str(state)) if "analyzer" not in port_out.name: self.port_connect_streamer(port_out)
def test_update_time(): app = App(fake_server) app.logic.spawn_system.create_player(0) for i in range(15): app.logic.spawn_system.create_enemy() start = time.time() for i in range(100): app.update() delta = time.time() - start assert delta / 100 < 0.005
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.name = "Learn" self.button = wx.Button(self.tabPageApps, label="Learn", pos=(10*self.Grid,4*self.Grid), size=(8*self.Grid,2*self.Grid)) self.appClock = AppClock(WuwPanel) self.appPhoto = AppPhoto(WuwPanel) self.graphics() self.after_init()
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.timeUpdating = [] self.name = "clock" self.button = wx.Button(self.tabPageApps,label="Clock",pos=(1*self.Grid,1*self.Grid), size=(8*self.Grid,2*self.Grid)) self.graphics() self.clock.Hide() self.after_init()
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.trying=[] self.name = "Weather" self.button = wx.Button(self.tabPageApps,label="Wheather",pos=(1*self.Grid,7*self.Grid), size=(8*self.Grid,2*self.Grid)) self.button.Bind(wx.EVT_BUTTON, self.Weather) self.after_init()
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.name = "photo" self.button = wx.Button(self.tabPageApps,label="Photo",pos=(1*self.Grid,4*self.Grid), size=(8*self.Grid,2*self.Grid)) self.box = wx.StaticBitmap(self.wuw, wx.ID_ANY, pos=(18*self.Grid,16*self.Grid), size=(64*self.Grid,48*self.Grid)) self.box.Hide() self.box.Bind(wx.EVT_PAINT, self.draw_photo) self.after_init()
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.name = "rally" self.ResetEnvironmentOnStart = False self.ResetEnvironmentOnEnd = False self._Rally = False self.button = wx.Button(self.tabPageApps,label="Rally",pos=(1*self.Grid,13*self.Grid), size=(8*self.Grid,2*self.Grid)) self.box = wx.StaticBox(self.wuw,pos=(0*self.Grid,16*self.Grid), size=(35*self.Grid,38*self.Grid)) self.BoxRally = self.box self.box.Hide() self.after_init()
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.name = "book" self.ResetEnvironmentOnStart = False self.ResetEnvironmentOnEnd = False self.button = wx.Button(self.tabPageApps,label="Book",pos=(10*self.Grid,1*self.Grid), size=(8*self.Grid,2*self.Grid)) self.actions = {"pdf_left_move":self.leftMove, "pdf_right_move":self.rightMove } self.after_init()
def __init__(self,testCfg,appCfgOpt): self.myAppCfg = appConfig(appCfgOpt) self.appCfgOpt = appCfgOpt self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) self.testCfg = testCfg self.testApp = App(self.myAppCfg,self.testCfg) self.testApp.genCMDParam()
def __init__(self, WuwPanel): App.__init__(self, WuwPanel) self.trying = [] self.getChange = [] self.name = "stock" self.button = wx.Button(self.tabPageApps,label="Stock",pos=(1*self.Grid,10*self.Grid), size=(8*self.Grid,2*self.Grid)) self.box = wx.StaticBox(self.wuw,pos=(5*self.Grid,25*self.Grid), size=(90*self.Grid,50*self.Grid)) self.box.threadTime=None self.box.Hide() self.box.Bind(wx.EVT_PAINT, self.show_stock) self.after_init()
def runApp(sandBox=True, cert_file='', key_file='', driver='mysql', queue_host='', queue_port=3306, queue_db_name='', queue_username='', queue_password='', Q_name='', app_name='', is_debug=True, feedback_callback=''): """ 实例化App Class,仅需要调用 runApp() 方法 """ apns_process = App(sandBox=sandBox, cert_file=cert_file, key_file=key_file,driver=driver, Q_host=queue_host, Q_port=queue_port, Q_db=queue_db_name, Q_user=queue_username, Q_pass=queue_password, Q_name =Q_name, app_name=app_name, is_debug=is_debug, feedback_callback=feedback_callback) if apns_process: apns_process.run() else: sys.stderr.writelines( ('%s : App run failed with parameters : sandBox=%s, cert_file=%s, key_file=%s, queue_host=%s,' + 'queue_port=%s, queue_db_name=%s, queue_username=%s, queue_password=%s,Q_name=%s, app_name=%s,'+ 'is_debug=%s, feedback_callback=%s') % (time.asctime(), str(sandBox), cert_file, key_file, queue_host, queue_port, queue_db_name, queue_username, queue_password, Q_name, app_name, str(is_debug), feedback_callback)) return 0
def __init__(self): self.Interstitial = App.getInstance() self.unit_test_folder = self.Interstitial.Configuration.getUnit_test_folder() self.fixtures_folder = self.Interstitial.Configuration.getFixturesFolder() self.project_name = 'New_Project' self.test_folder_one = self.fixtures_folder + 'DAW' + os.sep self.test_folder_two = self.fixtures_folder + 'Reference' + os.sep pass
def parseSearchPage(page): #we need to parse the resulting page to get the app we are looking for document = BeautifulSoup(page.text) cards = document.findAll(attrs={"class": "card"}) #we are looking for div with class set to 'card' if len(cards) > 0: #we need to get info on the first card/app we find card = cards[0] app = App() #let's do some html/css parsing app.name = card.find(attrs={"class": "title"}).get("title") logger.debug("Got the App's name") app.link = "https://play.google.com" + card.find(attrs={"class": "title"}).get("href") logger.debug("Got the App's link") price = card.find(attrs={"class": "display-price"}) if price is None: app.free = True else: app.free = None logger.debug("Got the App's price") app.rating = card.find(attrs={"class": "current-rating"})["style"].strip().replace("width: ","").replace("%","")[:3].replace(".","") #we get the rating, reading it from the style attribute logger.debug("Got the App's rating") #we also download the page of the app to check for IAP and more logger.debug("Downlaoding the App's page") app_page = requests.get(app.link) logger.debug("Analyzing the App's page") app_document = BeautifulSoup(app_page.text) iap_element = app_document.findAll(attrs={"class": "inapp-msg"}) if len(iap_element) > 0: app.IAP = True else: app.IAP = False logger.debug("Got the App's IAP status") return app else: return None
def routing(self): routes = App.routing(self) return routes
def main(): app = App(root=PrototypeController(),dim=(800,600)) app.start()
# locales: localeDir = "%s%slocale" % (daboDir, os.sep) #locales = [("dabo.locale", (os.path.join(daboDir, "locale", "dabo.pot"),))] locales = [] def getLocales(arg, dirname, fnames): if ".svn" not in dirname and dirname[-1] != "\\": #po_files = tuple(glob.glob(os.path.join(dirname, "*.po"))) mo_files = tuple(glob.glob(os.path.join(dirname, "*.mo"))) if mo_files: subdir = os.path.join("dabo.locale", dirname[len(arg)+1:]) locales.append((subdir, mo_files)) os.path.walk(localeDir, getLocales, localeDir) # The applications App object contains all the meta info: app = App(MainFormClass=None) _appName = app.getAppInfo("appName") _appShortName = app.getAppInfo("appShortName") _appVersion = app.getAppInfo("appVersion") _appDescription = app.getAppInfo("appDescription") _copyright = app.getAppInfo("copyright") _authorName = app.getAppInfo("authorName") _authorEmail = app.getAppInfo("authorEmail") _authorURL = app.getAppInfo("authorURL") _authorPhone = app.getAppInfo("authorPhone") _appComments = ("This is custom software by %s.\r\n" "\r\n" "%s\r\n"
class testApp(unittest.TestCase): def setUp(self): self.storage = Storage() self.users = Users() self.sut = App(self.storage, self.users, Formatter()) def test_post_stores_message(self): self.storage.add = mock.MagicMock() Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 5)) self.sut.post("Marcel", "abcd") message = Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 5)) self.storage.add.assert_called_once_with(message) def test_get_returns_message(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 5)) ] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 8)) lines = self.sut.get("Marcel") self.assertEquals(1, len(lines)) self.assertEquals("abcd (3 seconds ago)", lines[0]) def test_get_returns_messages_in_reverse_order(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 0)), Message("Marcel", "efgh", datetime.datetime(2000, 1, 2, 3, 4, 2)) ] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 3)) lines = self.sut.get("Marcel") self.assertEquals(2, len(lines)) self.assertEquals("efgh (1 second ago)", lines[0]) self.assertEquals("abcd (3 seconds ago)", lines[1]) def test_get_only_returns_messages_from_given_user(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 0)), Message("Gigi", "efgh", datetime.datetime(2000, 1, 2, 3, 4, 2)) ] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 5)) lines = self.sut.get("Marcel") self.assertEquals(1, len(lines)) self.assertEquals("abcd (5 seconds ago)", lines[0]) def test_follows_adds_to_list_of_followed_users(self): self.users.add = mock.MagicMock() self.sut.follows("Marcel", "Gigi") self.users.add.assert_called_once_with("Marcel", "Gigi") def test_wall_returns_message(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 5)) ] self.users.get = mock.MagicMock() self.users.get.return_value = [] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 8)) lines = self.sut.wall("Marcel") self.assertEquals(1, len(lines)) self.assertEquals("Marcel: abcd (3 seconds ago)", lines[0]) def test_wall_returns_messages_in_reverse_order(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 0)), Message("Marcel", "efgh", datetime.datetime(2000, 1, 2, 3, 4, 2)) ] self.users.get = mock.MagicMock() self.users.get.return_value = [] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 3)) lines = self.sut.wall("Marcel") self.assertEquals(2, len(lines)) self.assertEquals("Marcel: efgh (1 second ago)", lines[0]) self.assertEquals("Marcel: abcd (3 seconds ago)", lines[1]) def test_wall_returns_messages_for_given_user_and_followed_ones(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 0)), Message("Gigi", "efgh", datetime.datetime(2000, 1, 2, 3, 4, 2)) ] self.users.get = mock.MagicMock() self.users.get.return_value = ["Gigi"] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 3)) lines = self.sut.wall("Marcel") self.assertEquals(2, len(lines)) self.assertEquals("Gigi: efgh (1 second ago)", lines[0]) self.assertEquals("Marcel: abcd (3 seconds ago)", lines[1]) def test_wall_ignores_users_other_than_given_or_followed(self): self.storage.get = mock.MagicMock() self.storage.get.return_value = [ Message("Marcel", "abcd", datetime.datetime(2000, 1, 2, 3, 4, 0)), Message("Gigi", "efgh", datetime.datetime(2000, 1, 2, 3, 4, 2)), Message("Other", "stuff", datetime.datetime(2000, 1, 2, 3, 4, 3)) ] self.users.get = mock.MagicMock() self.users.get.return_value = ["Gigi"] Clock.now = staticmethod(lambda: datetime.datetime(2000, 1, 2, 3, 4, 3)) lines = self.sut.wall("Marcel") self.assertEquals(2, len(lines)) self.assertEquals("Gigi: efgh (1 second ago)", lines[0]) self.assertEquals("Marcel: abcd (3 seconds ago)", lines[1])
config = context.config fileConfig(config.config_file_name) logger = logging.getLogger("alembic.env") db_names = config.get_main_option("databases") import site import os.path parent_dir = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] site.addsitedir(parent_dir) from App import core, App # app must be instantiated in order to get correct metadata App.create_app() target_metadata = {"production": core.db.metadata, "testing": core.db.metadata} def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """
counter += 1 if counter > nb+10: break # FIXME: a quick hack to avoid looping for a long time return list(combs) # ================================================================= if __name__ == "__main__": warnings.simplefilter(action = "ignore", category = FutureWarning) random.seed(1234) # ----------------------------- dbfiles = [gb.DATA_PATH + gb.VEHICLE + "_" + sig_id + ".db" for sig_id in gb.SIG_IDS] sigReaders = [ SignalReader(dbfile, preprocess=False) for dbfile in dbfiles ] # ----------------------------- app = App(sigReaders) DATA, AXES_INFO = app.build_features_data() # features_combinations = getCombinations( range(len(DATA[0])), nb=20, length=2 ) features_combinations = range(2, len(DATA[0])) combos=[]; qualitiesFSP=[]; qualitiesSSP=[] for id_combin, n_features in enumerate( features_combinations ): clust = Clustering(DATA, scale=True, features=None).gmm(k=gb.K) # kmeans, dpgmm # clust = Clustering(DATA, scale=True, features=n_features).gmm(k=gb.K) app.init_clust_tracker(clust, AXES_INFO) PLOT_PATH = gb.PLOT_PATH + str(id_combin) + '/' if not os.path.exists(PLOT_PATH): os.makedirs(PLOT_PATH)
def __init__(self): SharedApp.SharedApp.App = App.getInstance() pass
def main(): mainApp = App() mainApp.mainloop()
if sys.platform == "darwin": dabo.MDI = True # hack for locale error on OSX # import locale # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') import db import biz import ui import reports # included for PyInstaller #import wx.gizmos, wx.lib.calendar from App import App app = App(SourceURL=remotehost) app.db = db app.biz = biz app.ui = ui app.reports = reports # Make it easy to find any images or other files you put in the resources # directory. sys.path.append(os.path.join(app.HomeDirectory, "resources")) app.setup() app.MainFormClass = app.ui.FrmMain app.PreferenceManager.setValue("fontsize", 11) app.NoneDisplay = "" # Set up a global connection to the database that all bizobjs will share: app.dbConnection = app.getConnectionByName("WBSRemoteUser")
def main(): app = App("/wiki/China") app.run()
import sys import os import dabo # The loading of the UI needs to happen before the importing of the # db, biz, and ui packages: dabo.ui.loadUI("wx") if sys.platform[:3] == "win": dabo.MDI = True import db import biz import ui from App import App app = App(SourceURL=remotehost) app.db = db app.biz = biz app.ui = ui # Make it easy to find any images or other files you put in the resources # directory. sys.path.append(os.path.join(app.HomeDirectory, "resources")) # Set the BasePrefKey for the app app.BasePrefKey = "librarymanager" app.setup() # Set up a global connection to the database that all bizobjs will share: app.dbConnection = app.getConnectionByName("library")
from PyQt4.QtCore import * from PyQt4.QtGui import * import sys from App import App from Login import Login from Settings import Settings if __name__ == '__main__': app = QApplication(sys.argv) login = Login() settings = Settings() app_logic = App(login, settings) app_logic.run() app.exec_()
if sys.platform == "darwin": dabo.MDI = True # hack for locale error on OSX # import locale # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') import db import biz import ui import reports import sys # included for PyInstaller #import wx.gizmos, wx.lib.calendar from App import App app = App(SourceURL=remotehost) app.db = db app.biz = biz app.ui = ui app.reports = reports # Make it easy to find any images or other files you put in the resources # directory. sys.path.append(os.path.join(app.HomeDirectory, "resources")) app.setup() #app.PreferenceManager.setValue("basedir", None) app.BaseDir = app.PreferenceManager.getValue("basedir") print "basedir = " + str(app.BaseDir) if app.BaseDir == None or app.BaseDir == '':
def setUp(self): self.storage = Storage() self.users = Users() self.sut = App(self.storage, self.users, Formatter())
def __init__(self): App.__init__(self, "FoxDot - Live Coding with Python and SuperCollider") print "Welcome to FoxDot!"
#!/usr/bin/python #-*- coding: utf-8 -*- """ <title>: <description> Authors = Rafael Treviño <*****@*****.**> Date = """ # Imports externals # Imports internals from App import App # Main entry point if __name__ == '__main__': app = App('') # Exmaple of custom parameters # app.add_option('-c', dest='custom', # help='custom parameter', # default='') (params, args) = app.parse_args() # ...