def load_testentries(): """load test entries into database.""" print("test entries") Entry.query.delete() test_entry1 = Entry(user_id=1, date="31-Oct-2015", text_content="this is my test dream entry", title="title", hours_slept=8, mood_awake=1, clarity=1, lucidity=1, lucid_intent=1) test_entry2 = Entry(user_id=1, date="1-Nov-2015", text_content="this is my second test dream entry", title="title", hours_slept=8, mood_awake=1, clarity=1, lucidity=1, lucid_intent=1) db.session.add(test_entry1) db.session.add(test_entry2) db.session.commit()
def test_none_mark_to_string(self): entry_lj = Entry(mde=self.mde_longjump, athlete=self.athlete) db.session.add(entry_lj) db.session.commit() # No mark has been set self.assertEqual(entry_lj.mark_to_string(), "") entry_1600m = Entry(mde=self.mde_1600m, athlete=self.athlete) db.session.add(entry_1600m) db.session.commit() self.assertEqual(entry_1600m.mark_to_string(), "")
def example_data(): Entry.query.delete() Todo.query.delete() User.query.delete() #users brighticorn = User( name='Brighticorn', user_id=1, email='*****@*****.**', password= '******', zipcode='94566') pairprogrammer = User( name='PairProgrammer', user_id=2, email='*****@*****.**', password= '******', zipcode='94588') #entries be1 = Entry(user_id=1, date='2018-10-3', title='Entry Title', text='Entry body text', quote='Some random quote for the day', weather='Sunny') be2 = Entry(user_id=1, date='2018-10-4', title='Another Title', text='Some text to go in entry body', quote='another quote', weather='Cloudy') pe1 = Entry(user_id=2, date='2018-10-3', title='Testing same date', text='Enrty body for testing same date', quote='some quote', weather='Snowy') pe2 = Entry(user_id=2, date='2018-10-16', title='Test Title', text='Some text for an entry body', quote='daily quote', weather='Sunny') #todo bt1 = Todo(user_id=1, todo_id=1, todo='wash dishes') bt2 = Todo(user_id=1, todo_id=2, todo='laundry') pt1 = Todo(user_id=2, todo_id=3, todo='sweep/mop') db.session.add_all( [brighticorn, pairprogrammer, be1, be2, pe1, pe2, bt1, bt2, pt1]) db.session.commit()
def add_entry() -> str: #バリデーションクラス vld = validation.Validation() none_validate = { 'practice_id': 'No practice_id', 'member_id': 'No member_id' } messages = vld.check_json(none_validate, 'null_check') if not messages == []: return ','.join(messages) numeric_validate = { 'practice_id': 'practice_id is not numeric', 'member_id': 'member_id is not numeric' } messages = vld.check_json(numeric_validate, 'numeric_check') if not messages == []: return ','.join(messages) entry = Entry(request.json['practice_id'], request.json['member_id']) db.session.add(entry) db.session.commit() return "Success"
def get_entries_by_search_term(search_term): with sqlite3.connect("./dailyjournal.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute( """ SELECT e.id, e.entry, e.concept, e.date, e.moodId, m.mood FROM Entries e Join Moods m on m.id = e.moodId WHERE e.entry Like ? """, ("%" + search_term + "%"), ) entries = [] dataset = db_cursor.fetchall() for row in dataset: entry = Entry(row['id'], row['concept'], row['date'], row['moodId'], row['moodId']) mood = Mood(row['moodId'], row['mood']) entry.mood = mood.__dict__ entries.append(entry.__dict__) return json.dumps(entries)
def add_entry(trip_id): """This is where the user can add an entry to their trip.""" user_id = session["user_id"] if request.method == "POST": title = request.form["title"] text = request.form["entry"] all_numbers = datetime.now().timestamp() time_stamp = time.ctime(all_numbers) image_url = None if request.files: upload = request.files["file"] uploaded_file_info = cloudinary.uploader.upload(upload) image_url = uploaded_file_info['secure_url'] entry = Entry(title=title, entry=text, user_id=user_id, trip_id=trip_id, time_stamp=time_stamp, user_picture=image_url) db.session.add(entry) db.session.commit() return redirect(f"/user_journal/{user_id}") else: return render_template("create_entry.html", trip_id=trip_id, user_id=user_id)
def get_single_entry(id): with sqlite3.connect("./dailyjournal.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Use a ? parameter to inject a variable's value # into the SQL statement. db_cursor.execute( """ SELECT e.id, e.concept, e.entry, e.date, e.mood_id FROM Entries e WHERE e.id = ? """, (id, )) data = db_cursor.fetchone() # Create an animal instance from the current row entry = Entry(data['id'], data['concept'], data['entry'], data['date'], data['mood_id']) return json.dumps(entry.__dict__)
def test_set_mark_with_no_mark_string_field_event(self): entry_lj = Entry(mde=self.mde_longjump, athlete=self.athlete) db.session.add(entry_lj) db.session.commit() entry_lj.set_mark() self.assertEqual(entry_lj.mark, 0) self.assertEqual(entry_lj.mark_type, "inches") self.assertEqual(entry_lj.mark_to_string(), "")
def create_entry(entry_list, roaster, score, note): entry = Entry(entry_list=entry_list, roaster=roaster, score=score, note=note) db.session.add(entry) db.session.commit() return entry
def create_entry(user, blog, city, title): entry = Entry(user=user, blog=blog, city=city, title=title) db.session.add(entry) db.session.commit() return entry
def create_entry(request): title = "\'" + request.json["title"] + "\'" text = "\'" + request.json["text"] + "\'" entry = Entry(title=title, text=text, created_at=datetime.datetime.now()) entry.save() return json.dumps(entry.id)
def save_entry(text): """Create an Entry""" entry = Entry(text=text) db.session.add(entry) db.session.commit() return entry
def test_set_mark_with_no_mark_string_track_event(self): entry_1600m = Entry(mde=self.mde_1600m, athlete=self.athlete) db.session.add(entry_1600m) db.session.commit() entry_1600m.set_mark() # Test when no mark is provided for the event self.assertEqual(entry_1600m.mark, INFINITY_SECONDS) self.assertEqual(entry_1600m.mark_type, "seconds") self.assertEqual(entry_1600m.mark_to_string(), "")
def update(self, silent=False, feed=None): request = self.db_session.query(Feed) if feed is not None: request = request.filter(Feed.name == feed) result = request.all() for feed in result: if feed.twitter: api = twitter.Api() twits = api.GetUserTimeline(feed.name) for twit in twits: # we discard answers to other twits if not twit.in_reply_to_user_id: txt = twit.GetText() id = "%s_%s" % (feed.name, twit.GetId()) e = Entry(id, "", txt, "") self.db_session.add(e) feed.entries.append(e) try: self.db_session.commit() if not silent: msg = "[twitter: %s] %s" % (feed.name, txt) self.bot.say(msg) except (FlushError, IntegrityError): self.db_session.rollback() else: parsed = feedparser.parse(feed.url) for entry in parsed.entries: id = "%s_%s" % (feed.name, get_id(entry)) t = get_time(entry) e = Entry(id, entry.link, t, entry.title) self.db_session.add(e) feed.entries.append(e) try: self.db_session.commit() if not silent: msg = "[%s] %s : %s" % (feed.name, entry.title, entry.link) self.bot.say(msg) except (FlushError, IntegrityError): self.db_session.rollback()
def add_entry(self, eid, url, date, title, feed): f = self.db_session.query(Feed).filter(Feed.name == feed).all() if f == []: raise else: feed = f[0] e = Entry(eid, url, date, title) self.db_session.add(e) feed.entries.append(e) self.db_session.add(feed) self.db_session.commit()
def add_entry(): if not session.get('logged_in'): abort(401) form = request.form sys, dia, pulse = form['systolic'], form['diatolic'], form['pulse'] when, side = form['time'], form['side'] entry = Entry(sys, dia, pulse, side, when) db_session.add(entry) db_session.commit() flash("Succesful posted") return redirect(url_for('show_entries'))
def get(self): '''i=0 n = self.request.get('n') if not n: n='1' csvfile='data/data'+n+'.csv' self.response.headers['Content-Type'] = 'text/html' csvreader = csv.reader(file(os.path.join(os.path.dirname(__file__),csvfile))) for line in csvreader: e = Entry() e.title = line[0].decode('utf-8') e.url = line[1].decode('utf-8') e.content = line[2].decode('utf-8') e.private = False tag_name=line[3].decode('utf-8') t_q = Tag.all() t_q = t_q.filter('name =',tag_name) if(t_q.count(1)>0): t = t_q.get() t.count_link+=1 t.usetime=datetime.datetime.now() t.put() else: t = Tag() t.name = tag_name t.count_link=1 t.usetime=datetime.datetime.now() t.put() e.tags.append(db.Category(tag_name)) e.put() i +=1 self.response.out.write('%d ' % i) self.response.out.write('%s ' % e.key()) self.response.out.write('%s <br />' % line[0]) ''' n = self.request.get('n') if not n: n = 0 else: n = int(n) for i in range(1, 1000): e = Entry() e.title = str(i + n * 999) e.pageid = n e.put() self.response.out.write('%d ' % i) self.response.out.write('%s <br />' % e.key())
def _generate_entries(feeds): from model import database as db, Entry if not feeds: return [] entries = [ Entry(url='http://test.example.com/entry/{0}'.format(i), title='entry title {0}'.format(i), is_read=random.choice([True, False]), feed=random.choice(feeds)) for i in range(random.randint(0, 1000)) ] with db.transaction(): for e in entries: e.save() return entries
def worker(event, context): """Handler for processing batch event to database ingestion""" if event.get("source") in ["aws.events", "serverless-plugin-warmup"]: return {} for record in event['Records']: timestamp = float(record['attributes']['SentTimestamp']) / 1000 body = record['body'] hash_key = record['md5OfBody'] entry = Entry(created_at=datetime.fromtimestamp(timestamp), content=body, hash_key=hash_key) db.session.add(entry) else: db.session.commit() return None
def load_entries(): """Load entries from entries.item into database.""" print("Entires") for row in open("seed_data/entries.item"): row = row.rstrip() date, user_id, title, text, quote, weather = row.split("|") entry = Entry(date = date, user_id = user_id, title = title, text = text, quote = quote, weather = weather) db.session.add(entry) db.session.commit()
def get_all_entries(): # Open a connection to the database with sqlite3.connect("./dailyjournal.db") as conn: # Just use these. It's a Black Box. conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute(""" SELECT e.id, e.concept, e.entry, e.date, e.mood_id, m.label, m.id FROM Entries e JOIN Moods m on m.id = e.mood_id """) # Initialize an empty list to hold all animal representations entries = [] # Convert rows of data into a Python list dataset = db_cursor.fetchall() # Iterate list of data returned from database for row in dataset: # Create an animal instance from the current row. # Note that the database fields are specified in # exact order of the parameters defined in the # Animal class above. entry = Entry(row['id'], row['concept'], row['entry'], row['date'], row['mood_id']) mood = Mood(row['id'], row['label']) entry.mood = mood.__dict__ entries.append(entry.__dict__) # Use `json` package to properly serialize list as JSON return json.dumps(entries)
def parse_genome(genome_path): chrs = [] #lengths = [] names = set() with open(genome_path) as f: for line in f: line = line.strip().split() if len(line) == 1: chrs.append([]) #lengths.append(0) else: e= Entry(line[1],line[5],int(line[7]),int(line[9]),int(line[9])-int(line[7])) e.set_block_id(int(line[3])) chrs[-1].append(e) #lengths[-1] += e.length names.add(e.seq_id.split('.')[1]) return chrs
def messages_controller(request): if request.REQUEST_METHOD == 'POST': name = get_first_element(request.POST, 'name', '') message = get_first_element(request.POST, 'message', '') entry = Entry(name, message) manager.save(entry) response = Response('303 See Other', b'303 See Other') response.headers.append(('Location', '/messages')) return response entries = manager.get_all() entries_encoded = b'<hr />'.join( e.name.encode('utf-8') + b': ' + e.message.encode('utf-8') for e in entries) body = messages_view.render(messages=entries_encoded) return Response('200 OK', body)
def preprocess(self, pattern_type, filename): frame = cv2.imread(filename) size = 500 frame = self.resize(frame, size + 100) # 100px padding for cropping frame = self.square_crop(frame, size) # edge detection sobels = self.sobel(frame) sobel_sums = self.reduce(sobels) # remove outliers 95% percentile # figure out how to remove outliers without screwing up the image -- removed for now # outliers = percentile_based_outlier(sobel_sums.x, 95) # sobel_sums.x = [v for k, v in enumerate(sobel_sums.x) if outliers[k] == 0] # outliers = percentile_based_outlier(sobel_sums.y, 95) # sobel_sums.y = [v for k, v in enumerate(sobel_sums.y) if outliers[k] == 0] # prepare for NN entry = Entry(pattern_type, sobels, sobel_sums) # output # plt.subplot(3, 2, 1), plt.imshow(frame, cmap="gray") # plt.title('Original'), plt.xticks([]), plt.yticks([]) # color = ('b', 'g', 'r') # for i, col in enumerate(color): # histr = cv2.calcHist([frame], [i], None, [256], [0, 256]) # plt.subplot(3, 2, 2), plt.plot(histr, color=col) # plt.title('Histo'), plt.xticks([0, 256]), plt.yticks([]), plt.yscale('log') # plt.subplot(3, 2, 3), plt.imshow(sobels.x, cmap='gray') # plt.title('Sobel X'), plt.xticks([]), plt.yticks([]) # plt.subplot(3, 2, 4), plt.imshow(sobels.y, cmap='gray') # plt.title('Sobel Y'), plt.xticks([]), plt.yticks([]) # plt.subplot(3, 2, 5), plt.plot(sobel_sums.x) # plt.title('Sum X'), plt.xticks([0, 500]), plt.yticks([0, max(sobel_sums.x)]) # plt.subplot(3, 2, 6), plt.plot(sobel_sums.y) # plt.title('Sum Y'), plt.xticks([0, 500]), plt.yticks([0, max(sobel_sums.y)]) # plt.show() return entry
def create_entry(itinerary_id, name, description, url, image, comment, location, trip_day, complete=False): """Create and return a new entry""" new_entry = Entry( name=name, description=description, url=url, image=image, comment=comment, location=location, trip_day=trip_day, itinerary_id=itinerary_id, complete=complete ) db.session.add(new_entry) db.session.commit() return new_entry
def post(self): json_data = request.get_json(force=True) if not json_data: return {'message': 'No input data provided'}, 400 # Validate and deserialize input data, errors = entry_schema.load(json_data) if errors: print('errors:', errors) return errors, 422 entry = Entry(title=json_data['title'], body=json_data['body'], posted_by=json_data['posted_by']) db.session.add(entry) db.session.commit() result = entry_schema.dump(entry).data return {"status": 'success', 'data': result}, 201
def submit_form(): """Save entry into database""" today = datetime.date.today() finduser = User.query.filter_by(email=session["email"]).first() title = request.form.get("title") text = request.form.get("text") weather = request.form.get("weather") quote = request.form.get("quote") new_entry = Entry(weather=weather, quote=quote, title=title, text=text, date=today, user_id=finduser.user_id) db.session.add(new_entry) db.session.commit() results = {"title": title, "text": text} return jsonify(results)
def make_entry(command, description): arguments = [] add_arg = click.confirm('add argument and description?') while add_arg: arg = click.prompt('give argument') desc = click.prompt('give description') arguments.append(Argument(arg, desc)) add_arg = click.confirm('add another argument and description?') examples = [] add_ex = click.confirm('add example and description?') while add_ex: ex = click.prompt('give example') desc = click.prompt('give description') examples.append(Example(ex, desc)) add_ex = click.confirm('add another example and description?') entry = Entry(command, description, arguments=arguments, examples=examples) return entry
def add_entry_to_db(): """Save and redirect journal entries.""" try: title = request.form["title"] print "\n\n\n\n title", title body = request.form["journalBody"] print "\n\n\n\n\n journal body", body tags = request.form.getlist('prof1') print "\n\n\n\n tags", tags user_id = session['user_id'] print "\n\n\n\n user_id", user_id entry = Entry(entry_body=body, entry_title=title, user_id=user_id) # Need to consider entry_date # entry_id = Entry(body=entry_body, entry_date=entry_date, username=username, tag=tag) db.session.add(entry) db.session.commit() user_entries = Entry.query.filter(Entry.user_id == user_id).all() quote, quote_author = get_quotes_for_footer() return render_template("view_entries.html", user_entries=user_entries, title=title, body=body, quote=quote, quote_author=quote_author) except: quote, quote_author = get_quotes_for_footer() return render_template("error.html", quote=quote, quote_author=quote_author)
def add_word(group, w_data): print(w_data['lexicalEntries'][0]['pronunciations'][0]['audioFile']) group_letter = group word = w_data['word'] audio = w_data['lexicalEntries'][0]['pronunciations'][0]['audioFile'] ipa_spelling = w_data['lexicalEntries'][0]['pronunciations'][0][ 'phoneticSpelling'] group = None try: group = session.query(Group).filter_by(letter=group_letter).one() except Exception: print('Go on and add new Group') if not group: group = Group(letter=group_letter) session.add(group) session.flush() session.add( Entry(word=word, audio=audio, ipa_spelling=ipa_spelling, group_id=group.id)) session.commit() session.close()