prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>test_DataSeriesLoader.py<|end_file_name|><|fim▁begin|>import unittest from datetime import datetime import numpy as np import pandas as pd from excel_helper.helper import DataSeriesLoader class TestDataFrameWithCAGRCalculation(unittest.TestCase): def test_simple_CAGR(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) res = dfl['static_one'] print (res) assert res.loc[[datetime(2009, 1, 1)]][0] == 1 assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 def test_CAGR_ref_date_within_bounds(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) res = dfl['static_one'] assert res.loc[[datetime(2009, 1, 1)]][0] == 1 assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 def test_CAGR_ref_date_before_start(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) # equivalent to dfl['test_ref_date_before_start'] self.assertRaises(AssertionError, dfl.__getitem__, 'test_ref_date_before_start') def test_CAGR_ref_date_after_end(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) # equivalent to dfl['test_ref_date_before_start'] self.assertRaises(AssertionError, dfl.__getitem__, 'test_ref_date_after_end') def <|fim_middle|>(self): times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') xls = pd.ExcelFile('test.xlsx') df = xls.parse('Sheet1') ldr = DataSeriesLoader.from_dataframe(df, times, size=2) res = ldr['static_one'] assert res.loc[[datetime(2009, 1, 1)]][0] == 1 assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 def test_simple_CAGR_mm(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2015-01-01', '2016-01-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) res = dfl['mm'] print(res) # assert res.loc[[datetime(2009, 1, 1)]][0] == 1 # assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 if __name__ == '__main__': unittest.main() <|fim▁end|>
test_simple_CAGR_from_pandas
<|file_name|>test_DataSeriesLoader.py<|end_file_name|><|fim▁begin|>import unittest from datetime import datetime import numpy as np import pandas as pd from excel_helper.helper import DataSeriesLoader class TestDataFrameWithCAGRCalculation(unittest.TestCase): def test_simple_CAGR(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) res = dfl['static_one'] print (res) assert res.loc[[datetime(2009, 1, 1)]][0] == 1 assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 def test_CAGR_ref_date_within_bounds(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) res = dfl['static_one'] assert res.loc[[datetime(2009, 1, 1)]][0] == 1 assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 def test_CAGR_ref_date_before_start(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) # equivalent to dfl['test_ref_date_before_start'] self.assertRaises(AssertionError, dfl.__getitem__, 'test_ref_date_before_start') def test_CAGR_ref_date_after_end(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) # equivalent to dfl['test_ref_date_before_start'] self.assertRaises(AssertionError, dfl.__getitem__, 'test_ref_date_after_end') def test_simple_CAGR_from_pandas(self): times = pd.date_range('2009-01-01', '2009-04-01', freq='MS') xls = pd.ExcelFile('test.xlsx') df = xls.parse('Sheet1') ldr = DataSeriesLoader.from_dataframe(df, times, size=2) res = ldr['static_one'] assert res.loc[[datetime(2009, 1, 1)]][0] == 1 assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 def <|fim_middle|>(self): """ Basic test case, applying CAGR to a Pandas Dataframe. :return: """ # the time axis of our dataset times = pd.date_range('2015-01-01', '2016-01-01', freq='MS') # the sample axis our dataset samples = 2 dfl = DataSeriesLoader.from_excel('test.xlsx', times, size=samples, sheet_index=0) res = dfl['mm'] print(res) # assert res.loc[[datetime(2009, 1, 1)]][0] == 1 # assert np.abs(res.loc[[datetime(2009, 4, 1)]][0] - pow(1.1, 3. / 12)) < 0.00001 if __name__ == '__main__': unittest.main() <|fim▁end|>
test_simple_CAGR_mm
<|file_name|>conf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Backend.AI Library documentation build configuration file, created by # sphinx-quickstart on Tue Mar 1 21:26:20 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os on_rtd = os.environ.get('READTHEDOCS') == 'True' # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = ['.rst'] # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Backend.AI API Documentation' copyright = '2015-2020, Lablup Inc.' author = 'Lablup Inc.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = 'v5.20191215' # The full version, including alpha/beta/rc tags. release = '20.03' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] <|fim▁hole|># The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'tango' highlight_language = 'python3' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False numfig = True intersphinx_mapping = { 'client-py': ('https://client-py.docs.backend.ai/en/latest/', None), } # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'BackendAIAPIDoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'BackendAIDoc.tex', 'Backend.AI API Documentation', author, 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'backend.ai', 'Backend.AI API Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Backend.AI', 'Backend.AI API Documentation', author, 'Backend.AI', 'Backend.AI is a hassle-free backend for AI programming and service.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '':<|fim▁hole|> return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False)<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): <|fim_middle|> class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
"""A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: <|fim_middle|> index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members'
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): <|fim_middle|> def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): <|fim_middle|> class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore <|fim_middle|> # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): <|fim_middle|> name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. <|fim_middle|> <|fim▁end|>
instance.image.delete(False)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': <|fim_middle|> else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
return 'javascript:void(0)'
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: <|fim_middle|> def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
return self.social_link
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def <|fim_middle|>(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
get_social_link
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def <|fim_middle|>(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
__str__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def <|fim_middle|>(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
__str__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def <|fim_middle|>(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) <|fim▁end|>
compsoc_member_delete
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>"<|fim▁hole|> #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main()<|fim▁end|>
extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")]
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): <|fim_middle|> #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
""" Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output)
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): <|fim_middle|> def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
Paste(text).execute()
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): <|fim_middle|> def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
return self.get_recognition_info(node)
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): <|fim_middle|> #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output)
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): <|fim_middle|> #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")]
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): <|fim_middle|> #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")]
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): <|fim_middle|> #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))]
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect()
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: <|fim_middle|> return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
output.append(" - {0}: {1}".format(key, extra_node.value()))
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
main()
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def <|fim_middle|>(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
_process_recognition
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def <|fim_middle|>(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
value
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def <|fim_middle|>(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
get_recognition_info
<|file_name|>test_multiple_dictation.py<|end_file_name|><|fim▁begin|>""" Multiple dictation constructs =============================================================================== This file is a showcase investigating the use and functionality of multiple dictation elements within Dragonfly speech recognition grammars. The first part of this file (i.e. the module's doc string) contains a description of the functionality being investigated along with test code and actual output in doctest format. This allows the reader to see what really would happen, without needing to load the file into a speech recognition engine and put effort into speaking all the showcased commands. The test code below makes use of Dragonfly's built-in element testing tool. When run, it will connect to the speech recognition engine, load the element being tested, mimic recognitions, and process the recognized value. Multiple consecutive dictation elements ------------------------------------------------------------------------------- >>> tester = ElementTester(RuleRef(ConsecutiveDictationRule())) >>> print(tester.recognize("consecutive Alice Bob Charlie")) Recognition: "consecutive Alice Bob Charlie" Word and rule pairs: ("1000000" is "dgndictation") - consecutive (1) - Alice (1000000) - Bob (1000000) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("consecutive Alice Bob")) RecognitionFailure Mixed literal and dictation elements ------------------------------------------------------------------------------- Here we will investigate mixed, i.e. interspersed, fixed literal command words and dynamic dictation elements. We will use the "MixedDictationRule" class which has a spec of "mixed [<dictation1>] <dictation2> command <dictation3>". Note that "<dictation1>" was made optional instead of "<dictation2>" because otherwise the first dictation elements would always gobble up all dictated words. There would (by definition) be no way to distinguish which words correspond with which dictation elements. Such consecutive dictation elements should for that reason be avoided in real command grammars. The way the spec is defined now, adds some interesting dynamics, because of the order in which they dictation elements parse the recognized words. However, do note that that order is well defined but arbitrarily chosen. >>> tester = ElementTester(RuleRef(MixedDictationRule())) >>> print(tester.recognize("mixed Alice Bob command Charlie")) Recognition: "mixed Alice Bob command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - Bob (1000000) - command (1) - Charlie (1000000) Extras: - dictation1: Alice - dictation2: Bob - dictation3: Charlie >>> print(tester.recognize("mixed Alice command Charlie")) Recognition: "mixed Alice command Charlie" Word and rule pairs: ("1000000" is "dgndictation") - mixed (1) - Alice (1000000) - command (1) - Charlie (1000000) Extras: - dictation2: Alice - dictation3: Charlie >>> print(tester.recognize("mixed Alice Bob command")) RecognitionFailure >>> print(tester.recognize("mixed command Charlie")) RecognitionFailure Repetition of dictation elements ------------------------------------------------------------------------------- Now let's take a look at repetition of dictation elements. For this we will use the "RepeatedDictationRule" class, which defines its spec as a repetition of "command <dictation>". I.e. "command Alice" will match, and "command Alice command Bob" will also match. Note that this rule is inherently ambiguous, given the lack of a clear definition of grouping or precedence rules for fixed literal words in commands, and dynamic dictation elements. As an example, "command Alice command Bob" could either match 2 repetitions with "Alice" and "Bob" as dictation values, or a single repetition with "Alice command Bob" as its only dictation value. The tests below the show which of these actually occurs. >>> tester = ElementTester(RuleRef(RepeatedDictationRule())) >>> print(tester.recognize("command Alice")) Recognition: "command Alice" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice)]] >>> print(tester.recognize("command Alice command Bob")) Recognition: "command Alice command Bob" Word and rule pairs: ("1000000" is "dgndictation") - command (1) - Alice (1000000) - command (1000000) - Bob (1000000) Extras: - repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]] """ #--------------------------------------------------------------------------- import doctest from dragonfly import * from dragonfly.test.infrastructure import RecognitionFailure from dragonfly.test.element_testcase import ElementTestCase from dragonfly.test.element_tester import ElementTester #--------------------------------------------------------------------------- class RecognitionAnalysisRule(CompoundRule): """ Base class that implements reporting in human-readable format details about the recognized phrase. It is used by the actual testing rules below, and allows the doctests above to be easily readable and informative. """ def _process_recognition(self, node, extras): Paste(text).execute() def value(self, node): return self.get_recognition_info(node) def get_recognition_info(self, node): output = [] output.append('Recognition: "{0}"'.format(" ".join(node.words()))) output.append('Word and rule pairs: ("1000000" is "dgndictation")') for word, rule in node.full_results(): output.append(" - {0} ({1})".format(word, rule)) output.append("Extras:") for key in sorted(extra.name for extra in self.extras): extra_node = node.get_child_by_name(key) if extra_node: output.append(" - {0}: {1}".format(key, extra_node.value())) return "\n".join(output) #--------------------------------------------------------------------------- class ConsecutiveDictationRule(RecognitionAnalysisRule): spec = "consecutive <dictation1> <dictation2> <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class MixedDictationRule(RecognitionAnalysisRule): spec = "mixed [<dictation1>] <dictation2> command <dictation3>" extras = [Dictation("dictation1"), Dictation("dictation2"), Dictation("dictation3")] #--------------------------------------------------------------------------- class RepeatedDictationRule(RecognitionAnalysisRule): spec = "<repetition>" extras = [Repetition(name="repetition", child=Sequence([Literal("command"), Dictation()]))] #--------------------------------------------------------------------------- def <|fim_middle|>(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect() if __name__ == "__main__": main() <|fim▁end|>
main
<|file_name|>test_grids.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 from __future__ import print_function, division import numpy as np from sht.grids import standard_grid, get_cartesian_grid def test_grids(): L = 10 thetas, phis = standard_grid(L) # Can't really test much here assert thetas.size == L assert phis.size == L**2 <|fim▁hole|><|fim▁end|>
grid = get_cartesian_grid(thetas, phis) assert grid.shape == (L**2, 3)
<|file_name|>test_grids.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 from __future__ import print_function, division import numpy as np from sht.grids import standard_grid, get_cartesian_grid def test_grids(): <|fim_middle|> <|fim▁end|>
L = 10 thetas, phis = standard_grid(L) # Can't really test much here assert thetas.size == L assert phis.size == L**2 grid = get_cartesian_grid(thetas, phis) assert grid.shape == (L**2, 3)
<|file_name|>test_grids.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 from __future__ import print_function, division import numpy as np from sht.grids import standard_grid, get_cartesian_grid def <|fim_middle|>(): L = 10 thetas, phis = standard_grid(L) # Can't really test much here assert thetas.size == L assert phis.size == L**2 grid = get_cartesian_grid(thetas, phis) assert grid.shape == (L**2, 3) <|fim▁end|>
test_grids
<|file_name|>squareplot.py<|end_file_name|><|fim▁begin|># Simple plotter for Gut books. # All this does is draw a sqare for every stat in the input # and color it based on the score. # # Another fine example of how Viz lies to you. You will # need to fudge the range by adjusting the clipping. import numpy as np import matplotlib.pyplot as plt import sys as sys if len(sys.argv) <2: print "Need an input file with many rows of 'id score'\n" sys.exit(1) fname = sys.argv[1] vals = np.loadtxt(fname) ids = vals[:,0] score = vals[:,1] score_max = 400; #max(score) #score_max = max(score) score = np.clip(score, 10, score_max) score = score/score_max # want 3x1 ratio, so 3n*n= 30824 (max entries), horiz=3n=300 NUM_COLS=300 fig = plt.figure(figsize=(12,9)) ax = fig.add_subplot(111) ax.set_axis_bgcolor('0.50') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for i in range(len(vals)): #print i, ids[i] row = int(ids[i]) / NUM_COLS col = int(ids[i]) % NUM_COLS cval = score[i] #score[i]*score[i] # Square the values to drop the lower end cmap = plt.get_cmap('hot') val = cmap(cval) ax.add_patch(plt.Rectangle((col,row),1,1,color=val)); #, cmap=plt.cm.autumn)) ax.set_aspect('equal')<|fim▁hole|>print cmap(0.9) plt.xlim([0,NUM_COLS]) plt.ylim([0,1+int(max(ids))/NUM_COLS]) plt.show()<|fim▁end|>
print cmap(0.1)
<|file_name|>squareplot.py<|end_file_name|><|fim▁begin|># Simple plotter for Gut books. # All this does is draw a sqare for every stat in the input # and color it based on the score. # # Another fine example of how Viz lies to you. You will # need to fudge the range by adjusting the clipping. import numpy as np import matplotlib.pyplot as plt import sys as sys if len(sys.argv) <2: <|fim_middle|> fname = sys.argv[1] vals = np.loadtxt(fname) ids = vals[:,0] score = vals[:,1] score_max = 400; #max(score) #score_max = max(score) score = np.clip(score, 10, score_max) score = score/score_max # want 3x1 ratio, so 3n*n= 30824 (max entries), horiz=3n=300 NUM_COLS=300 fig = plt.figure(figsize=(12,9)) ax = fig.add_subplot(111) ax.set_axis_bgcolor('0.50') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for i in range(len(vals)): #print i, ids[i] row = int(ids[i]) / NUM_COLS col = int(ids[i]) % NUM_COLS cval = score[i] #score[i]*score[i] # Square the values to drop the lower end cmap = plt.get_cmap('hot') val = cmap(cval) ax.add_patch(plt.Rectangle((col,row),1,1,color=val)); #, cmap=plt.cm.autumn)) ax.set_aspect('equal') print cmap(0.1) print cmap(0.9) plt.xlim([0,NUM_COLS]) plt.ylim([0,1+int(max(ids))/NUM_COLS]) plt.show() <|fim▁end|>
print "Need an input file with many rows of 'id score'\n" sys.exit(1)
<|file_name|>wrapper_head_tail.py<|end_file_name|><|fim▁begin|>import sys import petsc4py petsc4py.init(sys.argv) from ecoli_in_pipe import head_tail # import numpy as np # from scipy.interpolate import interp1d # from petsc4py import PETSc # from ecoli_in_pipe import single_ecoli, ecoliInPipe, head_tail, ecoli_U # from codeStore import ecoli_common # # # def call_head_tial(uz_factor=1., wz_factor=1.): # PETSc.Sys.Print('') # PETSc.Sys.Print('################################################### uz_factor = %f, wz_factor = %f' % # (uz_factor, wz_factor)) # t_head_U = head_U.copy() # t_tail_U = tail_U.copy() # t_head_U[2] = t_head_U[2] * uz_factor # t_tail_U[2] = t_tail_U[2] * uz_factor # # C1 = t_head_U[5] - t_tail_U[5] # # C2 = t_head_U[5] / t_tail_U[5] # # t_head_U[5] = wz_factor * C1 * C2 / (wz_factor * C2 - 1) # # t_tail_U[5] = C1 / (wz_factor * C2 - 1) # t_head_U[5] = wz_factor * t_head_U[5] # t_kwargs = {'head_U': t_head_U, # 'tail_U': t_tail_U, } # total_force = head_tail.main_fun() # return total_force # # # OptDB = PETSc.Options() # fileHandle = OptDB.getString('f', 'ecoliInPipe') # OptDB.setValue('f', fileHandle)<|fim▁hole|># tail_U = np.array([0, 0, 1, 0, 0, 1]) # call_head_tial() head_tail.main_fun()<|fim▁end|>
# main_kwargs = {'fileHandle': fileHandle} # # head_U, tail_U, ref_U = ecoli_common.ecoli_restart(**main_kwargs) # # ecoli_common.ecoli_restart(**main_kwargs) # head_U = np.array([0, 0, 1, 0, 0, 1])
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False<|fim▁hole|> prev_tx = tx_bytes if __name__ == "__main__": main()<|fim▁end|>
start_time, prev_tx = time, tx_bytes else: print (time-start_time), (tx_bytes-prev_tx)
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: <|fim_middle|> with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes if __name__ == "__main__": main() <|fim▁end|>
print "Error: No input file"
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: <|fim_middle|> else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes if __name__ == "__main__": main() <|fim▁end|>
if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): <|fim_middle|> else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes if __name__ == "__main__": main() <|fim▁end|>
no_traffic_flag = False start_time, prev_tx = time, tx_bytes
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes else: <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
main()
<|file_name|>sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, argparse def <|fim_middle|>(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes if __name__ == "__main__": main() <|fim▁end|>
main
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date:<|fim▁hole|> c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main()<|fim▁end|>
c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d"))
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): <|fim_middle|> def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords <|fim_middle|> def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename)
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
sign_pdf(parser.parse_args())
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature <|fim_middle|> writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page)
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: <|fim_middle|> c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d"))
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: <|fim_middle|> if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
handle.close()
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: <|fim_middle|> def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
os.remove(sig_tmp_filename)
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
main()
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def <|fim_middle|>(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
_get_tmp_filename
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def <|fim_middle|>(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
sign_pdf
<|file_name|>signpdf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature file (png, jpg)") parser.add_argument("--date", action='store_true') parser.add_argument("--output", nargs='?', help="Output file. Defaults to input filename plus '_signed'") parser.add_argument("--coords", nargs='?', default='2x100x100x125x40', help="Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch).") def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def <|fim_middle|>(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main() <|fim▁end|>
main
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, include, url from django.views.generic import TemplateView home = TemplateView.as_view(template_name='home.html') urlpatterns = patterns( '',<|fim▁hole|> # An informative homepage. url(r'', home, name='home') )<|fim▁end|>
url(r'^filter/', include('demoproject.filter.urls')),
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id)<|fim▁hole|> return { 'type': 'file', 'content': content, 'format': format, }<|fim▁end|>
content, format = self._read_file(os_checkpoint_path, format=None)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): <|fim_middle|> class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
""" A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) )
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): <|fim_middle|> # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
try: return self.parent.root_dir except AttributeError: return getcwd()
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): <|fim_middle|> def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): <|fim_middle|> # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): <|fim_middle|> def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): <|fim_middle|> def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): <|fim_middle|> # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)]
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): <|fim_middle|> def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): <|fim_middle|> # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): <|fim_middle|> class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) )
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): <|fim_middle|> <|fim▁end|>
""" Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, }
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): <|fim_middle|> def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): <|fim_middle|> def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): <|fim_middle|> def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
"""Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), }
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): <|fim_middle|> <|fim▁end|>
"""Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, }
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): <|fim_middle|> def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): <|fim_middle|> self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
self.no_such_checkpoint(path, checkpoint_id)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): <|fim_middle|> else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
return []
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: <|fim_middle|> # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
return [self.checkpoint_model(checkpoint_id, os_path)]
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): <|fim_middle|> return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
self.no_such_checkpoint(path, checkpoint_id)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): <|fim_middle|> content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
self.no_such_checkpoint(path, checkpoint_id)
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def <|fim_middle|>(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
_root_dir_default
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def <|fim_middle|>(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
create_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def <|fim_middle|>(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
restore_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def <|fim_middle|>(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
rename_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def <|fim_middle|>(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
delete_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def <|fim_middle|>(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
list_checkpoints
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def <|fim_middle|>(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
checkpoint_path
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def <|fim_middle|>(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
checkpoint_model
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def <|fim_middle|>(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
no_such_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def <|fim_middle|>(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
create_file_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def <|fim_middle|>(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
create_notebook_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def <|fim_middle|>(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def get_file_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
get_notebook_checkpoint
<|file_name|>filecheckpoints.py<|end_file_name|><|fim▁begin|>""" File-based Checkpoints implementations. """ import os import shutil from tornado.web import HTTPError from .checkpoints import ( Checkpoints, GenericCheckpointsMixin, ) from .fileio import FileManagerMixin from IPython.utils import tz from IPython.utils.path import ensure_dir_exists from IPython.utils.py3compat import getcwd from IPython.utils.traitlets import Unicode class FileCheckpoints(FileManagerMixin, Checkpoints): """ A Checkpoints that caches checkpoints for files in adjacent directories. Only works with FileContentsManager. Use GenericFileCheckpoints if you want file-based checkpoints with another ContentsManager. """ checkpoint_dir = Unicode( '.ipynb_checkpoints', config=True, help="""The directory name in which to keep file checkpoints This is a path relative to the file's own directory. By default, it is .ipynb_checkpoints """, ) root_dir = Unicode(config=True) def _root_dir_default(self): try: return self.parent.root_dir except AttributeError: return getcwd() # ContentsManager-dependent checkpoint API def create_checkpoint(self, contents_mgr, path): """Create a checkpoint.""" checkpoint_id = u'checkpoint' src_path = contents_mgr._get_os_path(path) dest_path = self.checkpoint_path(checkpoint_id, path) self._copy(src_path, dest_path) return self.checkpoint_model(checkpoint_id, dest_path) def restore_checkpoint(self, contents_mgr, checkpoint_id, path): """Restore a checkpoint.""" src_path = self.checkpoint_path(checkpoint_id, path) dest_path = contents_mgr._get_os_path(path) self._copy(src_path, dest_path) # ContentsManager-independent checkpoint API def rename_checkpoint(self, checkpoint_id, old_path, new_path): """Rename a checkpoint from old_path to new_path.""" old_cp_path = self.checkpoint_path(checkpoint_id, old_path) new_cp_path = self.checkpoint_path(checkpoint_id, new_path) if os.path.isfile(old_cp_path): self.log.debug( "Renaming checkpoint %s -> %s", old_cp_path, new_cp_path, ) with self.perm_to_403(): shutil.move(old_cp_path, new_cp_path) def delete_checkpoint(self, checkpoint_id, path): """delete a file's checkpoint""" path = path.strip('/') cp_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(cp_path): self.no_such_checkpoint(path, checkpoint_id) self.log.debug("unlinking %s", cp_path) with self.perm_to_403(): os.unlink(cp_path) def list_checkpoints(self, path): """list the checkpoints for a given file This contents manager currently only supports one checkpoint per file. """ path = path.strip('/') checkpoint_id = "checkpoint" os_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_path): return [] else: return [self.checkpoint_model(checkpoint_id, os_path)] # Checkpoint-related utilities def checkpoint_path(self, checkpoint_id, path): """find the path to a checkpoint""" path = path.strip('/') parent, name = ('/' + path).rsplit('/', 1) parent = parent.strip('/') basename, ext = os.path.splitext(name) filename = u"{name}-{checkpoint_id}{ext}".format( name=basename, checkpoint_id=checkpoint_id, ext=ext, ) os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): ensure_dir_exists(cp_dir) cp_path = os.path.join(cp_dir, filename) return cp_path def checkpoint_model(self, checkpoint_id, os_path): """construct the info dict for a given checkpoint""" stats = os.stat(os_path) last_modified = tz.utcfromtimestamp(stats.st_mtime) info = dict( id=checkpoint_id, last_modified=last_modified, ) return info # Error Handling def no_such_checkpoint(self, path, checkpoint_id): raise HTTPError( 404, u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id) ) class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints): """ Local filesystem Checkpoints that works with any conforming ContentsManager. """ def create_file_checkpoint(self, content, format, path): """Create a checkpoint from the current content of a file.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_file(os_checkpoint_path, content, format=format) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def create_notebook_checkpoint(self, nb, path): """Create a checkpoint from the current content of a notebook.""" path = path.strip('/') # only the one checkpoint ID: checkpoint_id = u"checkpoint" os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) self.log.debug("creating checkpoint for %s", path) with self.perm_to_403(): self._save_notebook(os_checkpoint_path, nb) # return the checkpoint info return self.checkpoint_model(checkpoint_id, os_checkpoint_path) def get_notebook_checkpoint(self, checkpoint_id, path): """Get a checkpoint for a notebook.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) return { 'type': 'notebook', 'content': self._read_notebook( os_checkpoint_path, as_version=4, ), } def <|fim_middle|>(self, checkpoint_id, path): """Get a checkpoint for a file.""" path = path.strip('/') self.log.info("restoring %s from checkpoint %s", path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) content, format = self._read_file(os_checkpoint_path, format=None) return { 'type': 'file', 'content': content, 'format': format, } <|fim▁end|>
get_file_checkpoint
<|file_name|>HELP.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
print("hello!!!!")
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json')<|fim▁hole|> for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))<|fim▁end|>
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): <|fim_middle|> <|fim▁end|>
def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): <|fim_middle|> def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid))))) <|fim▁end|>
invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)]
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): <|fim_middle|> <|fim▁end|>
cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: <|fim_middle|> s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid))))) <|fim▁end|>
invalid.append(p) continue