async def get_story(name): sheet = service.spreadsheets() story_result = sheet.values().get( spreadsheetId=StoriesID, range='{}!A2:C1000'.format(name)).execute() story_result = story_result.get('values', []) story = Story(name) story.load_story(story_result) return story
def insert(self, actor): # Normally you would use notify_player_arrived() to trigger an action. # but for the game ending, we require an immediate response. # So instead we hook into the direct arrival of something in this location. super(GameEnd, self).insert() try: Story.completion_failed1() # player arrived! Great Success! except AttributeError: pass
def story(): story = Story( KEYS, """Once upon a time in a long-ago {place}, there lived a large {adjective} {noun}. It loved to {verb} {plural_noun}.""") answers = {} for key in KEYS: answers[key] = request.form[key] story = story.generate(answers) return render_template("story.html", story=story)
def start_the_story(self): while self.currentScene != -1: if self.currentScene == 0: self.currentScene = Story.introduction() elif self.currentScene == 100: self.currentScene = Story.pathone() #elif self.currentScene == 200: #elif self.currentScene == 0: elif self.currentScene == 9998: Story.exit()
def __init__(self, server_ip, dialogflow_key_file, dialogflow_agent_id): """ :param server_ip: IP address of Social Interaction Cloud server :param dialogflow_key_file: path to Google's Dialogflow key file (JSON) :param dialogflow_agent_id: ID number of Dialogflow agent to be used (project ID) """ self.sic = BasicSICConnector( server_ip, 'en-US', dialogflow_key_file, dialogflow_agent_id) self.conversation = Conversation(self.sic, robot_present=True, animation=True) self.story = Story(interactive=True)
def __init__(self): self.story = Story() # 初始的句子向量 self.vocab = self.story.vocab self.batch_size = self.story.batch_size - 2 #126 self.chunk_size = self.story.chunk_size self.embedding_dim = 300 self.num_units = 500 self.learning_rate = 0.001 self.epoch = 25 self.sample_size = 50
def main(): if len(argv) != 3: exit("Not enough arguments.") story_file = argv[1] property_file = argv[2] game = Story(property_file) game.Load_Story(story_file) Play(game) return
def do_it(self, sources): for source in sources: words = nltk.wordpunct_tokenize(source.headline) words.extend(nltk.wordpunct_tokenize(source.summary)) lowerwords=[x.lower() for x in words if len(x) > 1] self.ct += 1 print self.ct, "TITLE",source.headline self.corpus.append(lowerwords) self.titles.append(source.headline) self.links.append(source.url) [[self.key_word_list.add(x) for x in self.top_keywords(self.nkeywords,doc,self.corpus)] for doc in self.corpus] self.ct=-1 for doc in self.corpus: self.ct+=1 print self.ct,"KEYWORDS"," ".join(self.top_keywords(self.nkeywords,doc,self.corpus)) for document in self.corpus: vec=[] [vec.append(self.tfidf(word, document, self.corpus) if word in document else 0) for word in self.key_word_list] self.feature_vectors.append(vec) self.n=len(self.corpus) mat = numpy.empty((self.n, self.n)) for i in xrange(0,self.n): for j in xrange(0,self.n): mat[i][j] = nltk.cluster.util.cosine_distance(self.feature_vectors[i],self.feature_vectors[j]) Z = linkage(mat, 'single') dendrogram(Z, color_threshold=self.t) clusters = self.extract_clusters(Z,self.t,self.n) stories = [] for key in clusters: print "=============================================" story = Story() for id in clusters[key]: story.add_source(sources[id]) print id,self.titles[id],sources[id].url stories.append(story) return stories
def save_story(): if request.method == 'POST': story_title = request.form['story_title'] user_story = request.form['user_story'] acceptance_criteria = request.form['acceptance_criteria'] business_value = request.form['business_value'] estimation_hour = request.form['estimation_hour'] status = request.form['status'] story = Story(title=story_title, description=user_story, acceptance_criteria=acceptance_criteria, business_value=business_value, estimation_hour=estimation_hour, status=status) story.save() return redirect("/list")
def write_acknowledgement_page(self, title: str, acknowledgement: str, page: str, user_id: str): story = Story(user_id) story_id = story.create_new_story(title) page_name = 'page_{}'.format(page) pdf_writer = PdfHandler(page_name, user_id) pdf_writer.set_document_title('Acknowledgement') file_path = pdf_writer.write_document(acknowledgement) page_num = 0 return story.save_document_path(str(story_id), file_path, str(page_num), 'acknowledgement')
def run_once(debug=True): # Randomly assigns actors, places, and items for story root_state = random_state(4, 4) # Initialize Root Node - Possible Methods boolean MUST BE TRUE root_node = TreeNode(root_state, parent_edge=None, possible_methods=True) # Total methods in story num_methods = len(root_node.possible_methods) """ The following max_numsim = max_expansion * thres max_iter : Number of sentances in story = number of story nodes - 1 = number of story edges max_expansion : Number of expansions in search max_simlength : Maximum length of rollout C : Exploration Constant for selection thres : Minimum MCTS Visits for node expansion """ # Perform Monte Carlo - returns final node and whole story max_expansion = 250 if max_expansion < len(root_node.possible_methods): raise ValueError( "Max exp ({}) should be greater than num methods({})".format( max_expansion, len(root_node.possible_methods))) max_iter = 15 max_simlength = 20 C = 1 thres = 40 minlambda = 0.95 s = Story(root_node) print(s.create_expository()) #print("Max iteration: {}\nMax Expansion: {}\nMax simulation length: {}\nC: {}\nThreshold: {}".format(max_iter, max_expansion, max_simlength, C, thres)) n, s = mcts(root_node, max_iter, max_expansion, max_simlength, C, thres, mixlambda, debug=False) # Print out results #if debug: # print(s) # print(n.believability) # print(n.value) # print(percent_goals_satisfied(n, GOALS)) return (n, s)
def random(session): # useful only when you have a lot of stories (obviously) days = range((datetime.now() - session.birthday).days + 1) for i in range(25): # try 25 times _story_exists, date = session.find_stories(session.birthday + timedelta(rchoice(days))) if not date: break story = Story(session, date) if story.get_path(): return story.view() print ERROR, "Looks like you don't have much stories in the given location!"
def runStory(): #play avatar t = threading.Thread(target = avatar_player.run_avatar) t.daemon = True t.start() time.sleep(2) #create story from nodes and player story_line = getStory() if story_line == None: return player = Player(story_line) story = Story(player, story_line) #run through the story story.walk(player)
def runStory(): global win #play avatar t = threading.Thread(target = run_avatar) t.daemon = True t.start() time.sleep(2) #create story from nodes and player story_line = getStory() if story_line != None: player = Player(story_line) story = Story(player, story_line) #run through the story story.walk(player) win.minimize()
def __init__(self, filename): keys = ['storyFile', 'dataFile'] with open(filename, 'r') as f: for line in f: line = line.split('#', maxsplit=1)[0] if line.strip() == '': continue key, value = line.split(maxsplit=1) if key in keys: setattr(self, key.strip(), value.strip()) self.story = Story(self.storyFile) self.background = self.story.startBackground self.speaker = '' self.text = '' self.options = [] self.optionResults = {} self.firstGrey = 0 self.data = {} self.curScene = self.story[self.story.startScene] self.curSceneName = self.story.startScene self.load()
def main(): """Load data, display data""" args = arg_parser_setup() clubhouse_apikey = get_clubhouse_apikey_or_exit() ch_api = ClubHouseAPI(clubhouse_apikey) cycle_logic = CycleLogic() if args.googlesheets: cycle_logic.enable_google_sheets_output( sheet_id=SHEET_ID, scopes=SCOPES, service_account_file=GOOGLE_SERVICE_ACCOUNT_FILE ) members = ch_api.get_active_members() progress_bar = ProgressBar(total=len(members)) for i, member in enumerate(members): progress_bar.print_progress_bar(i+1) cycle_logic.add_member(member) stories = ch_api.stories_by_mention(member['profile']['mention_name']) for ch_story in stories: story = Story(load_from_dict=ch_story, owner_id=member['id']) cycle_logic.add_story(story) print('\n\n') print(cycle_logic.tabulate_result(debug_member=args.debugmember))
def publish_news(context: CallbackContext): try: response = get(JSON_URL) json = response.json() except Exception as e: logger.error("Failed to connect to gambe.ro. Skipping.") return storage = TelegramStorage() latest = storage.load() if latest: new_stories = get_new_stories(latest, json) else: new_stories = [Story.from_json_dict(json[0])] if len(new_stories) == 0: logger.info("No new stories found since last check") else: for story in new_stories: text = TelegramStoryFormatter().format_string(story) try: context.bot.send_message(chat_id=CHAT_ID, text=text, parse_mode="html") except Exception: logging.getLogger(__name__).error( f"Failed connection for story: {story}\n" f"Caused by:\n{traceback.format_exc()}") storage.save(new_stories[-1])
def main(): try: pleroma = login() except MastodonError: logger.error("login failed", exc_info=True) return except KeyError: logger.error("login failed", exc_info=True) return logger.debug("Logged in") try: response = get(JSON_URL) json = response.json() except Exception as e: logger.error("Failed to connect to gambe.ro. Skipping.") return logger.debug("Downloaded stories") storage = PleromaStorage() latest = storage.load() if latest: new_stories = get_new_stories(latest, json) else: new_stories = [Story.from_json_dict(json[0])] if len(new_stories) == 0: logger.info("No new stories found since last check") else: for story in new_stories: text = PleromaStoryFormatter().format_string(story) pleroma.status_post(status=text, content_type="text/html") storage.save(new_stories[-1])
def main(): # Creates bot bot = API(auth) logger.info("Checking for new posts...") # Fetches website to get new stories in JSON try: response = get(JSON_URL) json = response.json() except Exception as e: logger.error("Failed to connect to gambe.ro. Skipping.") return # Fetches Twitter for the last published stories last_posted_tweet = None new_stories = [] try: last_posted_tweet = get_last_posted_tweet(bot) new_stories = get_new_stories(last_posted_tweet, json) # If is not possible to retrieve last tweet gets only the latest story on the website except ValueError: new_stories = [Story.from_json_dict(json[0])] # Tweets all the new stories if (len(new_stories) == 0): logger.info("Nothing new here, the bot is back to sleep.") else: for story in new_stories: tweet: str = None try: tweet = TwitterStoryFormatter().format_string(story) bot.update_status(tweet) logger.info(f"Tweeted: {tweet}") except ValueError: logger.critical("Unable to post tweet") except TweepError: print_exc()
def py_search(session, date_start, date_end, word): occurrences, errors, no_stories, = [], 0, 0 start = timer() date_iter = DateIterator(date_start, date_end) for i, day in date_iter: occurred, story = [], Story(session, day) try: if not story.get_path(): no_stories += 1 continue data = story.decrypt() # AssertionError (if any) is caught here idx, jump, data_len = 0, len(word), len(data) # probably an inefficient way to find the word indices while idx < data_len: idx = data.find(word, idx) if idx == -1: break occurred.append(idx) idx += jump except AssertionError: errors += 1 if errors > 10: print ERROR, "More than 10 files couldn't be decrypted! Terminating the search..." return [], (timer() - start) if occurred and occurred[0] > 0: # "i" indicates the Nth day from the birthday occurrences.append((i, len(occurred), occurred)) sum_value = sum(map(lambda stuff: stuff[1], occurrences)) date_iter.send_msg('[Found: %d]' % sum_value) assert no_stories < (i + 1) return occurrences, (timer() - start)
def test_failing (): formatter = TelegramStoryFormatter() s = Story(title="failing_title"*500, story_url="https://someurl.com", discussion_url="https://someurl2.com", author="author", created_at=None, tags=[]) with pytest.raises(ValueError): formatter.format_string(s)
def __init__(self, **kwargs): super(EditScreen, self).__init__(**kwargs) self.d = None self.init_node_select_dropdown() self.story = Story() self.current_node = None self.refresh_btn.bind(on_release=self.refresh_graph) self.current_file = ''
def step(self): # Create an event in a random node # Allow nearby agents to perceive the event (distance = 0, 1, 2?) # We want to set up the frequency of world.step() so that the world is # not swarmed with new stories ... relative frequencey of world.step() to agent.step() # needs to be tweaked newStory = Story(self, self.getRandomNode(), None) self.stories[story.id()] = newStory
def _load_stories(): for subdir, dirs, files in os.walk('stories/'): for dir in dirs: try: s = Story.from_dir('stories/' + dir) stories[s.slug] = s except StoryError as e: print e.message
def write_page(self, text: str, page: str, user_id: str) -> any: story = Story(user_id) page_name = 'page_{}'.format(page) pdf_writer = PdfHandler(page_name, user_id) story_id = story.get_story_id_for_user() filepath = pdf_writer.write_document(text) story.save_progress(story_id, page, 'body') story.save_document_path(story_id, filepath, page, 'text') story.save_content(story_id, page, text) return True
def find_stories(self, date_start=None, return_on_first_story=True): ''' Find the dates corresponding to stories that exist in a given location (by default, returns on the first encountered story that exists) ''' date_start = date_start if date_start else self.birthday if return_on_first_story: for i, date in DateIterator(date_start, progress_msg=None): if Story(self, date).get_path(): return (i is 0, date) return False, None # getting the list of stories is an exhaustive process and should be considered as the last resort return [ date for _i, date in DateIterator(date_start, progress_msg=None) if Story(self, date).get_path() ]
def playground(story: Story): encoded = encoder.encode_story(story) with open('test.json', 'w') as f: f.write(encoded) decoded = decoder.decode_story(encoded, story.store()) player.cli_player(decoded)
def create_list_html(): with open( '/home/peter/python/first_flask_homework/templates/list.html', 'w') as f: f.write("<!DOCTYPE html>\n") f.write("<html lang='en'>\n") f.write("<head>\n") f.write("<meta charset='UTF-8'>\n") f.write("<title>Super Sprinter 3000</title>\n") f.write("</head>\n") f.write("<body>\n") f.write("<h2>Super Sprinter 3000</h2>\n") f.write("<form action='story'>\n") f.write("<input type='submit' value='Add a new user story' />\n") f.write("</form>\n") f.write("<p>\n") f.write("<table>\n") column_name = [ "ID", "Story", "User Story", "Acceptance Criteria", "Business Value", "Estimation", "Status" ] Create_html.print_separator_line(f, len(column_name)) f.write("<tr>\n") f.write("<th>|</th>\n") for element in column_name: f.write("<th>" + element + "</th>\n") f.write("<th>|</th>\n") f.write("</tr>\n") Create_html.print_separator_line(f, len(column_name)) story = Story.select() for element in story: f.write("<tr>\n") column_element = [ str(element.id), element.title, element.description, element.acceptance_criteria, str(element.business_value), str(element.estimation_hour), element.status ] f.write("<th>|</th>\n") for element in column_element: f.write("<th>" + element + "</th>\n") f.write("<th>|</th>\n") f.write( "<th><a href='story/" + str(column_element[0]) + "'><img src='quill.gif' alt='pen' height='15' width='15'/></a></th>\n" ) f.write( "<th><a href='delete/" + str(column_element[0]) + "'><img src='bin.jpg' alt='bin' height='15' width='15'/></a></th>\n" ) f.write("</tr>\n") Create_html.print_separator_line(f, len(column_name)) f.write("</table>\n") f.write("</p>\n") f.write("</body>\n") f.write("</html>\n")
def _decode_basic_node(node_dict, story: Story) -> Node: node = story.create_node(node_dict['title']) node.set_text(node_dict['text']) for req in node_dict['requirements']: node.add_requirement(_decode_var_command(req)) for change in node_dict['changes']: node.add_change(_decode_var_command(change)) return node
def get_top_stories(number, offset): url = "https://hacker-news.firebaseio.com/v0/topstories.json" r = requests.get(url) story_ids = r.json()[offset:number+offset] stories = [] for s in story_ids: url = "https://hacker-news.firebaseio.com/v0/item/" + str(s) + ".json" r = requests.get(url) stories.append(Story(r.json())) return pretty_print(stories, offset)
def print_csv(api, issues): stories = [] for issue in issues: if not issue_has_fields(issue): continue story = Story( issue["fields"]["issuetype"]["name"], issue["key"], issue["fields"]["summary"], issue["fields"]["customfield_10016"] ) get_issue_history(api, story, issue) stories.append(story) first_line = f"type,board,key,summary,start,end,status_changes,in_ready," first_line += f"in_progress,in_testing,in_completed,estimate,total_time_sum," first_line += f"total_time_diff,difference" print(first_line) for story in stories: story.print_csv()
def pop_story(self): cursor = self.con.cursor() query = "select * from stories_all where is_full <> 1 order by updated_at desc, created_at desc limit 1" cursor.execute(query) contents = cursor.fetchone() str = Story(id=contents[0], created_at=contents[4], updated_at=contents[5], content=json.loads(contents[2])) return str
def loadOrSave(self): app = App.get_running_app().root print(app.current) if app.current == "load": if self.memento: app.currentStory = Story(self.memento.folder, self.memento.stateId) app.current = "game" else: # save current game self.memento = StoryMemento(story=app.currentStory)
def build_paths(session, date_start, date_end): path_list = [] for _i, day in DateIterator(date_start, date_end, 'Building the path list... %s'): file_path = Story(session, day).get_path() if file_path: path_list.append(file_path) assert path_list path_list.append(session.key) return path_list
def get_stories(self): if not self.stories: self.fill_metadata() # WARNING: hard coded class names tofind1, tofind2 = 'bb', 't-t84 bb nobck' self.stories = self.p.findAll('a', {'class': tofind1}) self.stories += self.p.findAll('a', {'class': tofind2}) self.stories = [x['href'][28:] for x in self.stories] self.stories = [Story(story_id) for story_id in self.stories] return self.stories
def go(self): title = self.textBoxes["Title"].get("1.0", 'end-1c') author = self.textBoxes["Author"].get("1.0", 'end-1c') publisher = self.textBoxes["Publisher"].get("1.0", 'end-1c') copyright = self.textBoxes["Copyright"].get("1.0", 'end-1c') newStory = Story(title, author, self.path, copyright, publisher) chapterTitles = self.checkBoxes["Titles"] self.formatter.chapterNames = bool(self.var.get()) self.formatter.take(newStory) self.running = True self.formatThread = thread.start_new_thread(self.formatter.run, ())
def py_stats(session): # FIXME: shares a lot of code with `py_search` - refactor them out! word_count, no_stories = 0, 0 date_iter = DateIterator(date_start = session.birthday) for i, day in date_iter: try: story = Story(session, day) if not story.get_path(): no_stories += 1 continue data = story.decrypt() word_count += simple_counter(data) date_iter.send_msg('[Total words: %s]' % word_count) except AssertionError: errors += 1 if errors > 10: print ERROR, "More than 10 files couldn't be decrypted! Terminating the search..." return None assert no_stories < (i + 1) return word_count
def extract_story(self, e): link = e.xpath('link') #if link: print link[0].attrib['href'] #get node attrib url = link and link[0].get('href', '') if not url: return None story = Story(url) title = e.xpath('title') story.title = title and title[0].text summary = e.xpath('summary') or e.xpath('content') story.summary = strip_tags(summary and summary[0].text) categories = e.xpath('category') published = e.xpath('published') updated = e.xpath('updated') author = e.xpath('author') # compound data: name, etc. #if author: # name = author[0].xpath('name') # if name: print name[0].text source = e.xpath('source') # compound data return story
def run_through_story(story_doc): s = Story(story_doc) s.start() while True: try: story_state = s.eval_current_node() s.enact(story_state['autoact']) except StoryExited: break return s
def test_set_state_var_1(): story_doc = {'start_node': 'start', 'story': [{'id': 'start', 'scene': {'autoact': {'set': {'var': 'foo', 'val': 23}, 'goto': 'end'}}}, {'id': 'end', 'special': 'exit'}]} s = Story(story_doc) s.start() while True: try: story_state = s.eval_current_node() s.enact(story_state['autoact']) except StoryExited: break assert s.get_state_var('foo') == 23
def load_stories(self): db = sqlite3.connect('model/news.db') c = db.cursor() c.execute("SELECT id,title,date,category,story FROM news") news_table = c.fetchall() for story in news_table: c.execute("SELECT id,source,url,headline,story FROM sources WHERE id=?", [story[0]]) story_sources = c.fetchall() sources = [] for source in story_sources: sources.append(Source(source[1],source[2],source[3],source[4])) s = Story() s.id = story[0] s.title = story[1] s.date = story[2] s.category = story[3] s.story = story[4] s.sources = sources self.stories.append(s) c.close()
def zoo_story_factory(): s = Story(input_fct=get_input, workspace_id=actions.WKSPACE_ID) s.add_node(actions.entrance, start=True) s.add_node(actions.wallet) s.add_node(actions.parking_lot) exhibits = [actions.monkeys, actions.elephants, actions.lions, actions.tigers, actions.penguins, actions.otters, actions.pandas] exhibits = random.sample(exhibits, 4) for exhibit in exhibits: s.add_node(exhibit) dir_edges = [(actions.entrance, exhibit) for exhibit in exhibits] dir_edges += [(exhibit, actions.parking_lot) for exhibit in exhibits] dir_edges.append((actions.wallet, actions.parking_lot)) undir_edges = [] # the exhibits are fully connected for i, v in enumerate(exhibits): for w in exhibits[i+1:]: undir_edges.append((v, w)) s.add_edges_from(dir_edges) s.add_undirected_edges_from(undir_edges) s.node[actions.entrance]['dynamic_events'][actions.wallet] = 0.01 context = {'name': None, 'remaining': [e.__name__ for e in exhibits]} s.update_context(context) return s
def process(path): if not os.path.exists(path): print '%s not exists' % path return if os.path.isfile(path): return process_file(path) for dir_path, subpaths, filenames in os.walk(path): for filename in filenames: process_file(os.path.join(dir_path, filename)) if __name__ == '__main__': parser = OptionParser() parser.add_option('-i', "--input", dest="path", help="input file, or path") parser.add_option("-l", "--list", action="store_true", dest="list_stories", default=False, help="list stories") parser.add_option("-p", "--parse", action="store_true", dest="parse_stories", default=False, help="parse stories from input") (options, args) = parser.parse_args() if options.parse_stories: process(options.path) elif options.list_stories: stories = Story.get_all() for story in stories: if not story.url: print '-' * 80 print 'no link'
def setUp(self): self.s = Story()
class StoryTests(unittest.TestCase): def setUp(self): self.s = Story() def tearDown(self): del self.s def test_add_node(self): self.s.add_node('a') self.assertTrue('a' in self.s) self.s.add_node(1) self.assertFalse(1 in self.s) self.assertTrue('1' in self.s) l = ['b', 'c', 'd'] self.s.add_nodes_from(l) for c in l: self.assertTrue(c in self.s) self.assertTrue('a' in self.s) self.assertTrue('1' in self.s) def test_add_edge(self): self.s.add_node('a') self.s.add_node('b') self.s.add_edge('a', 'b') self.assertTrue('a' in self.s) self.assertTrue('b' in self.s) self.assertTrue('b' in self.s.neighbors('a')) self.assertFalse('a' in self.s.neighbors('b')) self.s.add_edge('c', 'd') self.assertTrue('c' in self.s) self.assertTrue('d' in self.s) self.assertTrue('d' in self.s.neighbors('c')) self.assertFalse('c' in self.s.neighbors('d')) ebunch = [('b', 'c'), ('d', 'e')] self.s.add_edges_from(ebunch) self.assertTrue('e' in self.s) def test_add_undir_edge(self): self.s.add_node('a') self.s.add_node('b') self.s.add_undirected_edge('a', 'b') self.assertTrue('a' in self.s) self.assertTrue('b' in self.s) self.assertTrue('b' in self.s.neighbors('a')) self.assertTrue('a' in self.s.neighbors('b')) self.s.add_undirected_edge('c', 'd') self.assertTrue('c' in self.s) self.assertTrue('d' in self.s) self.assertTrue('d' in self.s.neighbors('c')) self.assertTrue('c' in self.s.neighbors('d')) ebunch = [('b', 'c'), ('d', 'e')] self.s.add_undirected_edges_from(ebunch) self.assertTrue('e' in self.s) def test_set_current(self): with self.assertRaises(StoryError): self.s.current = 'a' self.s.add_node('a') self.s.current = 'a' self.assertTrue('a' in self.s.visited) self.assertTrue(self.s.current == 'a') def test_add_actions(self): self.s.add_node('a') s1 = 'This is a test message' self.s.add_say('a', message=s1) s2 = 'Fake message' self.s.add_say('a', message=s2) actions = self.s.node['a']['actions'] self.assertTrue(actions == [{'type': 'say', 'kwargs': {'message': s1}}, {'type': 'say', 'kwargs': {'message': s2}}]) def test_run_conditions1(self): l = ['a', 'b', 'c'] self.s.add_nodes_from(l) self.s.require_visit('b', 'a') self.s.require_visit('c', 'a', 'b') self.assertFalse('a' in self.s.visited) condition = self.s.run_conditions('b')[0] self.assertFalse(condition()) condition = self.s.run_conditions('c')[0] self.assertFalse(condition()) self.s.current = 'a' condition = self.s.run_conditions('b')[0] self.assertTrue(condition()) condition = self.s.run_conditions('c')[0] self.assertFalse(condition()) self.s.current = 'b' condition = self.s.run_conditions('c')[0] self.assertTrue(condition()) def test_run_conditions2(self): l = ['a', 'b', 'c', 'd'] self.s.add_nodes_from(l) self.s.context = {'apples': 5} self.s.check_context_for('b', 'apples') self.s.check_context_for('c', apples=6) self.s.check_context_for('d', 'oranges') condition = self.s.run_conditions('b')[0] self.assertTrue(condition()) condition = self.s.run_conditions('c')[0] self.assertFalse(condition()) condition = self.s.run_conditions('d')[0] self.assertFalse(condition()) updated_context = {'apples': 6, 'oranges': 0} self.s.update_context(updated_context) condition = self.s.run_conditions('b')[0] self.assertTrue(condition()) condition = self.s.run_conditions('c')[0] self.assertTrue(condition()) condition = self.s.run_conditions('d')[0] self.assertTrue(condition()) def test_context(self): d = {'a': 1, 'b': 2} self.s.context = d self.assertTrue(self.s.context == d) self.assertFalse(self.s.context is d) def test_run(self): # test empty self.s() l = ['a', 'b', 'c', 'd'] self.s.add_nodes_from(l) self.s.add_edge('a', 'b') self.s.add_edge('a', 'c') self.s.add_edge('c', 'd') self.s.current = 'a' path = ['c', 'd'] path_iter = iter(path) current = iter(path) dummy_input = lambda: next(path_iter) while not self.s.is_finished: self.s.input_fct = dummy_input self.s() self.assertTrue(self.s.current == next(current)) '''
def add_story(self, title, date, category, story, sources): #db = sqlite3.connect('model/news.db') #c = db.cursor() #c.execute("insert into news (title,date,category,story) values (?,?,?,?)", (title,date,category,story)) #id = c.lastrowid #for source in sources: # c.execute("insert into sources (id,source,url,headline,story) values (?,?,?,?,?)", (id,source.name,source.url,source.headline,source.story)) #db.commit() #c.close() story_instance = Story() story_instance.set_id(id) story_instance.set_title(title) story_instance.set_date(date) story_instance.set_story(story) for source in sources: story_instance.add_source(source) self.stories.append(story_instance)
def reconfigure(self): # FIXME: Could take arguments via command-line? '''Reset the diary's configuration''' try: self._reset() self.delete_config_file() clear_screen() print "\nLet's start configuring your diary...\n", \ '\nEnter the location for your diary...', \ "\n(Note that this will create a foler named 'Diary' if the path doesn't end with it)" self.location = os.path.expanduser(raw_input('\nPath: ')) while not write_access(self.location): self.location = os.path.expanduser(raw_input('\nPlease enter a valid path: ')) if not self.location.rstrip(os.sep).endswith('Diary'): # just put everything in a folder for Diary self.location = os.path.join(self.location, 'Diary') print '(Reminding you that this will make use of %r)' % self.location if not os.path.exists(self.location): os.mkdir(self.location) self.location = self.location.rstrip(os.sep) + os.sep while True: try: # 'birthday' of the diary is important because random stories and searching is based on that birth = raw_input('''\ \nWhen did you start writing this diary? (Press [Enter] for today)\ \nDate should be of the form YYYY-MM-DD (Mind you, with hyphen!) \nDate: ''') # FIXME: just ask the year and 'infer' from the location if not birth: self.birthday, life_time = datetime.now(), 'new' break else: self.birthday, life_time = datetime.strptime(birth, '%Y-%m-%d'), 'old' first_story_exists, date = self.find_stories() if first_story_exists: break elif date: print ERROR, "Your 'first' story doesn't exist!", \ date.strftime('However, a story exists on %B %d, %Y (%A)\n') if raw_input('Do you wanna begin from there (y), or go for another date (n)? ') == 'y': self.birthday = date break else: print ERROR, "A story doesn't exist (in the given path) on that day!" continue except ValueError: print ERROR, 'Oops! ERROR in input. Check the date format and try again...' while True: self.get_pass(life_time = life_time) first_story = Story(self, self.birthday) try: if first_story.get_path(): _data = first_story.decrypt() break elif (datetime.now() - self.birthday).days: # 'unreachable' because this should've already been handled raise Exception, 'Entered unreachable code!' else: # first-timer... break except AssertionError: print ERROR, "Couldn't decrypt your 'first' story with the given password! Try again..." self.write_to_config_file() self.loop = True print "\nIf you plan to reconfigure it manually, then it's located here (%s)" % self.config_location print "And, be careful with that, because invalid configuration files will be deleted during startup!" raw_input('\nPress [Enter] to continue...') except (KeyboardInterrupt, EOFError): sleep(CAPTURE_WAIT) if not all([self.location, self.key, self.birthday, self.loop]): print '\n', ERROR, "Failed to store the login credentials!" if os.path.exists(self.config_location): os.remove(self.config_location) self._reset()
class EditScreen(Screen): # dropdown_wid = ObjectProperty() dropdown_btn_wid = ObjectProperty() node_info_wid = ObjectProperty() refresh_btn = ObjectProperty() storyboard_wid = ObjectProperty() def __init__(self, **kwargs): super(EditScreen, self).__init__(**kwargs) self.d = None self.init_node_select_dropdown() self.story = Story() self.current_node = None self.refresh_btn.bind(on_release=self.refresh_graph) self.current_file = '' def init_node_select_dropdown(self): self.d = d = DropDown() b = Button(text='Add a node...', size_hint_y=None, height=dp(30)) b.bind(on_release=self.show_add_popup) d.add_widget(b) d.bind(on_select=lambda _, text: setattr(self.dropdown_btn_wid, 'text', text)) self.dropdown_btn_wid.bind(on_release=d.open) def show_file_browser(self, action): p = FileBrowserPopup() def update_current_file(instance, text): self.current_file = p.current_path + '/' + text.strip() if action == 'save as': p.filename_inp.bind(text=update_current_file) p.action_btn.text = 'Save' def save(button): self.save_current() p.dismiss() p.action_btn.bind(on_release=save) p.open() elif action == 'load': p.action_btn.text = 'Load' def load(button): path = p.selected_file self.load_story(path) p.dismiss() p.action_btn.bind(on_release=load) p.open() def save_current(self): if self.current_file: filename = self.current_file.strip() # check whether user has appended '.story' filename extension filename = filename.split('.') if len(filename) == 1 or filename[-1] != 'story': filename.append('story') filename = '.'.join(filename) print(filename) with open(filename, 'w') as f: pickle.dump(self.story, f) else: self.show_file_browser('save as') def load_story(self, path): # TODO: check whether current file is saved with open(path, 'r') as f: try: obj = pickle.load(f) except IOError as e: print(str(e)) return if isinstance(obj, Story): self.story = obj else: # TODO: display helpful message return for node in self.story: b = Button(text=node, size_hint_y=None, height=dp(30)) b.bind(on_release=self.show_info_callback) self.d.add_widget(b) self.refresh_graph() def check_current_file(self): board = self.ids['board'] if board.current_file: board.save_story(board.current_file) else: self.show_file_chooser() def refresh_graph(self, *args): g = self.story plt.clf() nx.draw_networkx(g, node_size=2000, font_size=dp(16), node_shape=',') curr_axes = plt.gca() curr_axes.axes.get_xaxis().set_visible(False) curr_axes.axes.get_yaxis().set_visible(False) buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) image = CoreImage(buf, ext='png') self.storyboard_wid.texture = image.texture def show_add_popup(self, button): # show the add popup p = AddNodePopup(attach_to=self) p.open() def add_callback(button): """Add the node to the story and update the dropdown menu """ self.d.dismiss() node_name = p.node_name self.story.add_node(node_name) print(self.story.nodes()) p.dismiss() # update the dropdown menu b = Button(text=node_name, size_hint_y=None, height=dp(30)) b.bind(on_release=self.show_info_callback) self.d.add_widget(b) p.submit_btn_wid.bind(on_release=add_callback) def show_info_callback(self, button): """Shows the node information in the sidebar """ self.current_node = button.text self.d.select(button.text) # p.dismiss() node_info = self.node_info_wid node_info.clear_widgets() node_info.add_widget(Label(text='name:')) # TODO: allow node renaming? node_info.add_widget(TextInput(text=button.text, multiline=False)) node_info.add_widget(Label(text='actions:')) actions_b = Button(text='edit...') actions_b.bind(on_release=self.show_add_action_popup) node_info.add_widget(actions_b) node_info.add_widget(Label(text='destinations:')) dest_b = Button(text='edit...') dest_b.bind(on_release=self.show_add_dest_popup) node_info.add_widget(dest_b) node_info.add_widget(Label(text='origins:')) orig_b = Button(text='edit...') orig_b.bind(on_release=self.show_add_origin_popup) node_info.add_widget(orig_b) def show_add_action_popup(self, button): p = AddActionPopup(existing_actions=self.story.get_actions(self.current_node), attach_to=self) p.open() def add_action_callback(button): a = Action() p.add_action(a) # p.actions_list_wid.add_widget(a) # p.actions_temp.append(a) def update_story(action): if action.action_type == 'say': self.story.add_say(self.current_node, **action.parameters) elif action.action_type == 'listen': self.story.add_listen(self.current_node, **action.parameters) elif action.action_type == 'play': self.story.add_play(self.current_node, **action.parameters) def save_callback(button): actions = p.actions_temp for action in actions: update_story(action) p.dismiss() p.add_action_btn_wid.bind(on_release=add_action_callback) p.save_btn.bind(on_release=save_callback) def show_add_dest_popup(self, button): p = AddEdgePopup(title='Add destinations') valid_dest = self.story.nodes() valid_dest.remove(self.current_node) for dest in valid_dest: b = ToggleButton(text=dest, size_hint_y=None, height=dp(30)) if dest in self.story.neighbors(self.current_node): b.state = 'down' p.node_list.add_widget(b) p.node_list.add_widget(Widget()) def save_callback(button): to_add = [] to_remove = [] for child in p.node_list.children: if isinstance(child, ToggleButton): node_name = child.text if child.state == 'down': to_add.append(node_name) else: to_remove.append(node_name) for node in to_add: if node not in self.story.neighbors(self.current_node): self.story.add_edge(self.current_node, node) for node in to_remove: if node in self.story.neighbors(self.current_node): self.story.remove_edge(self.current_node, node) p.dismiss() p.save_btn.bind(on_release=save_callback) p.open() def show_add_origin_popup(self, button): p = AddEdgePopup(title='Add origins') valid_orig = self.story.nodes() valid_orig.remove(self.current_node) for orig in valid_orig: b = ToggleButton(text=orig, size_hint_y=None, height=dp(30)) if orig in self.story.predecessors(self.current_node): b.state = 'down' p.node_list.add_widget(b) p.node_list.add_widget(Widget()) def save_callback(button): to_add = [] to_remove = [] for child in p.node_list.children: if isinstance(child, ToggleButton): node_name = child.text if child.state == 'down': to_add.append(node_name) else: to_remove.append(node_name) for node in to_add: if node not in self.story.predecessors(self.current_node): self.story.add_edge(node, self.current_node) for node in to_remove: if node in self.story.predecessors(self.current_node): self.story.remove_edge(node, self.current_node) p.dismiss() p.save_btn.bind(on_release=save_callback) p.open()
def __init__(self, story_file = 'story.json'): self.repl_commands = ['history', 'load', 'save', 'restart'] self.story = Story(story_file) self.pretext() self.story.start()
class REPL: def __init__(self, story_file = 'story.json'): self.repl_commands = ['history', 'load', 'save', 'restart'] self.story = Story(story_file) self.pretext() self.story.start() def load_game(self, savegame_file = 'autosave.json'): self.story.load_state() def save_game(self, savegame_file = 'autosave.json'): self.story.save_state() def restart_game(self): self.story.start() def pretext(self): print() title = self.story.get_metadata('title') print(title) print('-'*len(title)) print() print("By %s" % (self.story.get_metadata('author'), )) print() def repl_command(self, cmd_str): repl_command = cmd_str.split(' ') if repl_command[0] == 'history': # FIXME: Story should have an interface to access the history history = self.story.state['__history'] if len(repl_command) == 1: print("History so far:") pprint(history) else: try: n = int(repl_command[1]) print("Last %d history entries:" % (n, )) pprint(history[-n:]) except ValueError: print("Usage: history <n>") elif repl_command[0] == 'load': self.load_game() elif repl_command[0] == 'save': self.save_game() elif repl_command[0] == 'restart': self.restart_game() def loop(self): skip_eval = False while True: try: if not skip_eval: current_node = self.story.eval_current_node() presentation = current_node.get('presentation', False) actables = current_node.get('actables', False) autoacts = current_node.get('autoact', False) else: skip_eval = False if presentation: for line in textwrap.wrap(presentation['text']): print(line) if actables: for act_id in range(0, len(actables)): print("%d) %s" % (act_id+1, actables[act_id]['text'])) if autoacts and not actables: self.story.enact(autoacts) else: cmd = input('> ') if len(cmd)>0 and cmd.split(' ')[0] in self.repl_commands: self.repl_command(cmd) elif cmd=="a": # FIXME: Make sure that autoact exists, otherwise reprompt self.story.enact(autoacts) elif cmd=='?': pprint(current_node) skip_eval = True else: try: # FIXME: Make sure that answer is in range, otherwise reprompt cmd_id = int(cmd)-1 except ValueError: pass # FIXME: Reprompt (What was entered wasn't an int) if cmd_id > len(actables): pass # FIXME: Reprompt (list is too long) self.story.enact(actables[cmd_id]['result']) except StoryExited: break except EOFError: # Ctrl-D in input() print() print("See you later, hope you had a good time!") print() break